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
110867
3
use 5.022;
11
1
1
1
1
1
51
use feature 'unicode_strings';
12
1
1
1
1
2
9
use strict;
13
1
1
1
1
1
21
use warnings;
14
1
1
1
1
1
14
no warnings qw(experimental::vlb);
15
1
1
1
1
1
2
use utf8;
16
1
1
1
12
1
25
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
1
1
46
use File::Basename;
18
1
1
1
2
0
14
use Cwd 'abs_path';
19
1
1
1
1
1
20
use File::Spec;
20
1
1
1
1
1
19
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
1
11
use File::Path qw/ make_path /;
22
1
1
1
287
0
19
use CheckSpelling::Util;
23
1
1
1
206
1264
819
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
13
  my ($expression) = @_;
49
14
14
5
115
  return eval { qr /$expression/ };
50}
51
52sub quote_re {
53
14
8
  my ($expression) = @_;
54
14
14
  return $expression if $expression =~ /\?\{/;
55
14
32
  $expression =~ s/
56   \G
57   (
58      (?:[^\\]|\\[^Q])*
59   )
60   (?:
61      \\Q
62      (?:[^\\]|\\[^E])*
63      (?:\\E)?
64   )?
65/
66
28
48
   $1 . (defined($2) ? quotemeta($2) : '')
67/xge;
68
14
15
  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
5
    local $/=undef;
78
3
24
    my $file=<$fh>;
79
3
11
    close $fh;
80
3
1
    my $line_number = 0;
81
3
3
    my $hint = '';
82
3
15
    for (split /\R/, $file) {
83
17
12
      ++$line_number;
84
17
6
      chomp;
85
17
39
      if (/^#(?:\s(.+)|)/) {
86
6
13
        $hint = $1 if ($hint eq '' && defined $1);
87
6
4
        next;
88      }
89
11
14
      $hint = '' unless $_ ne '';
90
11
9
      next if $_ eq '$^';
91
11
8
      my $pattern = $_;
92
11
27
      next unless s/^(.+)/(?:$1)/;
93
7
9
      my $quoted = quote_re($1);
94
7
10
      unless (test_re $quoted) {
95
1
2
        my $error = $@;
96
1
57
        my $home = dirname(__FILE__);
97
1
24
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
98
1
13
        print STDERR $error;
99
1
3
        $_ = '(?:\$^ - skipped because bad-regex)';
100
1
2
        $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
20
        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
6
        push @patterns, $_;
109
6
9
        $hints{$_} = $hint;
110      }
111
7
11
      $hint = '';
112    }
113  }
114
115  return {
116
3
15
    patterns => \@patterns,
117    hints => \%hints,
118  };
119}
120
121sub file_to_list {
122
2
1301
  my ($re) = @_;
123
2
6
  my $lists = file_to_lists($re);
124
125
2
2
2
7
  return @{$lists->{'patterns'}};
126}
127
128sub list_to_re {
129
2
3
  my (@list) = @_;
130
2
5
5
2
6
3
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
131
2
5
1
6
  @list = grep { $_ ne '' } @list;
132
2
1
  return '$^' unless scalar @list;
133
2
7
  return join "|", (@list);
134}
135
136sub not_empty {
137
76
68
  my ($thing) = @_;
138
76
362
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
139}
140
141sub valid_word {
142  # shortest_word is an absolute
143
22
10
  our ($shortest, $longest, $shortest_word, $longest_word);
144
22
23
  $shortest = $shortest_word if $shortest_word;
145
22
18
  if ($longest_word) {
146    # longest_word is an absolute
147
20
27
    $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
16
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
154
22
66
18
163
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
155
22
22
  $word_pattern = q<\\w|'> unless $word_pattern;
156
22
44
  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
29
  $shortest = 3 unless defined $shortest;
162
22
17
  $longest = '' unless not_empty($longest);
163
22
96
  $word_match = "(?:$word_pattern){$shortest,$longest}";
164
22
201
  return qr/\b$word_match\b/;
165}
166
167sub load_dictionary {
168
12
1759
  my ($dict) = @_;
169
12
7
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
170
12
10
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
171
12
15
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
172
12
6
  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
41
  $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
23
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
177
12
21
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
178
12
59
  $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
31
  if ($check_homoglyphs && $check_homoglyphs !~ /false/i) {
181
11
12
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
182
11
76
    if (-s $homoglyph_list_path) {
183
1
1
1
346
1
3311
      use CheckSpelling::Homoglyph;
184
11
24
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
185    } else {
186
0
0
      $check_homoglyphs = 0;
187    }
188  } else {
189
1
1
    $check_homoglyphs = 0;
190  }
191
12
17
  %dictionary = ();
192
193
12
404
  open(my $dict_fh, '<:utf8', $dict);
194
12
17
  my $word_match_relaxed = $word_match;
195
12
60
  if ($word_match =~ /\{(\d+),/) {
196
12
23
    my $three = $1;
197
12
16
    if ($three > 1) {
198
12
7
      my $two = $three - 1;
199
12
89
      $word_match_relaxed =~ s/\b$three\b/$two/g;
200    }
201  }
202
12
60
  while (!eof($dict_fh)) {
203
32
33
    my $word = <$dict_fh>;
204
32
27
    chomp $word;
205
32
130
    next unless $word =~ $word_match_relaxed;
206
31
27
    my $l = length $word;
207
31
21
    $longest = -1 unless not_empty($longest);
208
31
35
    $longest = $l if $l > $longest;
209
31
76
    if ($word =~ $word_match) {
210
29
24
      $shortest = $l if $l < $shortest;
211    }
212
31
62
    $dictionary{$word}=1;
213  }
214
12
28
  close $dict_fh;
215
216
12
12
  $word_match = valid_word();
217}
218
219sub hunspell_dictionary {
220
3
4
  my ($dict) = @_;
221
3
2
  my $name = $dict;
222
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
223
3
14
  $name =~ s{.*/}{};
224
3
4
  my $aff = $dict;
225
3
2
  my $encoding;
226
3
9
  $aff =~ s/\.dic$/.aff/;
227
3
35
  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
8
    close $aff_fh;
234  }
235  return {
236
3
337
    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
10940
  my ($configuration) = @_;
246
9
11
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
247
9
40
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
248
9
9
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
249
9
18
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
250
9
7
  our %forbidden_re_descriptions;
251
9
6
  our @reject_re_list;
252
9
7
  our $reject_re;
253
9
9
  if ($hunspell_dictionary_path) {
254
3
39
    our @hunspell_dictionaries = ();
255
1
1
1
1
1
1
1
1
1
3
304
1239
26
6
0
16
8
1
17
172
    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
7
        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
14
  my (@patterns_re_list, %in_patterns_re_list);
265
9
52
  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
12
    $patterns_re = undef;
271  }
272
273
9
40
  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
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
277
1
2
    $forbidden_re = list_to_re @forbidden_re_list;
278  } else {
279
8
12
    $forbidden_re = undef;
280  }
281
282
9
46
  if (-e "$configuration/candidates.txt") {
283
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
284
1
2
2
2
2
6
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
285
1
4
    $candidates_re = list_to_re @candidates_re_list;
286  } else {
287
8
7
    $candidates_re = undef;
288  }
289
290
9
46
  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
17
    $reject_re = '$^';
296  }
297
298
9
11
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
299
300
9
9
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
301
9
7
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
302
9
7
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
303
9
6
  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
8
  $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
10
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
316
317
9
7
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
318
319
9
9
  $word_match = valid_word();
320
321
9
22
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
322
9
38
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
323
9
10
  load_dictionary($base_dict);
324}
325
326sub split_line {
327
1159
467
  our (%dictionary, $word_match, $disable_word_collating);
328
1159
445
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
329
1159
440
  our @hunspell_dictionaries;
330
1159
411
  our $shortest;
331
1159
705
  my $shortest_threshold = $shortest + 2;
332
1159
563
  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
510
  my $rsqm = "\xE2\x80\x99";
337
338
1159
605
  my ($words, $unrecognized) = (0, 0);
339
1159
731
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
340
1159
4844
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
341
1159
1927
    $line =~ s/(?:$ignore_pattern)+/ /g;
342
1159
1518
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
343
1159
2806
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
344
1159
1217
    for my $token (split /\s+/, $line) {
345
3631
3039
      next unless $token =~ /$pattern/;
346
2473
1863
      $token =~ s/^(?:'|$rsqm)+//g;
347
2473
2245
      $token =~ s/(?:'|$rsqm)+s?$//g;
348
2473
1340
      my $raw_token = $token;
349
2473
1319
      $token =~ s/^[^Ii]?'+//; # need to reconsider for French
350
2473
1169
      $token =~ s/'+$//;
351
2473
3482
      next unless $token =~ $word_match;
352
2316
1905
      if (defined $dictionary{$token}) {
353
1036
491
        ++$words;
354
1036
544
        $unique_ref->{$token}=1;
355
1036
861
        next;
356      }
357
1280
845
      if (@hunspell_dictionaries) {
358
1254
550
        my $found = 0;
359
1254
697
        for my $hunspell_dictionary (@hunspell_dictionaries) {
360          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
361
1254
957
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
362
1254
2143
          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
828
        next if $found;
370      }
371
1280
822
      my $key = lc $token;
372
1280
997
      if (defined $dictionary{$key}) {
373
6
4
        ++$words;
374
6
3
        $unique_ref->{$key}=1;
375
6
8
        next;
376      }
377
1274
760
      unless ($disable_word_collating) {
378
1274
715
        $key =~ s/''+/'/g;
379
1274
1062
        $key =~ s/'[sd]$// if length $key >= $shortest_threshold;
380      }
381
1274
952
      if (defined $dictionary{$key}) {
382
0
0
        ++$words;
383
0
0
        $unique_ref->{$key}=1;
384
0
0
        next;
385      }
386
1274
583
      ++$unrecognized;
387
1274
741
      $unique_unrecognized_ref->{$raw_token}=1;
388
1274
1548
      $unrecognized_line_items_ref->{$raw_token}=1;
389    }
390
1159
1319
    return ($words, $unrecognized);
391}
392
393sub skip_file {
394
7
28
  my ($temp_dir, $reason) = @_;
395
7
228
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
396
7
60
  print $skipped_fh $reason;
397
7
115
  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
752
  my ($warnings_fh, $begin, $end, $match) = @_;
445
1274
465
  our $reject_re;
446
1274
833
  my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
447
1274
1130
  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
4212
    print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
463  }
464}
465
466sub split_file {
467
17
12692
  my ($file) = @_;
468  our (
469
17
12
    $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
35
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
479
480
17
9
  our %forbidden_re_descriptions;
481
17
9
  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
19
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
487
17
15
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
488
17
20
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
489
17
11
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
490
17
36
  my $temp_dir = tempdir(DIR=>$sandbox);
491
17
2831
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
492
17
440
  open(my $name_fh, '>', "$temp_dir/name");
493
17
38
    print $name_fh $file;
494
17
231
  close $name_fh;
495
17
207
  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
6
    return $temp_dir;
499  }
500
16
29
  if ($use_magic_file) {
501
8
13091
    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
31230
      my $file_kind = <$file_fh>;
513
8
3947
      close $file_fh;
514
8
15
      my $file_converted = 0;
515
8
20
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
516
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
517      }
518
8
200
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
519
2
40
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
520
2
56
        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
97
  my $file_size = -s $file;
528
14
30
  if (defined $largest_file) {
529
14
25
    unless ($check_file_names eq $file) {
530
14
17
      if ($file_size > $largest_file) {
531
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
532
1
3
        return $temp_dir;
533      }
534    }
535  }
536
13
153
  open my $file_fh, '<', $file;
537
13
9
  binmode $file_fh;
538
13
10
  my $head;
539
13
132
  read($file_fh, $head, 4096);
540
13
870
  $head =~ s/(?:\r|\n)+$//;
541
13
65
  my $dos_new_lines = () = $head =~ /\r\n/gi;
542
13
32
  my $unix_new_lines = () = $head =~ /\n/gi;
543
13
130
  my $mac_new_lines = () = $head =~ /\r/gi;
544
13
64
  local $/;
545
13
84
  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
7
    $/ = "\r\n";
549  } elsif ($mac_new_lines > $unix_new_lines) {
550
2
7
    $/ = "\r";
551  } else {
552
7
7
    $/ = "\n";
553  }
554
13
30
  seek($file_fh, 0, 0);
555
13
29
  ($words, $unrecognized) = (0, 0);
556
13
43
  %unique = ();
557
13
35
  %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
126
  };
565
566
13
368
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
567
13
14
  our $timeout;
568
13
14
  eval {
569
13
0
103
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
570
13
40
    alarm $timeout;
571
572
13
22
    my $ignore_next_line = 0;
573
13
16
    my $offset = 0;
574
13
89
    while (<$file_fh>) {
575
1162
879
      if ($. == 1) {
576
13
28
        unless ($disable_minified_file) {
577
13
115
          if ($file_size >= 512 && length($_) == $file_size) {
578
1
13
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
579
1
2
            last;
580          }
581        }
582
12
38
        s/^\x{FEFF}//;
583      }
584
1161
1808
      $_ = decode_utf8($_, FB_DEFAULT);
585
1161
2259
      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
1164
      s/\R$//;
590
1161
950
      next unless /./;
591
1160
734
      my $raw_line = $_;
592
593
1160
517
      my $ignore_this_line = $ignore_next_line;
594
1160
889
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
595
1160
703
      next if $ignore_this_line;
596
597      # hook for custom line based text exclusions:
598
1159
721
      if (defined $patterns_re) {
599
2
6
11
9
        s/($patterns_re)/"="x length($1)/ge;
600      }
601
1159
613
      my $initial_line_state = $_;
602
1159
602
      my $previous_line_state = $_;
603
1159
556
      my $line_flagged;
604
1159
715
      if ($forbidden_re) {
605
9
5
63
13
        while (s/($forbidden_re)/"="x length($1)/e) {
606
5
2
          $line_flagged = 1;
607
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
608
5
4
          my $found_trigger_re;
609
5
6
          for my $i (0 .. $#forbidden_re_list) {
610
7
6
            my $forbidden_re_singleton = $forbidden_re_list[$i];
611
7
6
            my $test_line = $previous_line_state;
612
7
4
58
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
613
4
5
              next unless $test_line eq $_;
614
4
5
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
615
4
5
              next unless $begin == $begin_test;
616
4
3
              next unless $end == $end_test;
617
4
4
              next unless $match eq $match_test;
618
4
2
              $found_trigger_re = $forbidden_re_singleton;
619
4
8
              my $hit = "$.:$begin:$end";
620
4
2
              $forbidden_re_hits[$i]++;
621
4
5
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
622
4
7
              last;
623            }
624          }
625
5
5
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
626
5
6
          if ($found_trigger_re) {
627
4
7
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
628
4
8
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
629
4
4
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
630
4
4
            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
4
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
637          }
638
5
22
          $previous_line_state = $_;
639        }
640
9
8
        $_ = $initial_line_state;
641      }
642      # This is to make it easier to deal w/ rules:
643
1159
1009
      s/^/ /;
644
1159
617
      my %unrecognized_line_items = ();
645
1159
479
      our $check_homoglyphs;
646
1159
633
      if ($check_homoglyphs) {
647
1159
596
        my $check_line_for_homoglyphs = $_;
648
1159
612
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
649        # problematic characters: `\\`, `-`, `]`
650
1159
11437
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
651
1159
1217
        $homoglyphs = "[$homoglyphs]";
652
1159
471
        our ($longest_word, $shortest_word);
653
1159
1627
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
654
1159
500
        my $dollar = '$';
655
1159
1444
        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
9858
        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
2
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
658
1
58
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
659
1
2
          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
15
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
664          }
665        }
666      }
667
1159
773
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
668
1159
553
      $words += $new_words;
