File Coverage

File:lib/CheckSpelling/UnknownWordSplitter.pm
Coverage:79.1%

linestmtbrancondsubtimecode
1#! -*-perl-*-
2
3# ~/bin/w
4# Search for potentially misspelled words
5# Output is:
6# misspellled
7# woord (WOORD, Woord, woord, woord's)
8package CheckSpelling::UnknownWordSplitter;
9
10
1
1
109424
3
use 5.022;
11
1
1
1
2
0
52
use feature 'unicode_strings';
12
1
1
1
2
2
7
use strict;
13
1
1
1
1
0
21
use warnings;
14
1
1
1
1
0
16
no warnings qw(experimental::vlb);
15
1
1
1
1
1
2
use utf8;
16
1
1
1
13
0
23
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
30
use File::Basename;
18
1
1
1
1
1
14
use Cwd 'abs_path';
19
1
1
1
2
0
20
use File::Spec;
20
1
1
1
1
1
16
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
0
14
use File::Path qw/ make_path /;
22
1
1
1
284
18
21
use CheckSpelling::Util;
23
1
1
1
209
1223
811
use Digest::SHA;
24our $VERSION='0.1.0';
25
26my ($longest_word, $shortest_word, $word_match, $forbidden_re, $patterns_re, $candidates_re, $disable_word_collating, $check_file_names);
27my ($check_homoglyphs);
28my ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
29my ($shortest, $longest) = (255, 0);
30my @forbidden_re_list;
31my %forbidden_re_descriptions;
32my @candidates_re_list;
33my $hunspell_dictionary_path;
34my @hunspell_dictionaries;
35my %dictionary = ();
36our @reject_re_list = ();
37our $reject_re = '$^';
38my $base_dict;
39my %unique;
40my %unique_unrecognized;
41my ($last_file, $words, $unrecognized) = ('', 0, 0);
42my ($ignore_next_line_pattern);
43my ($check_images, $ocr_directory);
44
45my $disable_flags;
46
47sub test_re {
48
14
12
  my ($expression) = @_;
49
14
14
5
108
  return eval { qr /$expression/ };
50}
51
52sub quote_re {
53
14
14
  my ($expression) = @_;
54
14
14
  return $expression if $expression =~ /\?\{/;
55
14
30
  $expression =~ s/
56   \G
57   (
58      (?:[^\\]|\\[^Q])*
59   )
60   (?:
61      \\Q
62      (?:[^\\]|\\[^E])*
63      (?:\\E)?
64   )?
65/
66
28
46
   $1 . (defined($2) ? quotemeta($2) : '')
67/xge;
68
14
14
  return $expression;
69}
70
71sub file_to_lists {
72
3
3
  my ($re) = @_;
73
3
4
  my @patterns;
74  my %hints;
75
3
0
  my $fh;
76
3
30
  if (open($fh, '<:utf8', $re)) {
77
3
6
    local $/=undef;
78
3
24
    my $file=<$fh>;
79
3
9
    close $fh;
80
3
2
    my $line_number = 0;
81
3
7
    my $hint = '';
82
3
14
    for (split /\R/, $file) {
83
17
8
      ++$line_number;
84
17
12
      chomp;
85
17
20
      if (/^#(?:\s(.+)|)/) {
86
6
13
        $hint = $1 if ($hint eq '' && defined $1);
87
6
5
        next;
88      }
89
11
15
      $hint = '' unless $_ ne '';
90
11
13
      next if $_ eq '$^';
91
11
6
      my $pattern = $_;
92
11
32
      next unless s/^(.+)/(?:$1)/;
93
7
9
      my $quoted = quote_re($1);
94
7
11
      unless (test_re $quoted) {
95
1
2
        my $error = $@;
96
1
53
        my $home = dirname(__FILE__);
97
1
28
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
98
1
11
        print STDERR $error;
99
1
1
        $_ = '(?:\$^ - skipped because bad-regex)';
100
1
1
        $hint = '';
101      }
102
7
12
      if (defined $hints{$_}) {
103
1
2
        my $pattern_length = length $pattern;
104
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
105
1
16
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
106
1
2
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
107      } else {
108
6
5
        push @patterns, $_;
109
6
11
        $hints{$_} = $hint;
110      }
111
7
9
      $hint = '';
112    }
113  }
114
115  return {
116
3
15
    patterns => \@patterns,
117    hints => \%hints,
118  };
119}
120
121sub file_to_list {
122
2
1336
  my ($re) = @_;
123
2
6
  my $lists = file_to_lists($re);
124
125
2
2
3
8
  return @{$lists->{'patterns'}};
126}
127
128sub list_to_re {
129
2
2
  my (@list) = @_;
130
2
5
5
2
3
4
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
131
2
5
1
5
  @list = grep { $_ ne '' } @list;
132
2
2
  return '$^' unless scalar @list;
133
2
6
  return join "|", (@list);
134}
135
136sub not_empty {
137
76
61
  my ($thing) = @_;
138
76
347
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
139}
140
141sub valid_word {
142  # shortest_word is an absolute
143
22
14
  our ($shortest, $longest, $shortest_word, $longest_word);
144
22
23
  $shortest = $shortest_word if $shortest_word;
145
22
22
  if ($longest_word) {
146    # longest_word is an absolute
147
20
26
    $longest = $longest_word;
148  } elsif (not_empty($longest)) {
149    # we allow for some sloppiness (a couple of stuck keys per word)
150    # it's possible that this should scale with word length
151
1
1
    $longest += 2;
152  }
153
22
18
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
154
22
66
22
171
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
155
22
26
  $word_pattern = q<\\w|'> unless $word_pattern;
156
22
58
  if ((defined $shortest && not_empty($longest)) &&
157      ($shortest > $longest)) {
158
0
0
    $word_pattern = "(?:$word_pattern){3}";
159
0
0
    return qr/$word_pattern/;
160  }
161
22
27
  $shortest = 3 unless defined $shortest;
162
22
19
  $longest = '' unless not_empty($longest);
163
22
76
  $word_match = "(?:$word_pattern){$shortest,$longest}";
164
22
223
  return qr/\b$word_match\b/;
165}
166
167sub load_dictionary {
168
12
1824
  my ($dict) = @_;
169
12
5
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
170
12
12
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
171
12
11
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
172
12
4
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
173
12
14
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
174
12
47
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
175
12
25
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
176
12
25
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
177
12
23
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
178
12
27
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
179
12
21
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
180
12
35
  if ($check_homoglyphs && $check_homoglyphs !~ /false/i) {
181
11
9
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
182
11
74
    if (-s $homoglyph_list_path) {
183
1
1
1
310
1
3314
      use CheckSpelling::Homoglyph;
184
11
17
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
185    } else {
186
0
0
      $check_homoglyphs = 0;
187    }
188  } else {
189
1
0
    $check_homoglyphs = 0;
190  }
191
12
18
  %dictionary = ();
192
193
12
379
  open(my $dict_fh, '<:utf8', $dict);
194
12
17
  my $word_match_relaxed = $word_match;
195
12
68
  if ($word_match =~ /\{(\d+),/) {
196
12
13
    my $three = $1;
197
12
16
    if ($three > 1) {
198
12
8
      my $two = $three - 1;
199
12
85
      $word_match_relaxed =~ s/\b$three\b/$two/g;
200    }
201  }
202
12
56
  while (!eof($dict_fh)) {
203
32
35
    my $word = <$dict_fh>;
204
32
24
    chomp $word;
205
32
124
    next unless $word =~ $word_match_relaxed;
206
31
32
    my $l = length $word;
207
31
17
    $longest = -1 unless not_empty($longest);
208
31
35
    $longest = $l if $l > $longest;
209
31
64
    if ($word =~ $word_match) {
210
29
26
      $shortest = $l if $l < $shortest;
211    }
212
31
63
    $dictionary{$word}=1;
213  }
214
12
33
  close $dict_fh;
215
216
12
10
  $word_match = valid_word();
217}
218
219sub hunspell_dictionary {
220
3
6
  my ($dict) = @_;
221
3
3
  my $name = $dict;
222
3
5
  $name =~ s{/src/index/hunspell/index\.dic$}{};
223
3
14
  $name =~ s{.*/}{};
224
3
5
  my $aff = $dict;
225
3
5
  my $encoding;
226
3
11
  $aff =~ s/\.dic$/.aff/;
227
3
36
  if (open my $aff_fh, '<', $aff) {
228
3
22
    while (<$aff_fh>) {
229
0
0
      next unless /^SET\s+(\S+)/;
230
0
0
      $encoding = $1 if ($1 !~ /utf-8/i);
231
0
0
      last;
232    }
233
3
9
    close $aff_fh;
234  }
235  return {
236
3
350
    name => $name,
237    dict => $dict,
238    aff => $aff,
239    encoding => $encoding,
240    engine => Text::Hunspell->new($aff, $dict),
241  }
242}
243
244sub init {
245
9
10989
  my ($configuration) = @_;
246
9
9
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
247
9
27
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
248
9
16
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
249
9
16
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
250
9
4
  our %forbidden_re_descriptions;
251
9
7
  our @reject_re_list;
252
9
3
  our $reject_re;
253
9
12
  if ($hunspell_dictionary_path) {
254
3
38
    our @hunspell_dictionaries = ();
255
1
1
1
1
1
1
1
1
1
3
331
1163
20
5
2
14
7
0
17
206
    if (eval 'use Text::Hunspell; 1') {
256
3
125
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
257
3
10
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
258
3
20
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
259      }
260    } else {
261
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
262    }
263  }
264
9
13
  my (@patterns_re_list, %in_patterns_re_list);
265
9
60
  if (-e "$configuration/patterns.txt") {
266
0
0
    @patterns_re_list = file_to_list "$configuration/patterns.txt";
267
0
0
    $patterns_re = list_to_re @patterns_re_list;
268
0
0
0
0
    %in_patterns_re_list = map {$_ => 1} @patterns_re_list;
269  } else {
270
9
8
    $patterns_re = undef;
271  }
272
273
9
43
  if (-e "$configuration/forbidden.txt") {
274
1
2
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
275
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
276
1
1
1
5
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
277
1
2
    $forbidden_re = list_to_re @forbidden_re_list;
278  } else {
279
8
8
    $forbidden_re = undef;
280  }
281
282
9
52
  if (-e "$configuration/candidates.txt") {
283
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
284
1
2
2
1
1
4
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
285
1
2
    $candidates_re = list_to_re @candidates_re_list;
286  } else {
287
8
5
    $candidates_re = undef;
288  }
289
290
9
43
  if (-e "$configuration/reject.txt") {
291
0
0
    @reject_re_list = file_to_list "$configuration/reject.txt";
292
0
0
0
0
0
0
    @reject_re_list = map { my $quoted = quote_re($_); !test_re($quoted) ? '' : '^'.$quoted.'$' } @reject_re_list;
293
0
0
    $reject_re = list_to_re @reject_re_list;
294  } else {
295
9
14
    $reject_re = '$^';
296  }
297
298
9
10
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
299
300
9
8
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
301
9
11
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
302
9
4
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
303
9
8
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
304
305
9
6
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
306
9
7
  $ignore_next_line_pattern =~ s/\s+/|/g;
307
308
9
8
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
309
9
6
  $check_images = $check_images =~ /^(?:1|true)$/i;
310
9
9
  if ($check_images) {
311
0
0
    our $ocr_directory = CheckSpelling::Util::get_file_from_env('ocr_directory', '/tmp/ocr');
312
0
0
    $ocr_directory = $1 if ($ocr_directory =~ /^(.*)$/);
313  }
314
315
9
7
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
316
317
9
9
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
318
319
9
13
  $word_match = valid_word();
320
321
9
50
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
322
9
44
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
323
9
10
  load_dictionary($base_dict);
324}
325
326sub split_line {
327
1159
473
  our (%dictionary, $word_match, $disable_word_collating);
328
1159
447
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
329
1159
429
  our @hunspell_dictionaries;
330
1159
419
  our $shortest;
331
1159
720
  my $shortest_threshold = $shortest + 2;
332
1159
557
  my $pattern = '.';
333  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
334
335  # https://www.fileformat.info/info/unicode/char/2019/
336
1159
497
  my $rsqm = "\xE2\x80\x99";
337
338
1159
591
  my ($words, $unrecognized) = (0, 0);
339
1159
790
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
340
1159
4591
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
341
1159
1946
    $line =~ s/(?:$ignore_pattern)+/ /g;
342
1159
1502
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
343
1159
2771
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
344
1159
1140
    for my $token (split /\s+/, $line) {
345
3631
2961
      next unless $token =~ /$pattern/;
346
2473
1927
      $token =~ s/^(?:'|$rsqm)+//g;
347
2473
2343
      $token =~ s/(?:'|$rsqm)+s?$//g;
348
2473
1329
      my $raw_token = $token;
349
2473
1279
      $token =~ s/^[^Ii]?'+//; # need to reconsider for French
350
2473
1170
      $token =~ s/'+$//;
351
2473
3572
      next unless $token =~ $word_match;
352
2316
1909
      if (defined $dictionary{$token}) {
353
1036
450
        ++$words;
354
1036
572
        $unique_ref->{$token}=1;
355
1036
950
        next;
356      }
357
1280
781
      if (@hunspell_dictionaries) {
358
1254
641
        my $found = 0;
359
1254
689
        for my $hunspell_dictionary (@hunspell_dictionaries) {
360          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
361
1254
933
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
362
1254
2245
          next unless ($hunspell_dictionary->{'engine'}->check($token_encoded));
363
0
0
          ++$words;
364
0
0
          $dictionary{$token} = 1;
365
0
0
          $unique_ref->{$token}=1;
366
0
0
          $found = 1;
367
0
0
          last;
368        }
369
1254
815
        next if $found;
370      }
371
1280
801
      my $key = lc $token;
372
1280
1010
      if (defined $dictionary{$key}) {
373
6
3
        ++$words;
374
6
5
        $unique_ref->{$key}=1;
375
6
7
        next;
376      }
377
1274
784
      unless ($disable_word_collating) {
378
1274
649
        $key =~ s/''+/'/g;
379
1274
1056
        $key =~ s/'[sd]$// if length $key >= $shortest_threshold;
380      }
381
1274
940
      if (defined $dictionary{$key}) {
382
0
0
        ++$words;
383
0
0
        $unique_ref->{$key}=1;
384
0
0
        next;
385      }
386
1274
575
      ++$unrecognized;
387
1274
749
      $unique_unrecognized_ref->{$raw_token}=1;
388
1274
1623
      $unrecognized_line_items_ref->{$raw_token}=1;
389    }
390
1159
1445
    return ($words, $unrecognized);
391}
392
393sub skip_file {
394
7
29
  my ($temp_dir, $reason) = @_;
395
7
239
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
396
7
37
  print $skipped_fh $reason;
397
7
125
  close $skipped_fh;
398}
399
400sub maybe_ocr_file {
401
0
0
  my ($file) = @_;
402
0
0
  our $ocr_directory;
403
0
0
  my $ocr_file = "$ocr_directory/$file";
404
0
0
  $ocr_file =~ /^(.*)$/;
405
0
0
  $ocr_file = $1;
406
0
0
  my $ocr_source_sha = "$ocr_file.sha1";
407
0
0
  $ocr_file = "$ocr_file.txt";
408
0
0
  my $sha = Digest::SHA->new(1)->addfile($file, 'b')->hexdigest;
409
0
0
  if (-e $ocr_file &&
410      -e $ocr_source_sha &&
411      open my $source_sha, '<', $ocr_source_sha) {
412
0
0
    my $last_sha = <$source_sha>;
413
0
0
    close $source_sha;
414
0
0
    if ($last_sha =~ /(.*)/) {
415
0
0
      return ($ocr_file, 1) if ($1 eq $sha);
416    }
417  }
418
0
0
  my $tesseract = dirname(dirname(dirname(__FILE__)))."/wrappers/run-tesseract";
419
0
0
  $ENV{'input'} = $file;
420
0
0
  my $text_file = `"$tesseract"`;
421
0
0
  delete $ENV{'input'};
422
0
0
  return ($file, 0) unless defined $text_file;
423
0
0
  my $file_converted = 0;
424
0
0
  chomp $text_file;
425
0
0
  if ($text_file =~ /^(.*)$/) {
426
0
0
    $text_file = $1;
427
0
0
    my $file_size = -s $text_file || 0;
428
0
0
    if ($file_size > 20) {
429
0
0
      $file_converted = 1;
430
0
0
      make_path(dirname($ocr_source_sha));
431
0
0
      open my $source_sha, '>', $ocr_source_sha;
432
0
0
      print $source_sha $sha;
433
0
0
      close $source_sha;
434
0
0
      rename($text_file, $ocr_file);
435
0
0
      $file = $ocr_file;
436    } else {
437
0
0
      unlink($text_file);
438    }
439  }
440
0
0
  return ($file, $file_converted);
441}
442
443sub print_word_not_in_dictionary {
444
1274
706
  my ($warnings_fh, $begin, $end, $match) = @_;
445
1274
528
  our $reject_re;
446
1274
781
  my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
447
1274
1170
  if ($match =~ /^($reject_re)$/) {
448
0
0
    our @reject_re_list;
449
0
0
    my $found = 0;
450
0
0
    for my $reject (@reject_re_list) {
451
0
0
      if ($match =~ /^$reject$/) {
452
0
0
        my $rejection = CheckSpelling::Util::wrap_in_backticks($reject);
453
0
0
        print $warnings_fh ":$.:$begin ... $end, Error - Rejected word $wrapped matched $rejection (rejected-word)\n";
454
0
0
        $found = 1;
455      }
456    }
457
0
0
    unless ($found) {
458
0
0
      my $rejection = CheckSpelling::Util::wrap_in_backticks($reject_re);
459
0
0
      print $warnings_fh ":$.:$begin ... $end, Error - Rejected word $wrapped matched $rejection (rejected-word)\n";
460    }
461  } else {
462
1274
4418
    print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
463  }
464}
465
466sub split_file {
467
17
12932
  my ($file) = @_;
468  our (
469
17
10
    $unrecognized, $shortest, $largest_file, $words,
470    $word_match, %unique, %unique_unrecognized, $forbidden_re,
471    @forbidden_re_list, $patterns_re, %dictionary,
472    $candidates_re, @candidates_re_list, $check_file_names, $use_magic_file, $disable_minified_file,
473    $disable_single_line_file,
474    $ignore_next_line_pattern,
475    $sandbox,
476    $check_images,
477  );
478
17
42
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
479
480
17
7
  our %forbidden_re_descriptions;
481
17
11
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
482
483  # https://www.fileformat.info/info/unicode/char/2019/
484
17
12
  my $rsqm = "\xE2\x80\x99";
485
486
17
24
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
487
17
13
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
488
17
17
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
489
17
14
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
490
17
34
  my $temp_dir = tempdir(DIR=>$sandbox);
491
17
2869
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
492
17
436
  open(my $name_fh, '>', "$temp_dir/name");
493
17
37
    print $name_fh $file;
494
17
223
  close $name_fh;
495
17
228
  if (defined readlink($file) &&
496      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
497
1
2
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
498
1
3
    return $temp_dir;
499  }
500
16
24
  if ($use_magic_file) {
501
8
12645
    if (open(my $file_fh, '-|',
502              '/usr/bin/file',
503              '-b',
504              '--mime',
505              '-e', 'cdf',
506              '-e', 'compress',
507              '-e', 'csv',
508              '-e', 'elf',
509              '-e', 'json',
510              '-e', 'tar',
511              $file)) {
512
8
31822
      my $file_kind = <$file_fh>;
513
8
3943
      close $file_fh;
514
8
13
      my $file_converted = 0;
515
8
33
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
516
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
517      }
518
8
207
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
519
2
37
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
520
2
38
        return $temp_dir;
521      }
522    }
523  } elsif ($file =~ /\.(?:png|jpe?g|gif)$/) {
524
0
0
    my $file_converted = 0;
525
0
0
    ($file, $file_converted) = maybe_ocr_file($file);
526  }
527
14
93
  my $file_size = -s $file;
528
14
34
  if (defined $largest_file) {
529
14
22
    unless ($check_file_names eq $file) {
530
14
21
      if ($file_size > $largest_file) {
531
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
532
1
2
        return $temp_dir;
533      }
534    }
535  }
536
13
149
  open my $file_fh, '<', $file;
537
13
15
  binmode $file_fh;
538
13
8
  my $head;
539
13
127
  read($file_fh, $head, 4096);
540
13
827
  $head =~ s/(?:\r|\n)+$//;
541
13
62
  my $dos_new_lines = () = $head =~ /\r\n/gi;
542
13
33
  my $unix_new_lines = () = $head =~ /\n/gi;
543
13
150
  my $mac_new_lines = () = $head =~ /\r/gi;
544
13
59
  local $/;
545
13
110
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
546
3
7
    $/ = "\n";
547  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
548
1
5
    $/ = "\r\n";
549  } elsif ($mac_new_lines > $unix_new_lines) {
550
2
7
    $/ = "\r";
551  } else {
552
7
8
    $/ = "\n";
553  }
554
13
35
  seek($file_fh, 0, 0);
555
13
23
  ($words, $unrecognized) = (0, 0);
556
13
45
  %unique = ();
557
13
34
  %unique_unrecognized = ();
558
559  local $SIG{__WARN__} = sub {
560
0
0
    my $message = shift;
561
0
0
    $message =~ s/> line/> in $file - line/;
562
0
0
    chomp $message;
563
0
0
    print STDERR "$message\n";
564
13
132
  };
565
566
13
356
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
567
13
9
  our $timeout;
568
13
12
  eval {
569
13
0
109
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
570
13
38
    alarm $timeout;
571
572
13
18
    my $ignore_next_line = 0;
573
13
16
    my $offset = 0;
574
13
95
    while (<$file_fh>) {
575
1162
888
      if ($. == 1) {
576
13
24
        unless ($disable_minified_file) {
577
13
65
          if ($file_size >= 512 && length($_) == $file_size) {
578
1
9
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
579
1
5
            last;
580          }
581        }
582
12
38
        s/^\x{FEFF}//;
583      }
584
1161
1777
      $_ = decode_utf8($_, FB_DEFAULT);
585
1161
2359
      if (/[\x{D800}-\x{DFFF}]/) {
586
0
0
        skip_file($temp_dir, "file contains a UTF-16 surrogate -- UTF-16 surrogates are not supported (utf16-surrogate-file)\n");
587
0
0
        last;
588      }
589
1161
1260
      s/\R$//;
590
1161
1035
      next unless /./;
591
1160
742
      my $raw_line = $_;
592
593
1160
534
      my $ignore_this_line = $ignore_next_line;
594
1160
903
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
595
1160
699
      next if $ignore_this_line;
596
597      # hook for custom line based text exclusions:
598
1159
686
      if (defined $patterns_re) {
599
2
6
12
8
        s/($patterns_re)/"="x length($1)/ge;
600      }
601
1159
604
      my $initial_line_state = $_;
602
1159
628
      my $previous_line_state = $_;
603
1159
503
      my $line_flagged;
604
1159
701
      if ($forbidden_re) {
605
9
5
64
11
        while (s/($forbidden_re)/"="x length($1)/e) {
606
5
4
          $line_flagged = 1;
607
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
608
5
5
          my $found_trigger_re;
609
5
4
          for my $i (0 .. $#forbidden_re_list) {
610
7
4
            my $forbidden_re_singleton = $forbidden_re_list[$i];
611
7
5
            my $test_line = $previous_line_state;
612
7
4
58
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
613
4
4
              next unless $test_line eq $_;
614
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
615
4
4
              next unless $begin == $begin_test;
616
4
4
              next unless $end == $end_test;
617
4
2
              next unless $match eq $match_test;
618
4
5
              $found_trigger_re = $forbidden_re_singleton;
619
4
7
              my $hit = "$.:$begin:$end";
620
4
4
              $forbidden_re_hits[$i]++;
621
4
6
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
622
4
6
              last;
623            }
624          }
625
5
6
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
626
5
7
          if ($found_trigger_re) {
627
4
7
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
628
4
10
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
629
4
2
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
630
4
5
            if ($description ne '') {
631
3
14
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
632            } else {
633
1
6
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
634            }
635          } else {
636
1
3
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
637          }
638
5
26
          $previous_line_state = $_;
639        }
640
9
8
        $_ = $initial_line_state;
641      }
642      # This is to make it easier to deal w/ rules:
643
1159
1005
      s/^/ /;
644
1159
586
      my %unrecognized_line_items = ();
645
1159
473
      our $check_homoglyphs;
646
1159
657
      if ($check_homoglyphs) {
647
1159
625
        my $check_line_for_homoglyphs = $_;
648
1159
637
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
649        # problematic characters: `\\`, `-`, `]`
650
1159
11414
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
651
1159
1210
        $homoglyphs = "[$homoglyphs]";
652
1159
465
        our ($longest_word, $shortest_word);
653
1159
1549
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
654
1159
523
        my $dollar = '$';
655
1159
1449
        my $homoglyph_re = "(?=(?:${homoglyphs}|(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})){${shortest_word},${longest_word_string}}(?:${not_upper_or_lower_pattern}|${dollar}))((?:${upper_pattern}|${lower_pattern})+${homoglyphs}(?:(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})|${homoglyphs})*|${homoglyphs}+(?:${upper_pattern}|${lower_pattern})(?:(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})|${homoglyphs})*)";
656
1159
9915
        while ($check_line_for_homoglyphs =~ /((?=(?:${homoglyphs}|(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})){${shortest_word},${longest_word_string}}(?:${not_upper_or_lower_pattern}|${dollar}))((?:${upper_pattern}|${lower_pattern})+${homoglyphs}(?:(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})|${homoglyphs})*|${homoglyphs}+(?:${upper_pattern}|${lower_pattern})(?:(?:${upper_pattern}|${lower_pattern}|${punctuation_pattern})|${homoglyphs})*))/g) {
657
1
5
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
658
1
49
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
659
1
1
          if (defined $dictionary{$token}) {
660
1
1
            my $token_raw = CheckSpelling::Util::wrap_in_backticks($token_raw);
661
1
1
            my $token = CheckSpelling::Util::wrap_in_backticks($token);
662
1
1
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
663
1
16
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
664          }
665        }
666      }
667
1159
839
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
668
1159
587
      $words += $new_words;
