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
114492
2
use 5.022;
11
1
1
1
2
1
57
use feature 'unicode_strings';
12
1
1
1
5
0
8
use strict;
13
1
1
1
1
0
25
use warnings;
14
1
1
1
1
1
51
no warnings qw(experimental::vlb);
15
1
1
1
3
0
4
use utf8;
16
1
1
1
14
1
36
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
38
use File::Basename;
18
1
1
1
2
0
19
use Cwd 'abs_path';
19
1
1
1
2
1
20
use File::Spec;
20
1
1
1
1
1
21
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
2
0
17
use File::Path qw/ make_path /;
22
1
1
1
272
1
21
use CheckSpelling::Util;
23
1
1
1
193
1417
794
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
4
109
  return eval { qr /$expression/ };
48}
49
50sub quote_re {
51
14
13
  my ($expression) = @_;
52
14
12
  return $expression if $expression =~ /\?\{/;
53
14
33
  $expression =~ s/
54   \G
55   (
56      (?:[^\\]|\\[^Q])*
57   )
58   (?:
59      \\Q
60      (?:[^\\]|\\[^E])*
61      (?:\\E)?
62   )?
63/
64
28
52
   $1 . (defined($2) ? quotemeta($2) : '')
65/xge;
66
14
13
  return $expression;
67}
68
69sub file_to_lists {
70
3
4
  my ($re) = @_;
71
3
5
  my @patterns;
72  my %hints;
73
3
0
  my $fh;
74
3
30
  if (open($fh, '<:utf8', $re)) {
75
3
5
    local $/=undef;
76
3
23
    my $file=<$fh>;
77
3
9
    close $fh;
78
3
3
    my $line_number = 0;
79
3
4
    my $hint = '';
80
3
15
    for (split /\R/, $file) {
81
17
8
      ++$line_number;
82
17
10
      chomp;
83
17
21
      if (/^#(?:\s(.+)|)/) {
84
6
12
        $hint = $1 if ($hint eq '' && defined $1);
85
6
7
        next;
86      }
87
11
12
      $hint = '' unless $_ ne '';
88
11
13
      next if $_ eq '$^';
89
11
9
      my $pattern = $_;
90
11
30
      next unless s/^(.+)/(?:$1)/;
91
7
8
      my $quoted = quote_re($1);
92
7
11
      unless (test_re $quoted) {
93
1
3
        my $error = $@;
94
1
44
        my $home = dirname(__FILE__);
95
1
29
        $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
13
      if (defined $hints{$_}) {
101
1
2
        my $pattern_length = length $pattern;
102
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
103
1
21
        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
6
        push @patterns, $_;
107
6
10
        $hints{$_} = $hint;
108      }
109
7
14
      $hint = '';
110    }
111  }
112
113  return {
114
3
16
    patterns => \@patterns,
115    hints => \%hints,
116  };
117}
118
119sub file_to_list {
120
2
1610
  my ($re) = @_;
121
2
6
  my $lists = file_to_lists($re);
122
123
2
2
1
8
  return @{$lists->{'patterns'}};
124}
125
126sub list_to_re {
127
2
3
  my (@list) = @_;
128
2
5
5
2
2
5
  @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
7
  return join "|", (@list);
132}
133
134sub not_empty {
135
74
64
  my ($thing) = @_;
136
74
466
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
137}
138
139sub valid_word {
140  # shortest_word is an absolute
141
22
15
  our ($shortest, $longest, $shortest_word, $longest_word);
142
22
27
  $shortest = $shortest_word if $shortest_word;
143
22
22
  if ($longest_word) {
144    # longest_word is an absolute
145
20
22
    $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
21
169
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
153
22
21
  $word_pattern = q<\\w|'> unless $word_pattern;
154
22
55
  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
23
  $shortest = 3 unless defined $shortest;
160
22
24
  $longest = '' unless not_empty($longest);
161
22
86
  $word_match = "(?:$word_pattern){$shortest,$longest}";
162
22
211
  return qr/\b$word_match\b/;
163}
164
165sub load_dictionary {
166
12
2065
  my ($dict) = @_;
167
12
6
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
168
12
16
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
169
12
22
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
170
12
9
  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
53
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
173
12
29
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
174
12
27
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
175
12
23
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
176
12
28
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
177
12
24
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
178
12
35
  if ($check_homoglyphs && $check_homoglyphs ne 'false') {
179
11
10
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
180
11
82
    if (-s $homoglyph_list_path) {
181
1
1
1
303
1
3302
      use CheckSpelling::Homoglyph;
182
11
16
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
183    }
184  } else {
185
1
1
    $check_homoglyphs = 0;
186  }
187
12
20
  %dictionary = ();
188
189
12
559
  open(my $dict_fh, '<:utf8', $dict);
190
12
65
  while (!eof($dict_fh)) {
191
32
36
    my $word = <$dict_fh>;
192
32
24
    chomp $word;
193
32
95
    next unless $word =~ $word_match;
194
29
27
    my $l = length $word;
195
29
22
    $longest = -1 unless not_empty($longest);
196
29
31
    $longest = $l if $l > $longest;
197
29
26
    $shortest = $l if $l < $shortest;
198
29
63
    $dictionary{$word}=1;
199  }
200
12
32
  close $dict_fh;
201
202
12
11
  $word_match = valid_word();
203}
204
205sub hunspell_dictionary {
206
3
5
  my ($dict) = @_;
207
3
4
  my $name = $dict;
208
3
4
  $name =~ s{/src/index/hunspell/index\.dic$}{};
209
3
15
  $name =~ s{.*/}{};
210
3
3
  my $aff = $dict;
211
3
2
  my $encoding;
212
3
7
  $aff =~ s/\.dic$/.aff/;
213
3
33
  if (open my $aff_fh, '<', $aff) {
214
3
21
    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
292
    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
11570
  my ($configuration) = @_;
232
9
9
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
233
9
32
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
234
9
10
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
235
9
39
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
236
9
6
  our %forbidden_re_descriptions;
237
9
12
  if ($hunspell_dictionary_path) {
238
3
38
    our @hunspell_dictionaries = ();
239
1
1
1
1
1
1
1
1
1
3
309
1060
21
5
1
14
8
1
19
180
    if (eval 'use Text::Hunspell; 1') {
240
3
125
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
241
3
9
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
242
3
8
        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
14
  my (@patterns_re_list, %in_patterns_re_list);
249
9
63
  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
12
    $patterns_re = undef;
255  }
256
257
9
38
  if (-e "$configuration/forbidden.txt") {
258
1
3
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
259
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
260
1
1
1
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
261
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
262  } else {
263
8
14
    $forbidden_re = undef;
264  }
265
266
9
42
  if (-e "$configuration/candidates.txt") {
267
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
268
1
2
2
2
2
8
    @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
38
    $candidates_re = undef;
272  }
273
274
9
18
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
275
276
9
13
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
277
9
12
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
278
9
7
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
279
9
8
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
280
281
9
10
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
282
9
9
  $ignore_next_line_pattern =~ s/\s+/|/g;
283
284
9
9
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
285
9
10
  $check_images = $check_images =~ /^(?:1|true)$/i;
286
9
13
  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
10
  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
12
  $word_match = valid_word();
296
297
9
16
  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
35
  load_dictionary($base_dict);
300}
301
302sub split_line {
303
1157
483
  our (%dictionary, $word_match, $disable_word_collating);
304
1157
479
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
305
1157
486
  our @hunspell_dictionaries;
306
1157
530
  our $shortest;
307
1157
805
  my $shortest_threshold = $shortest + 2;
308
1157
727
  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
568
  my $rsqm = "\xE2\x80\x99";
313
314
1157
771
  my ($words, $unrecognized) = (0, 0);
315
1157
941
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
316
1157
5496
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
317
1157
2270
    $line =~ s/(?:$ignore_pattern)+/ /g;
318
1157
1927
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
319
1157
3320
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
320
1157
1374
    for my $token (split /\s+/, $line) {
321
3622
3413
      next unless $token =~ /$pattern/;
322
2466
2162
      $token =~ s/^(?:'|$rsqm)+//g;
323
2466
2570
      $token =~ s/(?:'|$rsqm)+s?$//g;
324
2466
1476
      my $raw_token = $token;
325
2466
1462
      $token =~ s/^[^Ii]?'+(.*)/$1/;
326
2466
1319
      $token =~ s/(.*?)'+$/$1/;
327
2466
3942
      next unless $token =~ $word_match;
328
2312
2221
      if (defined $dictionary{$token}) {
329
1033
494
        ++$words;
330
1033
589
        $unique_ref->{$token}=1;
331
1033
842
        next;
332      }
333
1279
1131
      if (@hunspell_dictionaries) {
334
1254
689
        my $found = 0;
335
1254
773
        for my $hunspell_dictionary (@hunspell_dictionaries) {
336          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
337
1254
1135
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
338
1254
3117
          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
981
        next if $found;
346      }
347
1279
1004
      my $key = lc $token;
348
1279
1166
      if (defined $dictionary{$key}) {
349
6
4
        ++$words;
350
6
3
        $unique_ref->{$key}=1;
351
6
8
        next;
352      }
353
1273
963
      unless ($disable_word_collating) {
354
1273
694
        $key =~ s/''+/'/g;
355
1273
1368
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
356      }
357
1273
1215
      if (defined $dictionary{$key}) {
358
0
0
        ++$words;
359
0
0
        $unique_ref->{$key}=1;
360
0
0
        next;
361      }
362
1273
708
      ++$unrecognized;
363
1273
830
      $unique_unrecognized_ref->{$raw_token}=1;
364
1273
1714
      $unrecognized_line_items_ref->{$raw_token}=1;
365    }
366
1157
1694
    return ($words, $unrecognized);
367}
368
369sub skip_file {
370
7
29
  my ($temp_dir, $reason) = @_;
371
7
232
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
372
7
42
  print $skipped_fh $reason;
373
7
135
  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
13375
  my ($file) = @_;
421  our (
422
16
13
    $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
45
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
432
433
16
10
  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
15
  my $rsqm = "\xE2\x80\x99";
438
439
16
23
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
440
16
18
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
441
16
16
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
442
16
12
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
443
16
37
  my $temp_dir = tempdir(DIR=>$sandbox);
444
16
2968
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
445
16
417
  open(my $name_fh, '>', "$temp_dir/name");
446
16
41
    print $name_fh $file;
447
16
225
  close $name_fh;
448
16
198
  if (defined readlink($file) &&
449      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
450
1
4
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
451
1
5
    return $temp_dir;
452  }
453
15
41
  if ($use_magic_file) {
454
8
14080
    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
30757
      my $file_kind = <$file_fh>;
466
8
5022
      close $file_fh;
467
8
21
      my $file_converted = 0;
468
8
23
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
469
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
470      }
471
8
197
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
472
2
28
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
473
2
40
        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
90
  my $file_size = -s $file;
481
13
21
  if (defined $largest_file) {
482
13
21
    unless ($check_file_names eq $file) {
483
13
16
      if ($file_size > $largest_file) {
484
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
485
1
3
        return $temp_dir;
486      }
487    }
488  }
489
12
152
  open my $file_fh, '<', $file;
490
12
11
  binmode $file_fh;
491
12
9
  my $head;
492
12
106
  read($file_fh, $head, 4096);
493
12
828
  $head =~ s/(?:\r|\n)+$//;
494
12
59
  my $dos_new_lines = () = $head =~ /\r\n/gi;
495
12
41
  my $unix_new_lines = () = $head =~ /\n/gi;
496
12
112
  my $mac_new_lines = () = $head =~ /\r/gi;
497
12
61
  local $/;
498
12
86
  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
7
    $/ = "\r\n";
502  } elsif ($mac_new_lines > $unix_new_lines) {
503
2
7
    $/ = "\r";
504  } else {
505
6
7
    $/ = "\n";
506  }
507
12
27
  seek($file_fh, 0, 0);
508
12
16
  ($words, $unrecognized) = (0, 0);
509
12
41
  %unique = ();
510
12
32
  %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
124
  };
518
519
12
396
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
520
12
8
  our $timeout;
521
12
18
  eval {
522
12
0
102
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
523
12
36
    alarm $timeout;
524
525
12
17
    my $ignore_next_line = 0;
526
12
13
    my $offset = 0;
527
12
91
    while (<$file_fh>) {
528
1160
1185
      if ($. == 1) {
529
12
21
        unless ($disable_minified_file) {
530
12
61
          if ($file_size >= 512 && length($_) == $file_size) {
531
1
10
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
532
1
5
            last;
533          }
534        }
535      }
536
1159
2639
      $_ = decode_utf8($_, FB_DEFAULT);
537
1159
2979
      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
1535
      s/\R$//;
542
1159
1102
      s/^\x{FEFF}// if $. == 1;
543
1159
1164
      next unless /./;
544
1158
873
      my $raw_line = $_;
545
546
1158
707
      my $ignore_this_line = $ignore_next_line;
547
1158
1069
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
548
1158
807
      next if $ignore_this_line;
549
550      # hook for custom line based text exclusions:
551
1157
814
      if (defined $patterns_re) {
552
2
6
12
8
        s/($patterns_re)/"="x length($1)/ge;
553      }
554
1157
649
      my $initial_line_state = $_;
555
1157
725
      my $previous_line_state = $_;
556
1157
595
      my $line_flagged;
557
1157
788
      if ($forbidden_re) {
558
9
5
70
12
        while (s/($forbidden_re)/"="x length($1)/e) {
559
5
5
          $line_flagged = 1;
560
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
561
5
3
          my $found_trigger_re;
562
5
6
          for my $i (0 .. $#forbidden_re_list) {
563
7
7
            my $forbidden_re_singleton = $forbidden_re_list[$i];
564
7
5
            my $test_line = $previous_line_state;
565
7
4
59
8
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
566
4
5
              next unless $test_line eq $_;
567
4
7
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
568
4
4
              next unless $begin == $begin_test;
569
4
3
              next unless $end == $end_test;
570
4
4
              next unless $match eq $match_test;
571
4
2
              $found_trigger_re = $forbidden_re_singleton;
572
4
9
              my $hit = "$.:$begin:$end";
573
4
3
              $forbidden_re_hits[$i]++;
574
4
5
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
575
4
7
              last;
576            }
577          }
578
5
6
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
579
5
6
          if ($found_trigger_re) {
580
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
581
4
10
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
582
4
3
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
583
4
3
            if ($description ne '') {
584
3
15
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
585            } else {
586
1
6
              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
26
          $previous_line_state = $_;
592        }
593
9
8
        $_ = $initial_line_state;
594      }
595      # This is to make it easier to deal w/ rules:
596
1157
1130
      s/^/ /;
597
1157
801
      my %unrecognized_line_items = ();
598
1157
445
      our $check_homoglyphs;
599
1157
776
      if ($check_homoglyphs) {
600
1157
647
        my $check_line_for_homoglyphs = $_;
601
1157
725
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
602        # problematic characters: `\\`, `-`, `]`
603
1157
10921
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
604
1157
1525
        $homoglyphs = "[$homoglyphs]";
605
1157
557
        our ($longest_word, $shortest_word);
606
1157
1938
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
607
1157
586
        my $dollar = '$';
608
1157
1853
        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
11356
        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
2
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
611
1
50
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
612
1
2
          if (defined $dictionary{$token}) {
613
1
1
            my $token_raw = CheckSpelling::Util::wrap_in_backticks($token_raw);
614
1
1
            my $token = CheckSpelling::Util::wrap_in_backticks($token);
615
1
2
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
616
1
9
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
617          }
618        }
619      }
620
1157
1064
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
621
1157
714
      $words += $new_words;
622
1157
569
      $unrecognized += $new_unrecognized;
623
1157
810
      my $line_length = length($raw_line);
624
1157
1738
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
625
1020
518
        my $found_token = 0;
626
1020
502
        my $raw_token = $token;
627
1020
523
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
628
1020
458
        my $before;
629
1020
1883
        if ($token =~ /^$upper_pattern$lower_pattern/) {
630
5
5
          $before = '(?<=.)';
631        } elsif ($token =~ /^$upper_pattern/) {
632
0
0
          $before = "(?<!$upper_pattern)";
633        } else {
634
1015
659
          $before = "(?<=$not_lower_pattern)";
635        }
636
1020
1219
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
637
1020
2177
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
638
1270
641
          $line_flagged = 1;
639
1270
497
          $found_token = 1;
640
1270
1816
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
641
1270
1232
          next unless $match =~ /./;
642
1270
986
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
643
1270
5053
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
644        }
645
1020
1160
        unless ($found_token) {
646
3
74
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
647
3
7
            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
1885
      if ($line_flagged && $candidates_re) {
658
1
1
        $_ = $previous_line_state = $initial_line_state;
659
1
1
20
2
        s/($candidates_re)/"="x length($1)/ge;
660
1
2
        if ($_ ne $initial_line_state) {
661
1
2
          $_ = $previous_line_state;
662
1
1
          for my $i (0 .. $#candidates_re_list) {
663
2
2
            my $candidate_re = $candidates_re_list[$i];
664
2
14
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
665
1
1
6
2
            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
1
              $candidates_re_hits[$i] += $replacements;
671
1
2
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
672
1
2
              $_ = $previous_line_state;
673            }
674          }
675        }
676      }
677
1157
962
      unless ($disable_minified_file) {
678
1157
973
        s/={3,}//g;
679
1157
915
        $offset += length;
680
1157
1095
        my $ratio = int($offset / $.);
681
1157
734
        my $ratio_threshold = 1000;
682
1157
3280
        if ($ratio > $ratio_threshold) {
683
2
11
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
684
2
10
          last;
685        }
686      }
687    }
688
689
12
93
    alarm 0;
690  };
691
12
15
  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
49
  close $file_fh;
699
12
173
  close $warnings_fh;
700
701
12
36
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
702
11
371
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
703
11
181
      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
173
    close $stats_fh;
711
11
247
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
712
11
19
54
29
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
713
11
125
    close $unknown_fh;
714  }
715
716
12
155
  return $temp_dir;
717}
718
719sub main {
720
2
496
  my ($configuration, @ARGV) = @_;
721
2
1
  our %dictionary;
722
2
3
  unless (%dictionary) {
723
1
2
    init($configuration);
724  }
725
726  # read all input
727
2
2
  my @reports;
728
729
2
3
  for my $file (@ARGV) {
730
2
3
    my $temp_dir = split_file($file);
731
2
4
    push @reports, "$temp_dir\n";
732  }
733
2
9
  print join '', @reports;
734}
735
7361;