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
102070
1
use 5.022;
11
1
1
1
2
0
67
use feature 'unicode_strings';
12
1
1
1
1
4
6
use strict;
13
1
1
1
1
1
19
use warnings;
14
1
1
1
1
0
16
no warnings qw(experimental::vlb);
15
1
1
1
3
1
4
use utf8;
16
1
1
1
11
1
33
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
0
29
use File::Basename;
18
1
1
1
2
0
17
use Cwd 'abs_path';
19
1
1
1
1
0
20
use File::Spec;
20
1
1
1
1
1
18
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
0
16
use File::Path qw/ make_path /;
22
1
1
1
262
1
20
use CheckSpelling::Util;
23
1
1
1
176
1216
726
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
10
  my ($expression) = @_;
47
14
14
7
110
  return eval { qr /$expression/ };
48}
49
50sub quote_re {
51
14
12
  my ($expression) = @_;
52
14
15
  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
44
   $1 . (defined($2) ? quotemeta($2) : '')
65/xge;
66
14
15
  return $expression;
67}
68
69sub file_to_lists {
70
3
6
  my ($re) = @_;
71
3
5
  my @patterns;
72  my %hints;
73
3
0
  my $fh;
74
3
24
  if (open($fh, '<:utf8', $re)) {
75
3
8
    local $/=undef;
76
3
17
    my $file=<$fh>;
77
3
7
    close $fh;
78
3
3
    my $line_number = 0;
79
3
4
    my $hint = '';
80
3
17
    for (split /\R/, $file) {
81
17
7
      ++$line_number;
82
17
10
      chomp;
83
17
20
      if (/^#(?:\s(.+)|)/) {
84
6
13
        $hint = $1 if ($hint eq '' && defined $1);
85
6
7
        next;
86      }
87
11
16
      $hint = '' unless $_ ne '';
88
11
11
      next if $_ eq '$^';
89
11
7
      my $pattern = $_;
90
11
27
      next unless s/^(.+)/(?:$1)/;
91
7
14
      my $quoted = quote_re($1);
92
7
11
      unless (test_re $quoted) {
93
1
1
        my $error = $@;
94
1
52
        my $home = dirname(__FILE__);
95
1
32
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
96
1
9
        print STDERR $error;
97
1
2
        $_ = '(?:\$^ - skipped because bad-regex)';
98
1
1
        $hint = '';
99      }
100
7
13
      if (defined $hints{$_}) {
101
1
3
        my $pattern_length = length $pattern;
102
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
103
1
14
        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
11
        $hints{$_} = $hint;
108      }
109
7
12
      $hint = '';
110    }
111  }
112
113  return {
114
3
14
    patterns => \@patterns,
115    hints => \%hints,
116  };
117}
118
119sub file_to_list {
120
2
1100
  my ($re) = @_;
121
2
7
  my $lists = file_to_lists($re);
122
123
2
2
3
7
  return @{$lists->{'patterns'}};
124}
125
126sub list_to_re {
127
2
2
  my (@list) = @_;
128
2
5
5
3
4
4
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
129
2
5
2
6
  @list = grep { $_ ne '' } @list;
130
2
4
  return '$^' unless scalar @list;
131
2
9
  return join "|", (@list);
132}
133
134sub not_empty {
135
74
78
  my ($thing) = @_;
136
74
400
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
137}
138
139sub valid_word {
140  # shortest_word is an absolute
141
22
12
  our ($shortest, $longest, $shortest_word, $longest_word);
142
22
28
  $shortest = $shortest_word if $shortest_word;
143
22
24
  if ($longest_word) {
144    # longest_word is an absolute
145
20
26
    $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
25
163
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
153
22
23
  $word_pattern = q<\\w|'> unless $word_pattern;
154
22
59
  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
31
  $shortest = 3 unless defined $shortest;
160
22
19
  $longest = '' unless not_empty($longest);
161
22
86
  $word_match = "(?:$word_pattern){$shortest,$longest}";
162
22
232
  return qr/\b$word_match\b/;
163}
164
165sub load_dictionary {
166
12
1743
  my ($dict) = @_;
167
12
15
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
168
12
13
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
169
12
12
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
170
12
12
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
171
12
21
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
172
12
45
  $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
19
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
175
12
22
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
176
12
25
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
177
12
27
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
178
12
38
  if ($check_homoglyphs && $check_homoglyphs ne 'false') {
179
11
12
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
180
11
78
    if (-s $homoglyph_list_path) {
181
1
1
1
287
1
2939
      use CheckSpelling::Homoglyph;
182
11
19
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
183    }
184  } else {
185
1
1
    $check_homoglyphs = 0;
186  }
187
12
20
  %dictionary = ();
188
189
12
553
  open(my $dict_fh, '<:utf8', $dict);
190
12
67
  while (!eof($dict_fh)) {
191
32
34
    my $word = <$dict_fh>;
192
32
37
    chomp $word;
193
32
104
    next unless $word =~ $word_match;
194
29
33
    my $l = length $word;
195
29
22
    $longest = -1 unless not_empty($longest);
196
29
42
    $longest = $l if $l > $longest;
197
29
34
    $shortest = $l if $l < $shortest;
198
29
63
    $dictionary{$word}=1;
199  }
200
12
26
  close $dict_fh;
201
202
12
20
  $word_match = valid_word();
203}
204
205sub hunspell_dictionary {
206
3
5
  my ($dict) = @_;
207
3
3
  my $name = $dict;
208
3
6
  $name =~ s{/src/index/hunspell/index\.dic$}{};
209
3
11
  $name =~ s{.*/}{};
210
3
4
  my $aff = $dict;
211
3
3
  my $encoding;
212
3
7
  $aff =~ s/\.dic$/.aff/;
213
3
27
  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
284
    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
10682
  my ($configuration) = @_;
232
9
8
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
233
9
31
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
234
9
12
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
235
9
21
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
236
9
9
  our %forbidden_re_descriptions;
237
9
16
  if ($hunspell_dictionary_path) {
238
3
36
    our @hunspell_dictionaries = ();
239
1
1
1
1
1
1
1
1
1
3
274
1021
27
5
2
16
8
2
16
172
    if (eval 'use Text::Hunspell; 1') {
240
3
109
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
241
3
7
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
242
3
9
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
243      }
244    } else {
245
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
246    }
247  }
248
9
17
  my (@patterns_re_list, %in_patterns_re_list);
249
9
47
  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
14
    $patterns_re = undef;
255  }
256
257
9
29
  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
