File Coverage

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

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
109232
2
use 5.022;
11
1
1
1
2
1
51
use feature 'unicode_strings';
12
1
1
1
1
5
6
use strict;
13
1
1
1
1
1
21
use warnings;
14
1
1
1
2
0
16
no warnings qw(experimental::vlb);
15
1
1
1
1
0
3
use utf8;
16
1
1
1
10
1
32
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
1
1
14
use Cwd 'abs_path';
19
1
1
1
1
0
19
use File::Spec;
20
1
1
1
1
1
20
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
1
14
use File::Path qw/ make_path /;
22
1
1
1
278
0
20
use CheckSpelling::Util;
23
1
1
1
207
1265
776
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
8
127
  return eval { qr /$expression/ };
50}
51
52sub quote_re {
53
14
11
  my ($expression) = @_;
54
14
13
  return $expression if $expression =~ /\?\{/;
55
14
53
  $expression =~ s/
56   \G
57   (
58      (?:[^\\]|\\[^Q])*
59   )
60   (?:
61      \\Q
62      (?:[^\\]|\\[^E])*
63      (?:\\E)?
64   )?
65/
66
28
50
   $1 . (defined($2) ? quotemeta($2) : '')
67/xge;
68
14
15
  return $expression;
69}
70
71sub file_to_lists {
72
3
6
  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
25
    my $file=<$fh>;
79
3
9
    close $fh;
80
3
3
    my $line_number = 0;
81
3
2
    my $hint = '';
82
3
14
    for (split /\R/, $file) {
83
17
10
      ++$line_number;
84
17
7
      chomp;
85
17
23
      if (/^#(?:\s(.+)|)/) {
86
6
13
        $hint = $1 if ($hint eq '' && defined $1);
87
6
6
        next;
88      }
89
11
14
      $hint = '' unless $_ ne '';
90
11
11
      next if $_ eq '$^';
91
11
8
      my $pattern = $_;
92
11
28
      next unless s/^(.+)/(?:$1)/;
93
7
10
      my $quoted = quote_re($1);
94
7
9
      unless (test_re $quoted) {
95
1
3
        my $error = $@;
96
1
54
        my $home = dirname(__FILE__);
97
1
26
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
98
1
11
        print STDERR $error;
99
1
2
        $_ = '(?:\$^ - skipped because bad-regex)';
100
1
3
        $hint = '';
101      }
102
7
11
      if (defined $hints{$_}) {
103
1
1
        my $pattern_length = length $pattern;
104
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
105
1
18
        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
11
        $hints{$_} = $hint;
110      }
111
7
12
      $hint = '';
112    }
113  }
114
115  return {
116
3
15
    patterns => \@patterns,
117    hints => \%hints,
118  };
119}
120
121sub file_to_list {
122
2
1357
  my ($re) = @_;
123
2
7
  my $lists = file_to_lists($re);
124
125
2
2
1
8
  return @{$lists->{'patterns'}};
126}
127
128sub list_to_re {
129
2
3
  my (@list) = @_;
130
2
5
5
3
5
5
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
131
2
5
2
6
  @list = grep { $_ ne '' } @list;
132
2
3
  return '$^' unless scalar @list;
133
2
6
  return join "|", (@list);
134}
135
136sub not_empty {
137
76
71
  my ($thing) = @_;
138
76
451
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
139}
140
141sub valid_word {
142  # shortest_word is an absolute
143
22
35
  our ($shortest, $longest, $shortest_word, $longest_word);
144
22
24
  $shortest = $shortest_word if $shortest_word;
145
22
21
  if ($longest_word) {
146    # longest_word is an absolute
147
20
20
    $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
27
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
154
22
66
18
151
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
155
22
20
  $word_pattern = q<\\w|'> unless $word_pattern;
156
22
49
  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
28
  $shortest = 3 unless defined $shortest;
162
22
32
  $longest = '' unless not_empty($longest);
163
22
98
  $word_match = "(?:$word_pattern){$shortest,$longest}";
164
22
210
  return qr/\b$word_match\b/;
165}
166
167sub load_dictionary {
168
12
2045
  my ($dict) = @_;
169
12
5
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
170
12
13
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
171
12
12
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
172
12
9
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
173
12
19
  $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
26
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
176
12
22
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
177
12
24
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
178
12
24
  $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
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
75
    if (-s $homoglyph_list_path) {
183
1
1
1
343
1
3344
      use CheckSpelling::Homoglyph;
184
11
14
      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
731
  open(my $dict_fh, '<:utf8', $dict);
194
12
16
  my $word_match_relaxed = $word_match;
195
12
136
  if ($word_match =~ /\{(\d+),/) {
196
12
15
    my $three = $1;
197
12
16
    if ($three > 1) {
198
12
12
      my $two = $three - 1;
199
12
97
      $word_match_relaxed =~ s/\b$three\b/$two/g;
200    }
201  }
202
12
62
  while (!eof($dict_fh)) {
203
32
36
    my $word = <$dict_fh>;
204
32
35
    chomp $word;
205
32
195
    next unless $word =~ $word_match_relaxed;
206
31
44
    my $l = length $word;
207
31
24
    $longest = -1 unless not_empty($longest);
208
31
65
    $longest = $l if $l > $longest;
209
31
68
    if ($word =~ $word_match) {
210
29
31
      $shortest = $l if $l < $shortest;
211    }
212
31
60
    $dictionary{$word}=1;
213  }
214
12
32
  close $dict_fh;
215
216
12
12
  $word_match = valid_word();
217}
218
219sub hunspell_dictionary {
220
3
5
  my ($dict) = @_;
221
3
6
  my $name = $dict;
222
3
4
  $name =~ s{/src/index/hunspell/index\.dic$}{};
223
3
14
  $name =~ s{.*/}{};
224
3
6
  my $aff = $dict;
225
3
2
  my $encoding;
226
3
9
  $aff =~ s/\.dic$/.aff/;
227
3
34
  if (open my $aff_fh, '<', $aff) {
228
3
24
    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
346
    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
11782
  my ($configuration) = @_;
246
9
6
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
247
9
35
  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
24
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
250
9
6
  our %forbidden_re_descriptions;
251
9
7
  our @reject_re_list;
252
9
3
  our $reject_re;
253
9
13
  if ($hunspell_dictionary_path) {
254
3
44
    our @hunspell_dictionaries = ();
255
1
1
1
1
1
1
1
1
1
3
333
1548
20
3
1
16
6
1
16
183
    if (eval 'use Text::Hunspell; 1') {
256
3
129
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
257
3
9
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
258
3
11
        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
11
  my (@patterns_re_list, %in_patterns_re_list);
265
9
63
  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
11
    $patterns_re = undef;
271  }
272
273
9
42
  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
2
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
277
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
278  } else {
279
8
9
    $forbidden_re = undef;
280  }
281
282
9
48
  if (-e "$configuration/candidates.txt") {
283
1
3
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
284
1
2
2
2
2
5
    @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
8
    $candidates_re = undef;
288  }
289
290
9
45
  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
12
    $reject_re = '$^';
296  }
297
298
9
11
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
299
300
9
12
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
301
9
13
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
302
9
5
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
303
9
7
  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
9
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
309
9
9
  $check_images = $check_images =~ /^(?:1|true)$/i;
310
9
7
  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
5
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
318
319
9
11
  $word_match = valid_word();
320
321
9
16
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
322
9
43
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
323
9
10
  load_dictionary($base_dict);
324}
325
326sub split_line {
327
1158
505
  our (%dictionary, $word_match, $disable_word_collating);
328
1158
461
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
329
1158
415
  our @hunspell_dictionaries;
330
1158
436
  our $shortest;
331
1158
720
  my $shortest_threshold = $shortest + 2;
332
1158
566
  my $pattern = '.';
333  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
334
335  # https://www.fileformat.info/info/unicode/char/2019/
336
1158
487
  my $rsqm = "\xE2\x80\x99";
337
338
1158
649
  my ($words, $unrecognized) = (0, 0);
339
1158
732
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
340
1158
4643
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
341
1158
1967
    $line =~ s/(?:$ignore_pattern)+/ /g;
342
1158
1434
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
343
1158
2849
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
344
1158
1137
    for my $token (split /\s+/, $line) {
345
3624
2978
      next unless $token =~ /$pattern/;
346
2467
1848
      $token =~ s/^(?:'|$rsqm)+//g;
347
2467
2320
      $token =~ s/(?:'|$rsqm)+s?$//g;
348
2467
1345
      my $raw_token = $token;
349
2467
1276
      $token =~ s/^[^Ii]?'+//; # need to reconsider for French
350
2467
1138
      $token =~ s/'+$//;
351
2467
3471
      next unless $token =~ $word_match;
352
2312
1821
      if (defined $dictionary{$token}) {
353
1033
477
        ++$words;
354
1033
542
        $unique_ref->{$token}=1;
355
1033
895
        next;
356      }
357
1279
853
      if (@hunspell_dictionaries) {
358
1254
582
        my $found = 0;
359
1254
650
        for my $hunspell_dictionary (@hunspell_dictionaries) {
360          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
361
1254
905
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
362
1254
2051
          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
837
        next if $found;
370      }
371
1279
822
      my $key = lc $token;
372
1279
959
      if (defined $dictionary{$key}) {
373
6
2
        ++$words;
374
6
4
        $unique_ref->{$key}=1;
375
6
8
        next;
376      }
377
1273
795
      unless ($disable_word_collating) {
378
1273
645
        $key =~ s/''+/'/g;
379
1273
1052
        $key =~ s/'[sd]$// if length $key >= $shortest_threshold;
380      }
381
1273
919
      if (defined $dictionary{$key}) {
382
0
0
        ++$words;
383
0
0
        $unique_ref->{$key}=1;
384
0
0
        next;
385      }
386
1273
611
      ++$unrecognized;
387
1273
693
      $unique_unrecognized_ref->{$raw_token}=1;
388
1273
1488
      $unrecognized_line_items_ref->{$raw_token}=1;
389    }
390
1158
1381
    return ($words, $unrecognized);
391}
392
393sub skip_file {
394
7
31
  my ($temp_dir, $reason) = @_;
395
7
236
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
396
7
40
  print $skipped_fh $reason;
397
7
110
  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
1273
721
  my ($warnings_fh, $begin, $end, $match) = @_;
445
1273
521
  our $reject_re;
446
1273
777
  my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
447
1273
1127
  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
1273
4178
    print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
463  }
464}
465
466sub split_file {
467
16
12997
  my ($file) = @_;
468  our (
469
16
4
    $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
16
39
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
479
480
16
8
  our %forbidden_re_descriptions;
481
16
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
16
15
  my $rsqm = "\xE2\x80\x99";
485
486
16
21
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
487
16
17
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
488
16
14
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
489
16
16
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
490
16
28
  my $temp_dir = tempdir(DIR=>$sandbox);
491
16
2995
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
492
16
436
  open(my $name_fh, '>', "$temp_dir/name");
493
16
35
    print $name_fh $file;
494
16
214
  close $name_fh;
495
16
214
  if (defined readlink($file) &&
496      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
497
1
4
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
498
1
6
    return $temp_dir;
499  }
500
15
27
  if ($use_magic_file) {
501
8
13567
    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
31951
      my $file_kind = <$file_fh>;
513
8
3999
      close $file_fh;
514
8
13
      my $file_converted = 0;
515
8
26
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
516
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
517      }
518
8
194
      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
47
        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
13
81
  my $file_size = -s $file;
528
13
15
  if (defined $largest_file) {
529
13
16
    unless ($check_file_names eq $file) {
530
13
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
3
        return $temp_dir;
533      }
534    }
535  }
536
12
155
  open my $file_fh, '<', $file;
537
12
10
  binmode $file_fh;
538
12
9
  my $head;
539
12
188
  read($file_fh, $head, 4096);
540
12
850
  $head =~ s/(?:\r|\n)+$//;
541
12
62
  my $dos_new_lines = () = $head =~ /\r\n/gi;
542
12
35
  my $unix_new_lines = () = $head =~ /\n/gi;
543
12
133
  my $mac_new_lines = () = $head =~ /\r/gi;
544
12
60
  local $/;
545
12
92
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
546
3
6
    $/ = "\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
9
    $/ = "\r";
551  } else {
552
6
6
    $/ = "\n";
553  }
554
12
30
  seek($file_fh, 0, 0);
555
12
27
  ($words, $unrecognized) = (0, 0);
556
12
39
  %unique = ();
557
12
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
12
123
  };
565
566
12
335
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
567
12
6
  our $timeout;
568
12
12
  eval {
569
12
0
92
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
570
12
33
    alarm $timeout;
571
572
12
16
    my $ignore_next_line = 0;
573
12
14
    my $offset = 0;
574
12
96
    while (<$file_fh>) {
575
1160
865
      if ($. == 1) {
576
12
19
        unless ($disable_minified_file) {
577
12
68
          if ($file_size >= 512 && length($_) == $file_size) {
578
1
11
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
579
1
4
            last;
580          }
581        }
582
11
21
        s/^\x{FEFF}//;
583      }
584
1159
1816
      $_ = decode_utf8($_, FB_DEFAULT);
585
1159
2243
      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
1159
1272
      s/\R$//;
590
1159
937
      next unless /./;
591
1159
653
      my $raw_line = $_;
592
593
1159
600
      my $ignore_this_line = $ignore_next_line;
594
1159
879
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
595
1159
693
      next if $ignore_this_line;
596
597      # hook for custom line based text exclusions:
598
1158
717
      if (defined $patterns_re) {
599
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
600      }
601
1158
614
      my $initial_line_state = $_;
602
1158
625
      my $previous_line_state = $_;
603
1158
500
      my $line_flagged;
604
1158
700
      if ($forbidden_re) {
605
9
5
72
11
        while (s/($forbidden_re)/"="x length($1)/e) {
606
5
3
          $line_flagged = 1;
607
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
608
5
41
          my $found_trigger_re;
609
5
4
          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
83
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
613
4
6
              next unless $test_line eq $_;
614
4
9
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
615
4
5
              next unless $begin == $begin_test;
616
4
0
              next unless $end == $end_test;
617
4
5
              next unless $match eq $match_test;
618
4
4
              $found_trigger_re = $forbidden_re_singleton;
619
4
8
              my $hit = "$.:$begin:$end";
620
4
3
              $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
8
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
626
5
5
          if ($found_trigger_re) {
627
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
628
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
629
4
5
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
630
4
6
            if ($description ne '') {
631
3
16
              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
25
          $previous_line_state = $_;
639        }
640
9
8
        $_ = $initial_line_state;
641      }
642      # This is to make it easier to deal w/ rules:
643
1158
1014
      s/^/ /;
644
1158
585
      my %unrecognized_line_items = ();
645
1158
480
      our $check_homoglyphs;
646
1158
648
      if ($check_homoglyphs) {
647
1158
650
        my $check_line_for_homoglyphs = $_;
648
1158
607
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
649        # problematic characters: `\\`, `-`, `]`
650
1158
11441
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
651
1158
1195
        $homoglyphs = "[$homoglyphs]";
652
1158
450
        our ($longest_word, $shortest_word);
653
1158
1555
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
654
1158
562
        my $dollar = '$';
655
1158
1393
        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
1158
9791
        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
54
          $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
2
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
663
1
14
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
664          }
665        }
666      }
667
1158
874
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
668
1158
562
      $words += $new_words;
669
1158
488
      $unrecognized += $new_unrecognized;
670
1158
721
      my $line_length = length($raw_line);
671
1158
1225
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
672
1020
441
        my $found_token = 0;
673
1020
450
        my $raw_token = $token;
674
1020
514
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
675
1020
421
        my $before;
676
1020
1393
        if ($token =~ /^$upper_pattern$lower_pattern/) {
677
5
4
          $before = '(?<=.)';
678        } elsif ($token =~ /^$upper_pattern/) {
679
0
0
          $before = "(?<!$upper_pattern)";
680        } else {
681
1015
509
          $before = "(?<=$not_lower_pattern)";
682        }
683
1020
1091
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
684
1020
1812
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
685
1270
582
          $line_flagged = 1;
686
1270
515
          $found_token = 1;
687
1270
1422
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
688
1270
1074
          next unless $match =~ /./;
689
1270
745
          print_word_not_in_dictionary($warnings_fh, $begin, $end, $match);
690        }
691
1020
985
        unless ($found_token) {
692
3
31
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
693
3
7
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
694
3
2
            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
1158
1402
      if ($line_flagged && $candidates_re) {
703
1
1
        $_ = $previous_line_state = $initial_line_state;
704
1
1
22
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
3
            my $candidate_re = $candidates_re_list[$i];
709
2
15
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
710
1
1
6
3
            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
2
              $_ = $previous_line_state;
714
1
1
31
2
              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
3
              $_ = $previous_line_state;
718            }
719          }
720        }
721      }
722
1158
759
      unless ($disable_minified_file) {
723
1158
805
        s/={3,}//g;
724
1158
757
        $offset += length;
725
1158
887
        my $ratio = int($offset / $.);
726
1158
515
        my $ratio_threshold = 1000;
727
1158
2567
        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
12
94
    alarm 0;
735  };
736
12
46
  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
12
69
  close $file_fh;
744
12
158
  close $warnings_fh;
745
746
12
42
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
747
11
364
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
748
11
159
      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
11
169
    close $stats_fh;
756
11
226
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
757
11
19
40
32
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
758
11
112
    close $unknown_fh;
759  }
760
761
12
146
  return $temp_dir;
762}
763
764sub main {
765
2
632
  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
4
  for my $file (@ARGV) {
775
2
2
    my $temp_dir = split_file($file);
776
2
4
    push @reports, "$temp_dir\n";
777  }
778
2
7
  print join '', @reports;
779}
780
7811;