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
109459
3
use 5.022;
11
1
1
1
2
0
48
use feature 'unicode_strings';
12
1
1
1
2
1
8
use strict;
13
1
1
1
1
1
20
use warnings;
14
1
1
1
1
1
12
no warnings qw(experimental::vlb);
15
1
1
1
21
1
2
use utf8;
16
1
1
1
16
0
25
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
22
use File::Basename;
18
1
1
1
4
0
15
use Cwd 'abs_path';
19
1
1
1
1
1
19
use File::Spec;
20
1
1
1
2
0
20
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
1
12
use File::Path qw/ make_path /;
22
1
1
1
273
0
20
use CheckSpelling::Util;
23
1
1
1
189
1205
770
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
13
  my ($expression) = @_;
47
14
14
7
127
  return eval { qr /$expression/ };
48}
49
50sub quote_re {
51
14
14
  my ($expression) = @_;
52
14
10
  return $expression if $expression =~ /\?\{/;
53
14
35
  $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
17
  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
28
  if (open($fh, '<:utf8', $re)) {
75
3
6
    local $/=undef;
76
3
23
    my $file=<$fh>;
77
3
9
    close $fh;
78
3
3
    my $line_number = 0;
79
3
2
    my $hint = '';
80
3
13
    for (split /\R/, $file) {
81
17
12
      ++$line_number;
82
17
7
      chomp;
83
17
23
      if (/^#(?:\s(.+)|)/) {
84
6
13
        $hint = $1 if ($hint eq '' && defined $1);
85
6
4
        next;
86      }
87
11
12
      $hint = '' unless $_ ne '';
88
11
13
      next if $_ eq '$^';
89
11
8
      my $pattern = $_;
90
11
27
      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
45
        my $home = dirname(__FILE__);
95
1
21
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
96
1
18
        print STDERR $error;
97
1
2
        $_ = '(?:\$^ - skipped because bad-regex)';
98
1
3
        $hint = '';
99      }
100
7
11
      if (defined $hints{$_}) {
101
1
2
        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
7
        push @patterns, $_;
107
6
9
        $hints{$_} = $hint;
108      }
109
7
12
      $hint = '';
110    }
111  }
112
113  return {
114
3
12
    patterns => \@patterns,
115    hints => \%hints,
116  };
117}
118
119sub file_to_list {
120
2
1169
  my ($re) = @_;
121
2
5
  my $lists = file_to_lists($re);
122
123
2
2
2
7
  return @{$lists->{'patterns'}};
124}
125
126sub list_to_re {
127
2
3
  my (@list) = @_;
128
2
5
5
2
5
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
7
  return join "|", (@list);
132}
133
134sub not_empty {
135
74
58
  my ($thing) = @_;
136
74
363
  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
19
  if ($longest_word) {
144    # longest_word is an absolute
145
20
17
    $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
17
165
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
153
22
20
  $word_pattern = q<\\w|'> unless $word_pattern;
154
22
35
  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
22
  $shortest = 3 unless defined $shortest;
160
22
15
  $longest = '' unless not_empty($longest);
161
22
111
  $word_match = "(?:$word_pattern){$shortest,$longest}";
162
22
192
  return qr/\b$word_match\b/;
163}
164
165sub load_dictionary {
166
12
2013
  my ($dict) = @_;
167
12
12
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
168
12
10
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
169
12
10
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
170
12
4
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
171
12
13
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
172
12
41
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
173
12
26
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
174
12
19
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
175
12
20
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
176
12
22
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
177
12
18
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
178
12
30
  if ($check_homoglyphs && $check_homoglyphs !~ /false/i) {
179
11
6
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
180
11
68
    if (-s $homoglyph_list_path) {
181
1
1
1
286
1
3117
      use CheckSpelling::Homoglyph;
182
11
12
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
183    } else {
184
0
0
      $check_homoglyphs = 0;
185    }
186  } else {
187
1
0
    $check_homoglyphs = 0;
188  }
189
12
13
  %dictionary = ();
190
191
12
485
  open(my $dict_fh, '<:utf8', $dict);
192
12
49
  while (!eof($dict_fh)) {
193
32
51
    my $word = <$dict_fh>;
194
32
28
    chomp $word;
195
32
82
    next unless $word =~ $word_match;
196
29
26
    my $l = length $word;
197
29
19
    $longest = -1 unless not_empty($longest);
198
29
31
    $longest = $l if $l > $longest;
199
29
24
    $shortest = $l if $l < $shortest;
200
29
59
    $dictionary{$word}=1;
201  }
202
12
23
  close $dict_fh;
203
204
12
8
  $word_match = valid_word();
205}
206
207sub hunspell_dictionary {
208
3
4
  my ($dict) = @_;
209
3
3
  my $name = $dict;
210
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
211
3
13
  $name =~ s{.*/}{};
212
3
3
  my $aff = $dict;
213
3
3
  my $encoding;
214
3
9
  $aff =~ s/\.dic$/.aff/;
215
3
32
  if (open my $aff_fh, '<', $aff) {
216
3
21
    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
329
    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
10662
  my ($configuration) = @_;
234
9
10
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
235
9
18
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
236
9
9
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
237
9
16
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
238
9
2
  our %forbidden_re_descriptions;
239
9
8
  if ($hunspell_dictionary_path) {
240
3
30
    our @hunspell_dictionaries = ();
241
1
1
1
1
1
1
1
1
1
3
270
1012
20
5
1
13
7
2
16
188
    if (eval 'use Text::Hunspell; 1') {
242
3
118
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
243
3
8
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
244
3
8
        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
20
  my (@patterns_re_list, %in_patterns_re_list);
251
9
53
  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
8
    $patterns_re = undef;
257  }
258
259
9
33
  if (-e "$configuration/forbidden.txt") {
260
1
2
    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
2
    $forbidden_re = list_to_re @forbidden_re_list;
264  } else {
265
8
7
    $forbidden_re = undef;
266  }
267
268
9
35
  if (-e "$configuration/candidates.txt") {
269
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
270
1
2
2
2
2
5
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
271
1
1
    $candidates_re = list_to_re @candidates_re_list;
272  } else {
273
8
8
    $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
9
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
279
9
10
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
280
9
7
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
281
9
2
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
282
283
9
8
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
284
9
7
  $ignore_next_line_pattern =~ s/\s+/|/g;
285
286
9
8
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
287
9
8
  $check_images = $check_images =~ /^(?:1|true)$/i;
288
9
6
  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
5
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
296
297
9
6
  $word_match = valid_word();
298
299
9
15
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
300
9
40
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
301
9
12
  load_dictionary($base_dict);
302}
303
304sub split_line {
305
1157
501
  our (%dictionary, $word_match, $disable_word_collating);
306
1157
548
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
307
1157
575
  our @hunspell_dictionaries;
308
1157
427
  our $shortest;
309
1157
786
  my $shortest_threshold = $shortest + 2;
310
1157
630
  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
538
  my $rsqm = "\xE2\x80\x99";
315
316
1157
723
  my ($words, $unrecognized) = (0, 0);
317
1157
811
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
318
1157
5537
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
319
1157
2295
    $line =~ s/(?:$ignore_pattern)+/ /g;
320
1157
1807
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
321
1157
3415
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
322
1157
1359
    for my $token (split /\s+/, $line) {
323
3622
3370
      next unless $token =~ /$pattern/;
324
2466
2194
      $token =~ s/^(?:'|$rsqm)+//g;
325
2466
2536
      $token =~ s/(?:'|$rsqm)+s?$//g;
326
2466
1478
      my $raw_token = $token;
327
2466
1459
      $token =~ s/^[^Ii]?'+(.*)/$1/;
328
2466
1304
      $token =~ s/(.*?)'+$/$1/;
329
2466
3888
      next unless $token =~ $word_match;
330
2312
2192
      if (defined $dictionary{$token}) {
331
1033
497
        ++$words;
332
1033
573
        $unique_ref->{$token}=1;
333
1033
885
        next;
334      }
335
1279
997
      if (@hunspell_dictionaries) {
336
1254
679
        my $found = 0;
337
1254
787
        for my $hunspell_dictionary (@hunspell_dictionaries) {
338          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
339
1254
1091
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
340
1254
3120
          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
983
        next if $found;
348      }
349
1279
1025
      my $key = lc $token;
350
1279
1249
      if (defined $dictionary{$key}) {
351
6
3
        ++$words;
352
6
4
        $unique_ref->{$key}=1;
353
6
8
        next;
354      }
355
1273
933
      unless ($disable_word_collating) {
356
1273
743
        $key =~ s/''+/'/g;
357
1273
1462
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
358      }
359
1273
1166
      if (defined $dictionary{$key}) {
360
0
0
        ++$words;
361
0
0
        $unique_ref->{$key}=1;
362
0
0
        next;
363      }
364
1273
689
      ++$unrecognized;
365
1273
798
      $unique_unrecognized_ref->{$raw_token}=1;
366
1273
1747
      $unrecognized_line_items_ref->{$raw_token}=1;
367    }
368
1157
1727
    return ($words, $unrecognized);
369}
370
371sub skip_file {
372
7
21
  my ($temp_dir, $reason) = @_;
373
7
217
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
374
7
33
  print $skipped_fh $reason;
375
7
109
  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
11907
  my ($file) = @_;
423  our (
424
16
7
    $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
41
  $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
8
  my $rsqm = "\xE2\x80\x99";
440
441
16
18
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
442
16
8
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
443
16
15
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
444
16
41
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
445
16
29
  my $temp_dir = tempdir(DIR=>$sandbox);
446
16
2554
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
447
16
400
  open(my $name_fh, '>', "$temp_dir/name");
448
16
33
    print $name_fh $file;
449
16
206
  close $name_fh;
450
16
188
  if (defined readlink($file) &&
451      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
452
1
4
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
453
1
3
    return $temp_dir;
454  }
455
15
23
  if ($use_magic_file) {
456
8
11829
    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
29169
      my $file_kind = <$file_fh>;
468
8
4774
      close $file_fh;
469
8
12
      my $file_converted = 0;
470
8
21
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
471
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
472      }
473
8
146
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
474
2
26
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
475
2
37
        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
62
  my $file_size = -s $file;
483
13
13
  if (defined $largest_file) {
484
13
12
    unless ($check_file_names eq $file) {
485
13
16
      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
116
  open my $file_fh, '<', $file;
492
12
11
  binmode $file_fh;
493
12
5
  my $head;
494
12
101
  read($file_fh, $head, 4096);
495
12
775
  $head =~ s/(?:\r|\n)+$//;
496
12
44
  my $dos_new_lines = () = $head =~ /\r\n/gi;
497
12
30
  my $unix_new_lines = () = $head =~ /\n/gi;
498
12
101
  my $mac_new_lines = () = $head =~ /\r/gi;
499
12
52
  local $/;
500
12
74
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
501
3
6
    $/ = "\n";
502  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
503
1
6
    $/ = "\r\n";
504  } elsif ($mac_new_lines > $unix_new_lines) {
505
2
5
    $/ = "\r";
506  } else {
507
6
7
    $/ = "\n";
508  }
509
12
23
  seek($file_fh, 0, 0);
510
12
16
  ($words, $unrecognized) = (0, 0);
511
12
34
  %unique = ();
512
12
25
  %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
92
  };
520
521
12
310
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
522
12
8
  our $timeout;
523
12
12
  eval {
524
12
0
81
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
525
12
33
    alarm $timeout;
526
527
12
15
    my $ignore_next_line = 0;
528
12
11
    my $offset = 0;
529
12
83
    while (<$file_fh>) {
530
1160
1060
      if ($. == 1) {
531
12
20
        unless ($disable_minified_file) {
532
12
49
          if ($file_size >= 512 && length($_) == $file_size) {
533
1
9
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
534
1
3
            last;
535          }
536        }
537      }
538
1159
2484
      $_ = decode_utf8($_, FB_DEFAULT);
539
1159
2930
      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
1517
      s/\R$//;
544
1159
1052
      s/^\x{FEFF}// if $. == 1;
545
1159
1142
      next unless /./;
546
1158
827
      my $raw_line = $_;
547
548
1158
714
      my $ignore_this_line = $ignore_next_line;
549
1158
1094
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
550
1158
812
      next if $ignore_this_line;
551
552      # hook for custom line based text exclusions:
553
1157
850
      if (defined $patterns_re) {
554
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
555      }
556
1157
701
      my $initial_line_state = $_;
557
1157
724
      my $previous_line_state = $_;
558
1157
597
      my $line_flagged;
559
1157
879
      if ($forbidden_re) {
560
9
5
61
12
        while (s/($forbidden_re)/"="x length($1)/e) {
561
5
4
          $line_flagged = 1;
562
5
10
          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
7
            my $forbidden_re_singleton = $forbidden_re_list[$i];
566
7
2
            my $test_line = $previous_line_state;
567
7
4
60
9
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
568
4
4
              next unless $test_line eq $_;
569
4
7
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
570
4
4
              next unless $begin == $begin_test;
571
4
4
              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
8
              my $hit = "$.:$begin:$end";
575
4
3
              $forbidden_re_hits[$i]++;
576
4
7
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
577
4
5
              last;
578            }
579          }
580
5
5
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
581
5
6
          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
15
              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
4
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
592          }
593
5
25
          $previous_line_state = $_;
594        }
595
9
9
        $_ = $initial_line_state;
596      }
597      # This is to make it easier to deal w/ rules:
598
1157
1177
      s/^/ /;
599
1157
805
      my %unrecognized_line_items = ();
600
1157
483
      our $check_homoglyphs;
601
1157
851
      if ($check_homoglyphs) {
602
1157
686
        my $check_line_for_homoglyphs = $_;
603
1157
721
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
604        # problematic characters: `\\`, `-`, `]`
605
1157
10896
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
606
1157
1369
        $homoglyphs = "[$homoglyphs]";
607
1157
597
        our ($longest_word, $shortest_word);
608
1157
2037
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
609
1157
681
        my $dollar = '$';
610
1157
1793
        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
11121
        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
3
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
613
1
48
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
614
1
1
          if (defined $dictionary{$token}) {
615
1
1
            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
32
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
619          }
620        }
621      }
622
1157
1113
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
623
1157
690
      $words += $new_words;
624
1157
528
      $unrecognized += $new_unrecognized;
625
1157
783
      my $line_length = length($raw_line);
626
1157
1739
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
627
1020
542
        my $found_token = 0;
628
1020
494
        my $raw_token = $token;
629
1020
509
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
630
1020
441
        my $before;
631
1020
1712
        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
649
          $before = "(?<=$not_lower_pattern)";
637        }
638
1020
1234
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
639
1020
2208
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
640
1270
595
          $line_flagged = 1;
641
1270
502
          $found_token = 1;
642
1270
1764
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
643
1270
1244
          next unless $match =~ /./;
644
1270
945
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
645
1270
5132
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
646        }
647
1020
1183
        unless ($found_token) {
648
3
29
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
649
3
4
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
650
3
4
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
651
3
11
            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
1888
      if ($line_flagged && $candidates_re) {
660
1
2
        $_ = $previous_line_state = $initial_line_state;
661
1
1
17
3
        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
14
            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
2
              $_ = $previous_line_state;
671
1
1
4
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
672
1
2
              $candidates_re_hits[$i] += $replacements;
673
1
1
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
674
1
3
              $_ = $previous_line_state;
675            }
676          }
677        }
678      }
679
1157
970
      unless ($disable_minified_file) {
680
1157
992
        s/={3,}//g;
681
1157
819
        $offset += length;
682
1157
1175
        my $ratio = int($offset / $.);
683
1157
597
        my $ratio_threshold = 1000;
684
1157
3320
        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
7
          last;
687        }
688      }
689    }
690
691
12
69
    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
42
  close $file_fh;
701
12
137
  close $warnings_fh;
702
703
12
30
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
704
11
347
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
705
11
157
      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
149
    close $stats_fh;
713
11
239
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
714
11
19
39
27
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
715
11
120
    close $unknown_fh;
716  }
717
718
12
179
  return $temp_dir;
719}
720
721sub main {
722
2
350
  my ($configuration, @ARGV) = @_;
723
2
1
  our %dictionary;
724
2
3
  unless (%dictionary) {
725
1
0
    init($configuration);
726  }
727
728  # read all input
729
2
2
  my @reports;
730
731
2
2
  for my $file (@ARGV) {
732
2
2
    my $temp_dir = split_file($file);
733
2
4
    push @reports, "$temp_dir\n";
734  }
735
2
7
  print join '', @reports;
736}
737
7381;