669
1159
510
      $unrecognized += $new_unrecognized;
670
1159
655
      my $line_length = length($raw_line);
671
1159
1190
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
672
1021
484
        my $found_token = 0;
673
1021
434
        my $raw_token = $token;
674
1021
513
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
675
1021
404
        my $before;
676
1021
1341
        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
547
          $before = "(?<=$not_upper_or_lower_pattern)";
682        }
683
1021
1004
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
684
1021
1816
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
685
1271
568
          $line_flagged = 1;
686
1271
532
          $found_token = 1;
687
1271
1465
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
688
1271
1015
          next unless $match =~ /./;
689
1271
712
          print_word_not_in_dictionary($warnings_fh, $begin, $end, $match);
690        }
691
1021
1005
        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
3
            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
1417
      if ($line_flagged && $candidates_re) {
703
1
1
        $_ = $previous_line_state = $initial_line_state;
704
1
1
21
3
        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
2
            my $candidate_re = $candidates_re_list[$i];
709
2
14
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
710
1
1
7
2
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
711
1
2
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
712
1
3
              my $hit = "$.:$begin:$end";
713
1
1
              $_ = $previous_line_state;
714
1
1
5
1
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
715
1
2
              $candidates_re_hits[$i] += $replacements;
716
1
2
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
717
1
2
              $_ = $previous_line_state;
718            }
719          }
720        }
721      }
722
1159
717
      unless ($disable_minified_file) {
723
1159
829
        s/={3,}//g;
724
1159
678
        $offset += length;
725
1159
901
        my $ratio = int($offset / $.);
726
1159
519
        my $ratio_threshold = 1000;
727
1159
2701
        if ($ratio > $ratio_threshold) {
728
2
9
          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
51
  close $file_fh;
744
13
174
  close $warnings_fh;
745
746
13
31
  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
141
    close $stats_fh;
756
12
239
    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
137
    close $unknown_fh;
759  }
760
761
13
138
  return $temp_dir;
762}
763
764sub main {
765
2
412
  my ($configuration, @ARGV) = @_;
766
2
2
  our %dictionary;
767
2
3
  unless (%dictionary) {
768
1
1
    init($configuration);
769  }
770
771  # read all input
772
2
2
  my @reports;
773
774
2
2
  for my $file (@ARGV) {
775
2
1
    my $temp_dir = split_file($file);
776
2
3
    push @reports, "$temp_dir\n";
777  }
778
2
7
  print join '', @reports;
779}
780
7811;