669
1159
488
      $unrecognized += $new_unrecognized;
670
1159
688
      my $line_length = length($raw_line);
671
1159
1250
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
672
1021
447
        my $found_token = 0;
673
1021
440
        my $raw_token = $token;
674
1021
513
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
675
1021
392
        my $before;
676
1021
1406
        if ($token =~ /^$upper_pattern$lower_pattern/) {
677
5
3
          $before = '(?<=.)';
678        } elsif ($token =~ /^$upper_pattern/) {
679
0
0
          $before = "(?<!$upper_pattern)";
680        } else {
681
1016
496
          $before = "(?<=$not_upper_or_lower_pattern)";
682        }
683
1021
1065
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
684
1021
1834
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
685
1271
602
          $line_flagged = 1;
686
1271
501
          $found_token = 1;
687
1271
1450
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
688
1271
1048
          next unless $match =~ /./;
689
1271
708
          print_word_not_in_dictionary($warnings_fh, $begin, $end, $match);
690        }
691
1021
945
        unless ($found_token) {
692
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
693
3
5
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
694
3
4
            print_word_not_in_dictionary($warnings_fh, $begin, $end, $match);
695          } else {
696
0
0
            my $offset = $line_length + 1;
697
0
0
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
698
0
0
            print $warnings_fh ":$.:1 ... $offset, Warning - Could not identify whole word $wrapped in line (token-is-substring)\n";
699          }
700        }
701      }
702
1159
1465
      if ($line_flagged && $candidates_re) {
703
1
2
        $_ = $previous_line_state = $initial_line_state;
704
1
1
21
2
        s/($candidates_re)/"="x length($1)/ge;
705
1
2
        if ($_ ne $initial_line_state) {
706
1
1
          $_ = $previous_line_state;
707
1
2
          for my $i (0 .. $#candidates_re_list) {
708
2
1
            my $candidate_re = $candidates_re_list[$i];
709
2
15
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
710
1
1
7
2
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
711
1
1
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
712
1
3
              my $hit = "$.:$begin:$end";
713
1
1
              $_ = $previous_line_state;
714
1
1
5
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
715
1
1
              $candidates_re_hits[$i] += $replacements;
716
1
1
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
717
1
3
              $_ = $previous_line_state;
718            }
719          }
720        }
721      }
722
1159
715
      unless ($disable_minified_file) {
723
1159
832
        s/={3,}//g;
724
1159
683
        $offset += length;
725
1159
880
        my $ratio = int($offset / $.);
726
1159
534
        my $ratio_threshold = 1000;
727
1159
2721
        if ($ratio > $ratio_threshold) {
728
2
6
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
729
2
7
          last;
730        }
731      }
732    }
733
734
13
99
    alarm 0;