2
    $forbidden_re = list_to_re @forbidden_re_list;
262  } else {
263
8
10
    $forbidden_re = undef;
264  }
265
266
9
39
  if (-e "$configuration/candidates.txt") {
267
1
3
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
268
1
2
2
2
6
5
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
269
1
2
    $candidates_re = list_to_re @candidates_re_list;
270  } else {
271
8
9
    $candidates_re = undef;
272  }
273
274
9
15
  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
13
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
278
9
11
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
279
9
10
  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
11
  $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
8
  $check_images = $check_images =~ /^(?:1|true)$/i;
286
9
12
  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
8
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
292
293
9
12
  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
18
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
298
9
35
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
299
9
17
  load_dictionary($base_dict);
300}
301
302sub split_line {
303
1157
494
  our (%dictionary, $word_match, $disable_word_collating);
304
1157
483
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
305
1157
407
  our @hunspell_dictionaries;
306
1157
412
  our $shortest;
307
1157
714
  my $shortest_threshold = $shortest + 2;
308
1157
626
  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
549
  my $rsqm = "\xE2\x80\x99";
313
314
1157
630
  my ($words, $unrecognized) = (0, 0);
315
1157
744
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
316
1157
4680
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
317
1157
2024
    $line =~ s/(?:$ignore_pattern)+/ /g;
318
1157
1476
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
319
1157
2803
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
320
1157
1245
    for my $token (split /\s+/, $line) {
321
3622
3066
      next unless $token =~ /$pattern/;
322
2466
1869
      $token =~ s/^(?:'|$rsqm)+//g;
323
2466
2241
      $token =~ s/(?:'|$rsqm)+s?$//g;
324
2466
1319
      my $raw_token = $token;
325
2466
1354
      $token =~ s/^[^Ii]?'+(.*)/$1/;
326
2466
1230
      $token =~ s/(.*?)'+$/$1/;
327
2466
3380
      next unless $token =~ $word_match;
328
2312
1959
      if (defined $dictionary{$token}) {
329
1033
465
        ++$words;
330
1033
542
        $unique_ref->{$token}=1;
331
1033
818
        next;
332      }
333
1279
818
      if (@hunspell_dictionaries) {
334
1254
583
        my $found = 0;
335
1254
632
        for my $hunspell_dictionary (@hunspell_dictionaries) {
336          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
337
1254
912
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
338
1254
2310
          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
834
        next if $found;
346      }
347
1279
834
      my $key = lc $token;
348
1279
1092
      if (defined $dictionary{$key}) {
349
6
4
        ++$words;
350
6
4
        $unique_ref->{$key}=1;
351
6
19
        next;
352      }
353
1273
789
      unless ($disable_word_collating) {
354
1273
673
        $key =~ s/''+/'/g;
355
1273
1252
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
356      }
357
1273
1086
      if (defined $dictionary{$key}) {
358
0
0
        ++$words;
359
0
0
        $unique_ref->{$key}=1;
360
0
0
        next;
361      }
362
1273
626
      ++$unrecognized;
363
1273
717
      $unique_unrecognized_ref->{$raw_token}=1;
364
1273
1675
      $unrecognized_line_items_ref->{$raw_token}=1;
365    }
366
1157
1519
    return ($words, $unrecognized);
367}
368
369sub skip_file {
370
7
24
  my ($temp_dir, $reason) = @_;
371
7
181
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
372
7
37
  print $skipped_fh $reason;
373
7
104
  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
11861
  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
43
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
432
433
16
12
  our %forbidden_re_descriptions;
434
16
6
  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
12
  my $rsqm = "\xE2\x80\x99";
438
439
16
22
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
440
16
15
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
441
16
12
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
442
16
15
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
443
16
36
  my $temp_dir = tempdir(DIR=>$sandbox);
444
16
2677
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
445
16
266
  open(my $name_fh, '>', "$temp_dir/name");
446
16
34
    print $name_fh $file;
447
16
159
  close $name_fh;
448
16
208
  if (defined readlink($file) &&
449      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
450
1
3
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
451
1
4
    return $temp_dir;
452  }
453
15
28
  if ($use_magic_file) {
454
8
10742
    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
28091
      my $file_kind = <$file_fh>;
466
8
4283
      close $file_fh;
467
8
14
      my $file_converted = 0;
468
8
36
      if ($check_images && $file_kind =~ m<^image/>) {
469
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
470      }
471
8
162
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
472
2
40
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
473
2
32
        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
63
  my $file_size = -s $file;
481
13
18
  if (defined $largest_file) {
482
13
23
    unless ($check_file_names eq $file) {
483
13
22
      if ($file_size > $largest_file) {
484
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
485
1
2
        return $temp_dir;
486      }
487    }
488  }
489
12
102
  open my $file_fh, '<', $file;
490
12
15
  binmode $file_fh;
491
12
6
  my $head;
492
12
90
  read($file_fh, $head, 4096);
493
12
659
  $head =~ s/(?:\r|\n)+$//;
494
12
60
  my $dos_new_lines = () = $head =~ /\r\n/gi;
495
12
43
  my $unix_new_lines = () = $head =~ /\n/gi;
496
12
117
  my $mac_new_lines = () = $head =~ /\r/gi;
497
12
46
  local $/;
498
12
78
  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
6
    $/ = "\r";
504  } else {
505
6
7
    $/ = "\n";
506  }
507
12
22
  seek($file_fh, 0, 0);
508
12
24
  ($words, $unrecognized) = (0, 0);
509
12
34
  %unique = ();
510
12
29
  %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
104
  };
518
519
12
218
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
520
12
7
  our $timeout;
521
12
12
  eval {
522
12
0
102
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
523
12
42
    alarm $timeout;
524
525
12
11
    my $ignore_next_line = 0;
526
12
14
    my $offset = 0;
527
12
73
    while (<$file_fh>) {
528
1160
983
      if ($. == 1) {
529
12
26
        unless ($disable_minified_file) {
530
12
60
          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
3
            last;
533          }
534        }
535      }
536
1159
1982
      $_ = decode_utf8($_, FB_DEFAULT);
537
1159
2473
      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
1229
      s/\R$//;
542
1159
988
      s/^\x{FEFF}// if $. == 1;
543
1159
956
      next unless /./;
544
1158
695
      my $raw_line = $_;
545
546
1158
551
      my $ignore_this_line = $ignore_next_line;
547
1158
929
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
548
1158
742
      next if $ignore_this_line;
549
550      # hook for custom line based text exclusions:
551
1157
760
      if (defined $patterns_re) {
552
2
6
13
8
        s/($patterns_re)/"="x length($1)/ge;
553      }
554
1157
595
      my $initial_line_state = $_;
555
1157
726
      my $previous_line_state = $_;
556
1157
515
      my $line_flagged;
557
1157
706
      if ($forbidden_re) {
558
9
5
77
9
        while (s/($forbidden_re)/"="x length($1)/e) {
559
5
7
          $line_flagged = 1;
560
5
10
          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
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
564
7
4
            my $test_line = $previous_line_state;
565
7
4
59
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
566
4
6
              next unless $test_line eq $_;
567
4
6
              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
3
              $found_trigger_re = $forbidden_re_singleton;
572
4
7
              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
8
              last;
576            }
577          }
578
5
6
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
579
5
7
          if ($found_trigger_re) {
580
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
581
4
9
            $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
8
            if ($description ne '') {
584
3
16
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
585            } else {
586
1
7
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
587            }
588          } else {
589
1
5
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
590          }
591
5
20
          $previous_line_state = $_;
592        }
593
9
10
        $_ = $initial_line_state;
594      }
595      # This is to make it easier to deal w/ rules:
596
1157
949
      s/^/ /;
597
1157
625
      my %unrecognized_line_items = ();
598
1157
433
      our $check_homoglyphs;
599
1157
693
      if ($check_homoglyphs) {
600
1157
584
        my $check_line_for_homoglyphs = $_;
601
1157
679
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
602        # problematic characters: `\\`, `-`, `]`
603
1157
10762
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
604
1157
1280
        $homoglyphs = "[$homoglyphs]";
605
1157
481
        our ($longest_word, $shortest_word);
606
1157
1715
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
607
1157
540
        my $dollar = '$';
608
1157
1320
        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
9104
        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
45
          $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
1
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
616
1
8
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
617          }
618        }
619      }
620
1157
791
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
621
1157
597
      $words += $new_words;
