File Coverage

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

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
112670
1
use 5.022;
11
1
1
1
2
0
49
use feature 'unicode_strings';
12
1
1
1
2
0
9
use strict;
13
1
1
1
1
1
17
use warnings;
14
1
1
1
2
0
15
no warnings qw(experimental::vlb);
15
1
1
1
19
0
2
use utf8;
16
1
1
1
17
0
28
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
2
0
13
use Cwd 'abs_path';
19
1
1
1
1
1
20
use File::Spec;
20
1
1
1
1
1
17
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
2
0
12
use File::Path qw/ make_path /;
22
1
1
1
283
1
19
use CheckSpelling::Util;
23
1
1
1
203
1253
771
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
4
108
  return eval { qr /$expression/ };
48}
49
50sub quote_re {
51
14
10
  my ($expression) = @_;
52
14
13
  return $expression if $expression =~ /\?\{/;
53
14
31
  $expression =~ s/
54   \G
55   (
56      (?:[^\\]|\\[^Q])*
57   )
58   (?:
59      \\Q
60      (?:[^\\]|\\[^E])*
61      (?:\\E)?
62   )?
63/
64
28
47
   $1 . (defined($2) ? quotemeta($2) : '')
65/xge;
66
14
24
  return $expression;
67}
68
69sub file_to_lists {
70
3
3
  my ($re) = @_;
71
3
7
  my @patterns;
72  my %hints;
73
3
0
  my $fh;
74
3
31
  if (open($fh, '<:utf8', $re)) {
75
3
4
    local $/=undef;
76
3
24
    my $file=<$fh>;
77
3
9
    close $fh;
78
3
3
    my $line_number = 0;
79
3
4
    my $hint = '';
80
3
13
    for (split /\R/, $file) {
81
17
14
      ++$line_number;
82
17
4
      chomp;
83
17
21
      if (/^#(?:\s(.+)|)/) {
84
6
12
        $hint = $1 if ($hint eq '' && defined $1);
85
6
5
        next;
86      }
87
11
14
      $hint = '' unless $_ ne '';
88
11
9
      next if $_ eq '$^';
89
11
9
      my $pattern = $_;
90
11
28
      next unless s/^(.+)/(?:$1)/;
91
7
10
      my $quoted = quote_re($1);
92
7
9
      unless (test_re $quoted) {
93
1
24
        my $error = $@;
94
1
54
        my $home = dirname(__FILE__);
95
1
25
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
96
1
13
        print STDERR $error;
97
1
3
        $_ = '(?:\$^ - skipped because bad-regex)';
98
1
1
        $hint = '';
99      }
100
7
10
      if (defined $hints{$_}) {
101
1
1
        my $pattern_length = length $pattern;
102
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
103
1
20
        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
8
        $hints{$_} = $hint;
108      }
109
7
11
      $hint = '';
110    }
111  }
112
113  return {
114
3
16
    patterns => \@patterns,
115    hints => \%hints,
116  };
117}
118
119sub file_to_list {
120
2
1318
  my ($re) = @_;
121
2
4
  my $lists = file_to_lists($re);
122
123
2
2
1
6
  return @{$lists->{'patterns'}};
124}
125
126sub list_to_re {
127
2
2
  my (@list) = @_;
128
2
5
5
2
2
1
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
129
2
5
2
5
  @list = grep { $_ ne '' } @list;
130
2
2
  return '$^' unless scalar @list;
131
2
6
  return join "|", (@list);
132}
133
134sub not_empty {
135
74
63
  my ($thing) = @_;
136
74
324
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
137}
138
139sub valid_word {
140  # shortest_word is an absolute
141
22
11
  our ($shortest, $longest, $shortest_word, $longest_word);
142
22
27
  $shortest = $shortest_word if $shortest_word;
143
22
14
  if ($longest_word) {
144    # longest_word is an absolute
145
20
16
    $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
18
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
152
22
66
23
155
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
153
22
22
  $word_pattern = q<\\w|'> unless $word_pattern;
154
22
46
  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
16
  $longest = '' unless not_empty($longest);
161
22
79
  $word_match = "(?:$word_pattern){$shortest,$longest}";
162
22
194
  return qr/\b$word_match\b/;
163}
164
165sub load_dictionary {
166
12
1991
  my ($dict) = @_;
167
12
5
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
168
12
18
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
169
12
11
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
170
12
5
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
171
12
10
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
172
12
42
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
173
12
58
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
174
12
29
  $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
22
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
177
12
23
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
178
12
34
  if ($check_homoglyphs && $check_homoglyphs ne 'false') {
179
11
9
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
180
11
74
    if (-s $homoglyph_list_path) {
181
1
1
1
323
1
3193
      use CheckSpelling::Homoglyph;
182
11
13
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
183    }
184  } else {
185
1
0
    $check_homoglyphs = 0;
186  }
187
12
16
  %dictionary = ();
188
189
12
431
  open(my $dict_fh, '<:utf8', $dict);
190
12
51
  while (!eof($dict_fh)) {
191
32
34
    my $word = <$dict_fh>;
192
32
28
    chomp $word;
193
32
85
    next unless $word =~ $word_match;
194
29
26
    my $l = length $word;
195
29
17
    $longest = -1 unless not_empty($longest);
196
29
30
    $longest = $l if $l > $longest;
197
29
28
    $shortest = $l if $l < $shortest;
198
29
54
    $dictionary{$word}=1;
199  }
200
12
26
  close $dict_fh;
201
202
12
10
  $word_match = valid_word();
203}
204
205sub hunspell_dictionary {
206
3
3
  my ($dict) = @_;
207
3
3
  my $name = $dict;
208
3
4
  $name =~ s{/src/index/hunspell/index\.dic$}{};
209
3
12
  $name =~ s{.*/}{};
210
3
3
  my $aff = $dict;
211
3
2
  my $encoding;
212
3
4
  $aff =~ s/\.dic$/.aff/;
213
3
37
  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
8
    close $aff_fh;
220  }
221  return {
222
3
305
    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
11093
  my ($configuration) = @_;
232
9
17
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
233
9
19
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
234
9
6
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
235
9
11
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
236
9
9
  our %forbidden_re_descriptions;
237
9
8
  if ($hunspell_dictionary_path) {
238
3
37
    our @hunspell_dictionaries = ();
239
1
1
1
1
1
1
1
1
1
3
278
1097
20
5
0
13
5
2
15
148
    if (eval 'use Text::Hunspell; 1') {
240
3
164
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
241
3
10
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
242
3
6
        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
12
  my (@patterns_re_list, %in_patterns_re_list);
249
9
55
  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
7
    $patterns_re = undef;
255  }
256
257
9
35
  if (-e "$configuration/forbidden.txt") {
258
1
2
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
259
1
1
0
2
    @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
6
    $forbidden_re = undef;
264  }
265
266
9
46
  if (-e "$configuration/candidates.txt") {
267
1
2
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
268
1
2
2
2
2
6
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
269
1
1
    $candidates_re = list_to_re @candidates_re_list;
270  } else {
271
8
5
    $candidates_re = undef;
272  }
273
274
9
12
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
275
276
9
9
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
277
9
9
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
278
9
3
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
279
9
6
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
280
281
9
9
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
282
9
5
  $ignore_next_line_pattern =~ s/\s+/|/g;
283
284
9
8
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
285
9
6
  $check_images = $check_images =~ /^(?:1|true)$/i;
286
9
8
  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
5
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
292
293
9
8
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
294
295
9
8
  $word_match = valid_word();
296
297
9
11
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
298
9
44
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
299
9
8
  load_dictionary($base_dict);
300}
301
302sub split_line {
303
1157
632
  our (%dictionary, $word_match, $disable_word_collating);
304
1157
437
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
305
1157
461
  our @hunspell_dictionaries;
306
1157
500
  our $shortest;
307
1157
813
  my $shortest_threshold = $shortest + 2;
308
1157
631
  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
572
  my $rsqm = "\xE2\x80\x99";
313
314
1157
732
  my ($words, $unrecognized) = (0, 0);
315
1157
832
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
316
1157
5435
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
317
1157
2237
    $line =~ s/(?:$ignore_pattern)+/ /g;
318
1157
1803
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
319
1157
3448
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
320
1157
1451
    for my $token (split /\s+/, $line) {
321
3622
3614
      next unless $token =~ /$pattern/;
322
2466
2103
      $token =~ s/^(?:'|$rsqm)+//g;
323
2466
2524
      $token =~ s/(?:'|$rsqm)+s?$//g;
324
2466
1457
      my $raw_token = $token;
325
2466
1476
      $token =~ s/^[^Ii]?'+(.*)/$1/;
326
2466
1235
      $token =~ s/(.*?)'+$/$1/;
327
2466
3877
      next unless $token =~ $word_match;
328
2312
2116
      if (defined $dictionary{$token}) {
329
1033
497
        ++$words;
330
1033
539
        $unique_ref->{$token}=1;
331
1033
843
        next;
332      }
333
1279
981
      if (@hunspell_dictionaries) {
334
1254
662
        my $found = 0;
335
1254
763
        for my $hunspell_dictionary (@hunspell_dictionaries) {
336          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
337
1254
1165
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
338
1254
2980
          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
979
        next if $found;
346      }
347
1279
950
      my $key = lc $token;
348
1279
1185
      if (defined $dictionary{$key}) {
349
6
4
        ++$words;
350
6
5
        $unique_ref->{$key}=1;
351
6
6
        next;
352      }
353
1273
902
      unless ($disable_word_collating) {
354
1273
746
        $key =~ s/''+/'/g;
355
1273
1357
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
356      }
357
1273
1120
      if (defined $dictionary{$key}) {
358
0
0
        ++$words;
359
0
0
        $unique_ref->{$key}=1;
360
0
0
        next;
361      }
362
1273
651
      ++$unrecognized;
363
1273
793
      $unique_unrecognized_ref->{$raw_token}=1;
364
1273
1714
      $unrecognized_line_items_ref->{$raw_token}=1;
365    }
366
1157
1716
    return ($words, $unrecognized);
367}
368
369sub skip_file {
370
7
18
  my ($temp_dir, $reason) = @_;
371
7
216
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
372
7
39
  print $skipped_fh $reason;
373
7
113
  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;
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
11929
  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
45
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
432
433
16
10
  our %forbidden_re_descriptions;
434
16
4
  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
13
  my $rsqm = "\xE2\x80\x99";
438
439
16
14
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
440
16
10
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
441
16
11
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
442
16
9
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
443
16
32
  my $temp_dir = tempdir(DIR=>$sandbox);
444
16
2545
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
445
16
441
  open(my $name_fh, '>', "$temp_dir/name");
446
16
37
    print $name_fh $file;
447
16
219
  close $name_fh;
448
16
190
  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
3
    return $temp_dir;
452  }
453
15
21
  if ($use_magic_file) {
454
8
12808
    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
30732
      my $file_kind = <$file_fh>;
466
8
4946
      close $file_fh;
467
8
11
      my $file_converted = 0;
468
8
18
      if ($check_images && $file_kind =~ m<^image/>) {
469
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
470      }
471
8
214
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
472
2
35
        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
100
  my $file_size = -s $file;
481
13
14
  if (defined $largest_file) {
482
13
15
    unless ($check_file_names eq $file) {
483
13
14
      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
141
  open my $file_fh, '<', $file;
490
12
10
  binmode $file_fh;
491
12
6
  my $head;
492
12
101
  read($file_fh, $head, 4096);
493
12
776
  $head =~ s/(?:\r|\n)+$//;
494
12
57
  my $dos_new_lines = () = $head =~ /\r\n/gi;
495
12
34
  my $unix_new_lines = () = $head =~ /\n/gi;
496
12
127
  my $mac_new_lines = () = $head =~ /\r/gi;
497
12
56
  local $/;
498
12
75
  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
7
    $/ = "\r";
504  } else {
505
6
6
    $/ = "\n";
506  }
507
12
32
  seek($file_fh, 0, 0);
508
12
17
  ($words, $unrecognized) = (0, 0);
509
12
39
  %unique = ();
510
12
30
  %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
118
  };
518
519
12
325
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
520
12
10
  our $timeout;
521
12
14
  eval {
522
12
0
101
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
523
12
33
    alarm $timeout;
524
525
12
16
    my $ignore_next_line = 0;
526
12
9
    my $offset = 0;
527
12
88
    while (<$file_fh>) {
528
1160
1044
      if ($. == 1) {
529
12
19
        unless ($disable_minified_file) {
530
12
49
          if ($file_size >= 512 && length($_) == $file_size) {
531
1
12
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
532
1
4
            last;
533          }
534        }
535      }
536
1159
2488
      $_ = decode_utf8($_, FB_DEFAULT);
537
1159
2810
      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
1484
      s/\R$//;
542
1159
1143
      s/^\x{FEFF}// if $. == 1;
543
1159
1120
      next unless /./;
544
1158
754
      my $raw_line = $_;
545
546
1158
611
      my $ignore_this_line = $ignore_next_line;
547
1158
998
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
548
1158
797
      next if $ignore_this_line;
549
550      # hook for custom line based text exclusions:
551
1157
793
      if (defined $patterns_re) {
552
2
6
11
7
        s/($patterns_re)/"="x length($1)/ge;
553      }
554
1157
678
      my $initial_line_state = $_;
555
1157
677
      my $previous_line_state = $_;
556
1157
554
      my $line_flagged;
557
1157
792
      if ($forbidden_re) {
558
9
5
62
10
        while (s/($forbidden_re)/"="x length($1)/e) {
559
5
4
          $line_flagged = 1;
560
5
9
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
561
5
4
          my $found_trigger_re;
562
5
6
          for my $i (0 .. $#forbidden_re_list) {
563
7
4
            my $forbidden_re_singleton = $forbidden_re_list[$i];
564
7
4
            my $test_line = $previous_line_state;
565
7
4
60
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
566
4
5
              next unless $test_line eq $_;
567
4
5
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
568
4
5
              next unless $begin == $begin_test;
569
4
4
              next unless $end == $end_test;
570
4
2
              next unless $match eq $match_test;
571
4
4
              $found_trigger_re = $forbidden_re_singleton;
572
4
6
              my $hit = "$.:$begin:$end";
573
4
4
              $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
5
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
579
5
6
          if ($found_trigger_re) {
580
4
9
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
581
4
7
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
582
4
4
            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
13
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
585            } else {
586
1
5
              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
24
          $previous_line_state = $_;
592        }
593
9
8
        $_ = $initial_line_state;
594      }
595      # This is to make it easier to deal w/ rules:
596
1157
1093
      s/^/ /;
597
1157
755
      my %unrecognized_line_items = ();
598
1157
570
      our $check_homoglyphs;
599
1157
773
      if ($check_homoglyphs) {
600
1157
690
        my $check_line_for_homoglyphs = $_;
601
1157
667
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
602        # problematic characters: `\\`, `-`, `]`
603
1157
10960
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
604
1157
1576
        $homoglyphs = "[$homoglyphs]";
605
1157
500
        our ($longest_word, $shortest_word);
606
1157
1848
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
607
1157
605
        my $dollar = '$';
608
1157
1762
        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
11154
        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
54
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
612
1
1
          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
1
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
616
1
15
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
617          }
618        }
619      }
620
1157
1067
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
621
1157
709
      $words += $new_words;
622
1157
561
      $unrecognized += $new_unrecognized;
623
1157
783
      my $line_length = length($raw_line);
624
1157
1661
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
625
1020
529
        my $found_token = 0;
626
1020
493
        my $raw_token = $token;
627
1020
532
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
628
1020
459
        my $before;
629
1020
1673
        if ($token =~ /^$upper_pattern$lower_pattern/) {
630
5
2
          $before = '(?<=.)';
631        } elsif ($token =~ /^$upper_pattern/) {
632
0
0
          $before = "(?<!$upper_pattern)";
633        } else {
634
1015
619
          $before = "(?<=$not_lower_pattern)";
635        }
636
1020
1203
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
637
1020
2184
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
638
1270
638
          $line_flagged = 1;
639
1270
545
          $found_token = 1;
640
1270
1736
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
641
1270
1303
          next unless $match =~ /./;
642
1270
932
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
643
1270
5078
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
644        }
645
1020
1191
        unless ($found_token) {
646
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
647
3
5
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
648
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
649
3
11
            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
1815
      if ($line_flagged && $candidates_re) {
658
1
2
        $_ = $previous_line_state = $initial_line_state;
659
1
1
17
2
        s/($candidates_re)/"="x length($1)/ge;
660
1
1
        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
13
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
665
1
1
5
2
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
666
1
2
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
667
1
2
              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
837
      unless ($disable_minified_file) {
678
1157
930
        s/={3,}//g;
679
1157
784
        $offset += length;
680
1157
1055
        my $ratio = int($offset / $.);
681
1157
588
        my $ratio_threshold = 1000;
682
1157
3299
        if ($ratio > $ratio_threshold) {
683
2
10
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
684
2
7
          last;
685        }
686      }
687    }
688
689
12
91
    alarm 0;
690  };
691
12
10
  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
44
  close $file_fh;
699
12
153
  close $warnings_fh;
700
701
12
26
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
702
11
309
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
703
11
154
      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
140
    close $stats_fh;
711
11
247
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
712
11
19
46
29
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
713
11
127
    close $unknown_fh;
714  }
715
716
12
140
  return $temp_dir;
717}
718
719sub main {
720
2
379
  my ($configuration, @ARGV) = @_;
721
2
1
  our %dictionary;
722
2
2
  unless (%dictionary) {
723
1
1
    init($configuration);
724  }
725
726  # read all input
727
2
2
  my @reports;
728
729
2
2
  for my $file (@ARGV) {
730
2
2
    my $temp_dir = split_file($file);
731
2
4
    push @reports, "$temp_dir\n";
732  }
733
2
6
  print join '', @reports;
734}
735
7361;