735  };
736
13
12
  if ($@) {
737
0
0
    die unless $@ eq "alarm\n";
738
0
0
    print $warnings_fh ":$.:1 ... 1, Warning - Could not parse file within time limit (slow-file)\n";
739
0
0
    skip_file($temp_dir, "it could not be parsed file within time limit (slow-file)\n");
740
0
0
    return $temp_dir;
741  }
742
743
13
53
  close $file_fh;
744
13
177
  close $warnings_fh;
745
746
13
35
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
747
12
379
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
748
12
181
      print $stats_fh "{words: $words, unrecognized: $unrecognized, unknown: ".(keys %unique_unrecognized).
749      ", unique: ".(keys %unique).
750      (@candidates_re_hits ? ", candidates: [".(join ',', @candidates_re_hits)."]" : "").
751      (@candidates_re_lines ? ", candidate_lines: [".(join ',', @candidates_re_lines)."]" : "").
752      (@forbidden_re_hits ? ", forbidden: [".(join ',', @forbidden_re_hits)."]" : "").
753      (@forbidden_re_lines ? ", forbidden_lines: [".(join ',', @forbidden_re_lines)."]" : "").
754      "}";
755
12
157
    close $stats_fh;
756
12
273
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
757
12
20
43
30
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
758
12
127
    close $unknown_fh;
759  }
760
761
13
152
  return $temp_dir;
762}
763
764sub main {
765
2
444
  my ($configuration, @ARGV) = @_;
766
2
1
  our %dictionary;
767
2
3
  unless (%dictionary) {
768
1
1
    init($configuration);
769  }
770
771  # read all input
772
2
3
  my @reports;
773
774
2
2
  for my $file (@ARGV) {
775
2
2
    my $temp_dir = split_file($file);
776
2
4
    push @reports, "$temp_dir\n";
777  }
778
2
9
  print join '', @reports;
779}
780
7811;