622
1157
477
      $unrecognized += $new_unrecognized;
623
1157
707
      my $line_length = length($raw_line);
624
1157
1310
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
625
1020
472
        my $found_token = 0;
626
1020
468
        my $raw_token = $token;
627
1020
490
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
628
1020
443
        my $before;
629
1020
1357
        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
522
          $before = "(?<=$not_lower_pattern)";
635        }
636
1020
1015
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
637
1020
1768
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
638
1270
597
          $line_flagged = 1;
639
1270
517
          $found_token = 1;
640
1270
1490
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
641
1270
1058
          next unless $match =~ /./;
642
1270
763
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
643
1270
4581
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
644        }
645
1020
1092
        unless ($found_token) {
646
3
30
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
647
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
648
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
649
3
12
            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
1666
      if ($line_flagged && $candidates_re) {
658
1
3
        $_ = $previous_line_state = $initial_line_state;
659
1
1
25
3
        s/($candidates_re)/"="x length($1)/ge;
660
1
3
        if ($_ ne $initial_line_state) {
661
1
1
          $_ = $previous_line_state;
662
1
2
          for my $i (0 .. $#candidates_re_list) {
663
2
1
            my $candidate_re = $candidates_re_list[$i];
664
2
16
            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
740
      unless ($disable_minified_file) {
678
1157
827
        s/={3,}//g;
679
1157
784
        $offset += length;
680
1157
926
        my $ratio = int($offset / $.);
681
1157
556
        my $ratio_threshold = 1000;
682
1157
2868
        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
6
          last;
685        }
686      }
687    }
688
689
12
78
    alarm 0;
690  };
691
12
17
  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
40
  close $file_fh;
699
12
121
  close $warnings_fh;
700
701
12
36
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
702
11
298
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
703
11
179
      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
98
    close $stats_fh;
711
11
147
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
712
11
19
39
30
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
713
11
79
    close $unknown_fh;
714  }
715
716
12
141
  return $temp_dir;
717}
718
719sub main {
720
2
530
  my ($configuration, @ARGV) = @_;
721
2
1
  our %dictionary;
722
2
5
  unless (%dictionary) {
723
1
2
    init($configuration);
724  }
725
726  # read all input
727
2
3
  my @reports;
728
729
2
3
  for my $file (@ARGV) {
730
2
5
    my $temp_dir = split_file($file);
731
2
4
    push @reports, "$temp_dir\n";
732  }
733
2
11
  print join '', @reports;
734}
735
7361;