File Coverage

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