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
110954
2
use 5.022;
11
1
1
1
1
1
47
use feature 'unicode_strings';
12
1
1
1
3
1
8
use strict;
13
1
1
1
1
1
19
use warnings;
14
1
1
1
2
0
12
no warnings qw(experimental::vlb);
15
1
1
1
2
0
2
use utf8;
16
1
1
1
13
0
24
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
1
2
25
use File::Basename;
18
1
1
1
21
1
18
use Cwd 'abs_path';
19
1
1
1
2
0
22
use File::Spec;
20
1
1
1
1
0
20
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
2
0
13
use File::Path qw/ make_path /;
22
1
1
1
283
1
19
use CheckSpelling::Util;
23
1
1
1
190
1222
796
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
10
  my ($expression) = @_;
49
14
14
7
106
  return eval { qr /$expression/ };
50}
51
52sub quote_re {
53
14
13
  my ($expression) = @_;
54
14
13
  return $expression if $expression =~ /\?\{/;
55
14
31
  $expression =~ s/
56   \G
57   (
58      (?:[^\\]|\\[^Q])*
59   )
60   (?:
61      \\Q
62      (?:[^\\]|\\[^E])*
63      (?:\\E)?
64   )?
65/
66
28
72
   $1 . (defined($2) ? quotemeta($2) : '')
67/xge;
68
14
16
  return $expression;
69}
70
71sub file_to_lists {
72
3
4
  my ($re) = @_;
73
3
3
  my @patterns;
74  my %hints;
75
3
0
  my $fh;
76
3
34
  if (open($fh, '<:utf8', $re)) {
77
3
7
    local $/=undef;
78
3
25
    my $file=<$fh>;
79
3
9
    close $fh;
80
3
2
    my $line_number = 0;
81
3
2
    my $hint = '';
82
3
14
    for (split /\R/, $file) {
83
17
10
      ++$line_number;
84
17
9
      chomp;
85
17
22
      if (/^#(?:\s(.+)|)/) {
86
6
15
        $hint = $1 if ($hint eq '' && defined $1);
87
6
5
        next;
88      }
89
11
14
      $hint = '' unless $_ ne '';
90
11
11
      next if $_ eq '$^';
91
11
8
      my $pattern = $_;
92
11
26
      next unless s/^(.+)/(?:$1)/;
93
7
6
      my $quoted = quote_re($1);
94
7
10
      unless (test_re $quoted) {
95
1
1
        my $error = $@;
96
1
48
        my $home = dirname(__FILE__);
97
1
22
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
98
1
15
        print STDERR $error;
99
1
3
        $_ = '(?:\$^ - 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
1
        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
6
        push @patterns, $_;
109
6
8
        $hints{$_} = $hint;
110      }
111
7
13
      $hint = '';
112    }
113  }
114
115  return {
116
3
13
    patterns => \@patterns,
117    hints => \%hints,
118  };
119}
120
121sub file_to_list {
122
2
1231
  my ($re) = @_;
123
2
5
  my $lists = file_to_lists($re);
124
125
2
2
3
6
  return @{$lists->{'patterns'}};
126}
127
128sub list_to_re {
129
2
3
  my (@list) = @_;
130
2
5
5
2
4
3
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
131
2
5
2
5
  @list = grep { $_ ne '' } @list;
132
2
3
  return '$^' unless scalar @list;
133
2
6
  return join "|", (@list);
134}
135
136sub not_empty {
137
76
65
  my ($thing) = @_;
138
76
354
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
139}
140
141sub valid_word {
142  # shortest_word is an absolute
143
22
9
  our ($shortest, $longest, $shortest_word, $longest_word);
144
22
26
  $shortest = $shortest_word if $shortest_word;
145
22
23
  if ($longest_word) {
146    # longest_word is an absolute
147
20
16
    $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
17
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
154
22
66
19
163
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
155
22
20
  $word_pattern = q<\\w|'> unless $word_pattern;
156
22
41
  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
23
  $shortest = 3 unless defined $shortest;
162
22
17
  $longest = '' unless not_empty($longest);
163
22
71
  $word_match = "(?:$word_pattern){$shortest,$longest}";
164
22
221
  return qr/\b$word_match\b/;
165}
166
167sub load_dictionary {
168
12
2188
  my ($dict) = @_;
169
12
6
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
170
12
11
  $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
10
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
173
12
9
  $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
29
  $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
23
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
178
12
28
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
179
12
24
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
180
12
34
  if ($check_homoglyphs && $check_homoglyphs !~ /false/i) {
181
11
10
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
182
11
108
    if (-s $homoglyph_list_path) {
183
1
1
1
295
1
3449
      use CheckSpelling::Homoglyph;
184
11
22
      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
18
  %dictionary = ();
192
193
12
431
  open(my $dict_fh, '<:utf8', $dict);
194
12
17
  my $word_match_relaxed = $word_match;
195
12
51
  if ($word_match =~ /\{(\d+),/) {
196
12
20
    my $three = $1;
197
12
13
    if ($three > 1) {
198
12
7
      my $two = $three - 1;
199
12
82
      $word_match_relaxed =~ s/\b$three\b/$two/g;
200    }
201  }
202
12
64
  while (!eof($dict_fh)) {
203
32
36
    my $word = <$dict_fh>;
204
32
24
    chomp $word;
205
32
123
    next unless $word =~ $word_match_relaxed;
206
31
27
    my $l = length $word;
207
31
24
    $longest = -1 unless not_empty($longest);
208
31
34
    $longest = $l if $l > $longest;
209
31
69
    if ($word =~ $word_match) {
210
29
31
      $shortest = $l if $l < $shortest;
211    }
212
31
58
    $dictionary{$word}=1;
213  }
214
12
28
  close $dict_fh;
215
216
12
13
  $word_match = valid_word();
217}
218
219sub hunspell_dictionary {
220
3
6
  my ($dict) = @_;
221
3
4
  my $name = $dict;
222
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
223
3
15
  $name =~ s{.*/}{};
224
3
4
  my $aff = $dict;
225
3
3
  my $encoding;
226
3
8
  $aff =~ s/\.dic$/.aff/;
227
3
33
  if (open my $aff_fh, '<', $aff) {
228
3
19
    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
10
    close $aff_fh;
234  }
235  return {
236
3
388
    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
13928
  my ($configuration) = @_;
246
9
11
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
247
9
21
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
248
9
11
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
249
9
17
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
250
9
12
  our %forbidden_re_descriptions;
251
9
3
  our @reject_re_list;
252
9
6
  our $reject_re;
253
9
10
  if ($hunspell_dictionary_path) {
254
3
54
    our @hunspell_dictionaries = ();
255
1
1
1
1
1
1
1
1
1
3
250
1106
20
5
2
15
8
1
16
158
    if (eval 'use Text::Hunspell; 1') {
256
3
118
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
257
3
8
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
258
3
6
        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
54
  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
9
    $patterns_re = undef;
271  }
272
273
9
35
  if (-e "$configuration/forbidden.txt") {
274
1
1
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
275
1
1
1
1
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
276
1
1
1
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
277
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
278  } else {
279
8
10
    $forbidden_re = undef;
280  }
281
282
9
40
  if (-e "$configuration/candidates.txt") {
283
1
4
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
284
1
2
2
1
1
5
    @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
6
    $candidates_re = undef;
288  }
289
290
9
36
  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
10
    $reject_re = '$^';
296  }
297
298
9
10
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
299
300
9
13
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
301
9
9
  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
5
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
304
305
9
8
  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
7
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
309
9
7
  $check_images = $check_images =~ /^(?:1|true)$/i;
310
9
10
  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
9
  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
8
  $word_match = valid_word();
320
321
9
21
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
322
9
42
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
323
9
11
  load_dictionary($base_dict);
324}
325
326sub split_line {
327
1159
603
  our (%dictionary, $word_match, $disable_word_collating);
328
1159
446
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
329
1159
492
  our @hunspell_dictionaries;
330
1159
495
  our $shortest;
331
1159
897
  my $shortest_threshold = $shortest + 2;
332
1159
646
  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
616
  my $rsqm = "\xE2\x80\x99";
337
338
1159
748
  my ($words, $unrecognized) = (0, 0);
339
1159
856
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
340
1159
5718
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
341
1159
2481
    $line =~ s/(?:$ignore_pattern)+/ /g;
342
1159
1789
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
343
1159
3424
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
344
1159
1407
    for my $token (split /\s+/, $line) {
345
3631
3465
      next unless $token =~ /$pattern/;
346
2473
3622
      $token =~ s/^(?:'|$rsqm)*(.*?)(?:'|$rsqm)+$/$1/g;
347
2473
1804
      $token =~ s/(?:'|$rsqm)+s$//g; # need to reconsider for not English
348
2473
1374
      my $raw_token = $token;
349
2473
1452
      $token =~ s/^[^Ii]?'+//; # need to reconsider for French
350
2473
1301
      $token =~ s/'+$//;
351
2473
4147
      next unless $token =~ $word_match;
352
2316
2251
      if (defined $dictionary{$token}) {
353
1036
506
        ++$words;
354
1036
520
        $unique_ref->{$token}=1;
355
1036
838
        next;
356      }
357
1280
995
      if (@hunspell_dictionaries) {
358
1254
600
        my $found = 0;
359
1254
841
        for my $hunspell_dictionary (@hunspell_dictionaries) {
360          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
361
1254
1173
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
362
1254
3197
          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
1037
        next if $found;
370      }
371
1280
946
      my $key = lc $token;
372
1280
1138
      if (defined $dictionary{$key}) {
373
6
2
        ++$words;
374
6
5
        $unique_ref->{$key}=1;
375
6
8
        next;
376      }
377
1274
948
      unless ($disable_word_collating) {
378
1274
856
        $key =~ s/''+/'/g;
379
1274
1286
        $key =~ s/'[sd]$// if length $key >= $shortest_threshold;
380      }
381
1274
1197
      if (defined $dictionary{$key}) {
382
0
0
        ++$words;
383
0
0
        $unique_ref->{$key}=1;
384
0
0
        next;
385      }
386
1274
683
      ++$unrecognized;
387
1274
885
      $unique_unrecognized_ref->{$raw_token}=1;
388
1274
1785
      $unrecognized_line_items_ref->{$raw_token}=1;
389    }
390
1159
1785
    return ($words, $unrecognized);
391}
392
393sub skip_file {
394
7
23
  my ($temp_dir, $reason) = @_;
395
7
217
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
396
7
32
  print $skipped_fh $reason;
397
7
107
  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
841
  my ($warnings_fh, $begin, $end, $match) = @_;
445
1274
573
  our $reject_re;
446
1274
999
  my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
447
1274
1501
  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
5354
    print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
463  }
464}
465
466sub split_file {
467
17
14293
  my ($file) = @_;
468  our (
469
17
15
    $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
34
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
479
480
17
13
  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
10
  my $rsqm = "\xE2\x80\x99";
485
486
17
23
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
487
17
16
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
488
17
15
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
489
17
44
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
490
17
30
  my $temp_dir = tempdir(DIR=>$sandbox);
491
17
2839
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
492
17
407
  open(my $name_fh, '>', "$temp_dir/name");
493
17
39
    print $name_fh $file;
494
17
250
  close $name_fh;
495
17
237
  if (defined readlink($file) &&
496      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
497
1
8
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
498
1
7
    return $temp_dir;
499  }
500
16
27
  if ($use_magic_file) {
501
8
11890
    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
27966
      my $file_kind = <$file_fh>;
513
8
3856
      close $file_fh;
514
8
10
      my $file_converted = 0;
515
8
17
      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
24
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
520
2
37
        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
77
  my $file_size = -s $file;
528
14
23
  if (defined $largest_file) {
529
14
15
    unless ($check_file_names eq $file) {
530
14
13
      if ($file_size > $largest_file) {
531
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
532
1
4
        return $temp_dir;
533      }
534    }
535  }
536
13
133
  open my $file_fh, '<', $file;
537
13
14
  binmode $file_fh;
538
13
6
  my $head;
539
13
118
  read($file_fh, $head, 4096);
540
13
799
  $head =~ s/(?:\r|\n)+$//;
541
13
44
  my $dos_new_lines = () = $head =~ /\r\n/gi;
542
13
35
  my $unix_new_lines = () = $head =~ /\n/gi;
543
13
105
  my $mac_new_lines = () = $head =~ /\r/gi;
544
13
58
  local $/;
545
13
69
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
546
3
5
    $/ = "\n";
547  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
548
1
6
    $/ = "\r\n";
549  } elsif ($mac_new_lines > $unix_new_lines) {
550
2
4
    $/ = "\r";
551  } else {
552
7
8
    $/ = "\n";
553  }
554
13
28
  seek($file_fh, 0, 0);
555
13
24
  ($words, $unrecognized) = (0, 0);
556
13
33
  %unique = ();
557
13
31
  %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
102
  };
565
566
13
351
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
567
13
9
  our $timeout;
568
13
15
  eval {
569
13
0
115
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
570
13
41
    alarm $timeout;
571
572
13
16
    my $ignore_next_line = 0;
573
13
6
    my $offset = 0;
574
13
124
    while (<$file_fh>) {
575
1162
1182
      if ($. == 1) {
576
13
15
        unless ($disable_minified_file) {
577
13
48
          if ($file_size >= 512 && length($_) == $file_size) {
578
1
10
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
579
1
3
            last;
580          }
581        }
582
12
23
        s/^\x{FEFF}//;
583      }
584
1161
2537
      $_ = decode_utf8($_, FB_DEFAULT);
585
1161
3025
      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
1686
      s/\R$//;
590
1161
1212
      next unless /./;
591
1160
774
      my $raw_line = $_;
592
593
1160
760
      my $ignore_this_line = $ignore_next_line;
594
1160
1209
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
595
1160
866
      next if $ignore_this_line;
596
597      # hook for custom line based text exclusions:
598
1159
830
      if (defined $patterns_re) {
599
2
6
10
9
        s/($patterns_re)/"="x length($1)/ge;
600      }
601
1159
687
      my $initial_line_state = $_;
602
1159
724
      my $previous_line_state = $_;
603
1159
653
      my $line_flagged;
604
1159
887
      if ($forbidden_re) {
605
9
5
59
12
        while (s/($forbidden_re)/"="x length($1)/e) {
606
5
4
          $line_flagged = 1;
607
5
11
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
608
5
2
          my $found_trigger_re;
609
5
6
          for my $i (0 .. $#forbidden_re_list) {
610
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
611
7
6
            my $test_line = $previous_line_state;
612
7
4
61
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
613
4
5
              next unless $test_line eq $_;
614
4
7
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
615
4
4
              next unless $begin == $begin_test;
616
4
3
              next unless $end == $end_test;
617
4
3
              next unless $match eq $match_test;
618
4
3
              $found_trigger_re = $forbidden_re_singleton;
619
4
7
              my $hit = "$.:$begin:$end";
620
4
4
              $forbidden_re_hits[$i]++;
621
4
5
              $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
6
          if ($found_trigger_re) {
627
4
9
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
628
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
629
4
3
            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
5
              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
1142
      s/^/ /;
644
1159
789
      my %unrecognized_line_items = ();
645
1159
649
      our $check_homoglyphs;
646
1159
778
      if ($check_homoglyphs) {
647
1159
700
        my $check_line_for_homoglyphs = $_;
648
1159
815
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
649        # problematic characters: `\\`, `-`, `]`
650
1159
11285
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
651
1159
1380
        $homoglyphs = "[$homoglyphs]";
652
1159
491
        our ($longest_word, $shortest_word);
653
1159
1960
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
654
1159
597
        my $dollar = '$';
655
1159
1768
        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
11456
        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
3
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
658
1
53
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
659
1
1
          if (defined $dictionary{$token}) {
660
1
2
            my $token_raw = CheckSpelling::Util::wrap_in_backticks($token_raw);
661
1
2
            my $token = CheckSpelling::Util::wrap_in_backticks($token);
662
1
19
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
663
1
18
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
664          }
665        }
666      }
667
1159
1288
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
668
1159
691
      $words += $new_words;
669
1159
555
      $unrecognized += $new_unrecognized;
670
1159
782
      my $line_length = length($raw_line);
671
1159
1669
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
672
1021
506
        my $found_token = 0;
673
1021
496
        my $raw_token = $token;
674
1021
578
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
675
1021
473
        my $before;
676
1021
1654
        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
663
          $before = "(?<=$not_upper_or_lower_pattern)";
682        }
683
1021
1377
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
684
1021
2398
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
685
1271
684
          $line_flagged = 1;
686
1271
645
          $found_token = 1;
687
1271
1814
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
688
1271
1192
          next unless $match =~ /./;
689
1271
858
          print_word_not_in_dictionary($warnings_fh, $begin, $end, $match);
690        }
691
1021
1299
        unless ($found_token) {
692
3
27
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
693
3
7
            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
1935
      if ($line_flagged && $candidates_re) {
703
1
2
        $_ = $previous_line_state = $initial_line_state;
704
1
1
17
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
2
            my $candidate_re = $candidates_re_list[$i];
709
2
14
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
710
1
1
6
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
4
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
715
1
1
              $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
951
      unless ($disable_minified_file) {
723
1159
989
        s/={3,}//g;
724
1159
921
        $offset += length;
725
1159
1227
        my $ratio = int($offset / $.);
726
1159
697
        my $ratio_threshold = 1000;
727
1159
3419
        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
5
          last;
730        }
731      }
732    }
733
734
13
78
    alarm 0;
735  };
736
13
13
  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
43
  close $file_fh;
744
13
160
  close $warnings_fh;
745
746
13
30
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
747
12
350
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
748
12
174
      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
156
    close $stats_fh;
756
12
307
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
757
12
20
45
32
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
758
12
136
    close $unknown_fh;
759  }
760
761
13
132
  return $temp_dir;
762}
763
764sub main {
765
2
345
  my ($configuration, @ARGV) = @_;
766
2
2
  our %dictionary;
767
2
2
  unless (%dictionary) {
768
1
1
    init($configuration);
769  }
770
771  # read all input
772
2
1
  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
6
  print join '', @reports;
779}
780
7811;