File Coverage

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