File Coverage

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

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
110449
1
use 5.022;
11
1
1
1
2
1
63
use feature 'unicode_strings';
12
1
1
1
2
0
9
use strict;
13
1
1
1
1
0
20
use warnings;
14
1
1
1
1
1
13
no warnings qw(experimental::vlb);
15
1
1
1
2
0
2
use utf8;
16
1
1
1
13
1
27
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
1
1
12
use Cwd 'abs_path';
19
1
1
1
1
1
19
use File::Spec;
20
1
1
1
1
1
18
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
0
12
use File::Path qw/ make_path /;
22
1
1
1
320
1
19
use CheckSpelling::Util;
23
1
1
1
207
1230
927
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 $begin_block_re = '';
29my @begin_block_list = ();
30my @end_block_list = ();
31my ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
32my ($shortest, $longest) = (255, 0);
33my @forbidden_re_list;
34my %forbidden_re_descriptions;
35my @candidates_re_list;
36my $hunspell_dictionary_path;
37my @hunspell_dictionaries;
38my %dictionary = ();
39my $base_dict;
40my %unique;
41my %unique_unrecognized;
42my ($last_file, $words, $unrecognized) = ('', 0, 0);
43my ($ignore_next_line_pattern);
44my ($check_images, $ocr_directory);
45
46my $disable_flags;
47
48sub test_re {
49
32
22
  my ($expression) = @_;
50
32
32
16
213
  return eval { qr /$expression/ };
51}
52
53sub quote_re {
54
34
33
  my ($expression) = @_;
55
34
28
  return $expression if $expression =~ /\?\{/;
56
34
71
  $expression =~ s/
57   \G
58   (
59      (?:[^\\]|\\[^Q])*
60   )
61   (?:
62      \\Q
63      (?:[^\\]|\\[^E])*
64      (?:\\E)?
65   )?
66/
67
68
100
   $1 . (defined($2) ? quotemeta($2) : '')
68/xge;
69
34
41
  return $expression;
70}
71
72sub file_to_lists {
73
6
6
  my ($re) = @_;
74
6
9
  my @patterns;
75  my %hints;
76
6
0
  my $fh;
77
6
60
  if (open($fh, '<:utf8', $re)) {
78
6
8
    local $/=undef;
79
6
45
    my $file=<$fh>;
80
6
17
    close $fh;
81
6
5
    my $line_number = 0;
82
6
6
    my $hint = '';
83
6
26
    for (split /\R/, $file) {
84
32
16
      ++$line_number;
85
32
21
      chomp;
86
32
33
      if (/^#(?:\s(.+)|)/) {
87
12
28
        $hint = $1 if ($hint eq '' && defined $1);
88
12
12
        next;
89      }
90
20
20
      $hint = '' unless $_ ne '';
91
20
17
      next if $_ eq '$^';
92
20
15
      my $pattern = $_;
93
20
52
      next unless s/^(.+)/(?:$1)/;
94
13
17
      my $quoted = quote_re($1);
95
13
15
      unless (test_re $quoted) {
96
1
1
        my $error = $@;
97
1
58
        my $home = dirname(__FILE__);
98
1
26
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
99
1
14
        print STDERR $error;
100
1
2
        $_ = '(?:\$^ - skipped because bad-regex)';
101
1
2
        $hint = '';
102      }
103
13
22
      if (defined $hints{$_}) {
104
1
1
        my $pattern_length = length $pattern;
105
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
106
1
16
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
107
1
2
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
108      } else {
109
12
13
        push @patterns, $_;
110
12
12
        $hints{$_} = $hint;
111      }
112
13
39
      $hint = '';
113    }
114  }
115
116  return {
117
6
21
    patterns => \@patterns,
118    hints => \%hints,
119  };
120}
121
122sub file_to_list {
123
5
1311
  my ($re) = @_;
124
5
6
  my $lists = file_to_lists($re);
125
126
5
5
3
17
  return @{$lists->{'patterns'}};
127}
128
129sub list_to_re {
130
5
5
  my (@list) = @_;
131
5
11
11
6
4
11
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
132
5
11
5
11
  @list = grep { $_ ne '' } @list;
133
5
7
  return '$^' unless scalar @list;
134
5
12
  return join "|", (@list);
135}
136
137sub not_empty {
138
107
88
  my ($thing) = @_;
139
107
449
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
140}
141
142sub parse_block_list {
143
3
1
  my ($re) = @_;
144
3
3
  my @file;
145
3
29
  return @file unless (open(my $file_fh, '<:utf8', $re));
146
147
3
4
  local $/=undef;
148
3
24
  my $file=<$file_fh>;
149
3
4
  my $last_line = $.;
150
3
8
  close $file_fh;
151
3
10
  for (split /\R/, $file) {
152
8
10
    next if /^#/;
153
5
4
    chomp;
154
5
4
    s/^\\#/#/;
155
5
7
    next unless /^./;
156
5
7
    push @file, $_;
157  }
158
159
3
4
  my $pairs = (0+@file) / 2;
160
3
25
  my $true_pairs = $pairs | 0;
161
3
4
  unless ($pairs == $true_pairs) {
162
1
1
    my $early_warnings = CheckSpelling::Util::get_file_from_env('early_warnings', '/dev/null');
163
1
9
    open my $early_warnings_fh, ">>:encoding(UTF-8)", $early_warnings;
164
1
32
    print $early_warnings_fh "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
165
1
21
    close $early_warnings_fh;
166
1
1
    my $i = 0;
167
1
2
    while ($i < $true_pairs) {
168
0
0
      print STDERR "block-delimiter $i S: $file[$i*2]\n";
169
0
0
      print STDERR "block-delimiter $i E: $file[$i*2+1]\n";
170
0
0
      $i++;
171    }
172
1
11
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
173
1
3
    @file = ();
174  }
175
176
3
10
  return @file;
177}
178
179sub valid_word {
180  # shortest_word is an absolute
181
28
20
  our ($shortest, $longest, $shortest_word, $longest_word);
182
28
32
  $shortest = $shortest_word if $shortest_word;
183
28
25
  if ($longest_word) {
184    # longest_word is an absolute
185
26
27
    $longest = $longest_word;
186  } elsif (not_empty($longest)) {
187    # we allow for some sloppiness (a couple of stuck keys per word)
188    # it's possible that this should scale with word length
189
1
1
    $longest += 2;
190  }
191
28
16
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
192
28
84
26
197
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
193
28
24
  $word_pattern = q<\\w|'> unless $word_pattern;
194
28
53
  if ((defined $shortest && not_empty($longest)) &&
195      ($shortest > $longest)) {
196
0
0
    $word_pattern = "(?:$word_pattern){3}";
197
0
0
    return qr/$word_pattern/;
198  }
199
28
28
  $shortest = 3 unless defined $shortest;
200
28
26
  $longest = '' unless not_empty($longest);
201
28
109
  $word_match = "(?:$word_pattern){$shortest,$longest}";
202
28
255
  return qr/\b$word_match\b/;
203}
204
205sub load_dictionary {
206
15
1771
  my ($dict) = @_;
207
15
7
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
208
15
13
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
209
15
12
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
210
15
9
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
211
15
20
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
212
15
51
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
213
15
33
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
214
15
29
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
215
15
26
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
216
15
27
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
217
15
29
  our $check_homoglyphs = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_HOMOGLYPHS', 0);
218
15
35
  if ($check_homoglyphs && $check_homoglyphs ne 'false') {
219
14
12
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
220
14
96
    if (-s $homoglyph_list_path) {
221
1
1
1
374
1
3285
      use CheckSpelling::Homoglyph;
222
14
32
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
223    }
224  } else {
225
1
1
    $check_homoglyphs = 0;
226  }
227
15
30
  %dictionary = ();
228
229
15
457
  open(my $dict_fh, '<:utf8', $dict);
230
15
81
  while (!eof($dict_fh)) {
231
53
53
    my $word = <$dict_fh>;
232
53
45
    chomp $word;
233
53
131
    next unless $word =~ $word_match;
234
50
56
    my $l = length $word;
235
50
26
    $longest = -1 unless not_empty($longest);
236
50
44
    $longest = $l if $l > $longest;
237
50
47
    $shortest = $l if $l < $shortest;
238
50
93
    $dictionary{$word}=1;
239  }
240
15
35
  close $dict_fh;
241
242
15
15
  $word_match = valid_word();
243}
244
245sub hunspell_dictionary {
246
3
6
  my ($dict) = @_;
247
3
4
  my $name = $dict;
248
3
6
  $name =~ s{/src/index/hunspell/index\.dic$}{};
249
3
12
  $name =~ s{.*/}{};
250
3
5
  my $aff = $dict;
251
3
4
  my $encoding;
252
3
9
  $aff =~ s/\.dic$/.aff/;
253
3
36
  if (open my $aff_fh, '<', $aff) {
254
3
21
    while (<$aff_fh>) {
255
0
0
      next unless /^SET\s+(\S+)/;
256
0
0
      $encoding = $1 if ($1 !~ /utf-8/i);
257
0
0
      last;
258    }
259
3
10
    close $aff_fh;
260  }
261  return {
262
3
303
    name => $name,
263    dict => $dict,
264    aff => $aff,
265    encoding => $encoding,
266    engine => Text::Hunspell->new($aff, $dict),
267  }
268}
269
270sub init {
271
12
15145
  my ($configuration) = @_;
272
12
13
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
273
12
7
  our ($begin_block_re, @begin_block_list, @end_block_list);
274
12
39
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
275
12
12
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
276
12
26
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
277
12
6
  our %forbidden_re_descriptions;
278
12
13
  if ($hunspell_dictionary_path) {
279
3
59
    our @hunspell_dictionaries = ();
280
1
1
1
1
1
1
1
1
1
3
335
1157
25
5
1
14
9
3
16
167
    if (eval 'use Text::Hunspell; 1') {
281
3
121
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
282
3
10
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
283
3
7
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
284      }
285    } else {
286
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
287    }
288  }
289
290
12
77
  if (-e "$configuration/block-delimiters.list") {
291
3
5
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
292
3
4
    if (@block_delimiters) {
293
2
2
      @begin_block_list = ();
294
2
3
      @end_block_list = ();
295
296
2
2
      while (@block_delimiters) {
297
2
4
        my ($begin, $end) = splice @block_delimiters, 0, 2;
298
2
2
        push @begin_block_list, $begin;
299
2
3
        push @end_block_list, $end;
300      }
301
302
2
2
2
4
      $begin_block_re = join '|', (map { '('.quote_re("\Q$_\E").')' } @begin_block_list);
303    }
304  }
305
306
12
14
  my (@patterns_re_list, %in_patterns_re_list);
307
12
47
  if (-e "$configuration/patterns.txt") {
308
0
0
    @patterns_re_list = file_to_list "$configuration/patterns.txt";
309
0
0
    $patterns_re = list_to_re @patterns_re_list;
310
0
0
0
0
    %in_patterns_re_list = map {$_ => 1} @patterns_re_list;
311  } else {
312
12
12
    $patterns_re = undef;
313  }
314
315
12
42
  if (-e "$configuration/forbidden.txt") {
316
1
2
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
317
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
318
1
1
1
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
319
1
3
    $forbidden_re = list_to_re @forbidden_re_list;
320  } else {
321
11
8
    $forbidden_re = undef;
322  }
323
324
12
51
  if (-e "$configuration/candidates.txt") {
325
4
7
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
326
4
8
8
5
6
17
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
327
4
5
    $candidates_re = list_to_re @candidates_re_list;
328  } else {
329
8
8
    $candidates_re = undef;
330  }
331
332
12
20
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
333
334
12
13
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
335
12
12
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
336
12
10
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
337
12
11
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
338
339
12
7
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
340
12
12
  $ignore_next_line_pattern =~ s/\s+/|/g;
341
342
12
10
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
343
12
6
  $check_images = $check_images =~ /^(?:1|true)$/i;
344
12
11
  if ($check_images) {
345
0
0
    our $ocr_directory = CheckSpelling::Util::get_file_from_env('ocr_directory', '/tmp/ocr');
346
0
0
    $ocr_directory = $1 if ($ocr_directory =~ /^(.*)$/);
347  }
348
349
12
10
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
350
351
12
10
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
352
353
12
14
  $word_match = valid_word();
354
355
12
26
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
356
12
48
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
357
12
16
  load_dictionary($base_dict);
358}
359
360sub split_line {
361
1161
440
  our (%dictionary, $word_match, $disable_word_collating);
362
1161
451
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
363
1161
464
  our @hunspell_dictionaries;
364
1161
398
  our $shortest;
365
1161
762
  my $shortest_threshold = $shortest + 2;
366
1161
512
  my $pattern = '.';
367  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
368
369  # https://www.fileformat.info/info/unicode/char/2019/
370
1161
532
  my $rsqm = "\xE2\x80\x99";
371
372
1161
587
  my ($words, $unrecognized) = (0, 0);
373
1161
813
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
374
1161
4666
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
375
1161
2042
    $line =~ s/(?:$ignore_pattern)+/ /g;
376
1161
1498
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
377
1161
2883
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
378
1161
1216
    for my $token (split /\s+/, $line) {
379
3645
2954
      next unless $token =~ /$pattern/;
380
2485
1880
      $token =~ s/^(?:'|$rsqm)+//g;
381
2485
2280
      $token =~ s/(?:'|$rsqm)+s?$//g;
382
2485
1370
      my $raw_token = $token;
383
2485
1345
      $token =~ s/^[^Ii]?'+(.*)/$1/;
384
2485
1174
      $token =~ s/(.*?)'+$/$1/;
385
2485
3504
      next unless $token =~ $word_match;
386
2319
1862
      if (defined $dictionary{$token}) {
387
1039
447
        ++$words;
388
1039
564
        $unique_ref->{$token}=1;
389
1039
860
        next;
390      }
391
1280
886
      if (@hunspell_dictionaries) {
392
1254
542
        my $found = 0;
393
1254
652
        for my $hunspell_dictionary (@hunspell_dictionaries) {
394          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
395
1254
922
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
396
1254
2269
          next unless ($hunspell_dictionary->{'engine'}->check($token_encoded));
397
0
0
          ++$words;
398
0
0
          $dictionary{$token} = 1;
399
0
0
          $unique_ref->{$token}=1;
400
0
0
          $found = 1;
401
0
0
          last;
402        }
403
1254
880
        next if $found;
404      }
405
1280
790
      my $key = lc $token;
406
1280
1010
      if (defined $dictionary{$key}) {
407
6
5
        ++$words;
408
6
4
        $unique_ref->{$key}=1;
409
6
7
        next;
410      }
411
1274
799
      unless ($disable_word_collating) {
412
1274
681
        $key =~ s/''+/'/g;
413
1274
1197
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
414      }
415
1274
1001
      if (defined $dictionary{$key}) {
416
0
0
        ++$words;
417
0
0
        $unique_ref->{$key}=1;
418
0
0
        next;
419      }
420
1274
548
      ++$unrecognized;
421
1274
735
      $unique_unrecognized_ref->{$raw_token}=1;
422
1274
1528
      $unrecognized_line_items_ref->{$raw_token}=1;
423    }
424
1161
1372
    return ($words, $unrecognized);
425}
426
427sub skip_file {
428
7
25
  my ($temp_dir, $reason) = @_;
429
7
244
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
430
7
41
  print $skipped_fh $reason;
431
7
118
  close $skipped_fh;
432}
433
434sub maybe_ocr_file {
435
0
0
  my ($file) = @_;
436
0
0
  our $ocr_directory;
437
0
0
  my $ocr_file = "$ocr_directory/$file";
438
0
0
  $ocr_file =~ /^(.*)$/;
439
0
0
  $ocr_file = $1;
440
0
0
  my $ocr_source_sha = "$ocr_file.sha1";
441
0
0
  $ocr_file = "$ocr_file.txt";
442
0
0
  my $sha = Digest::SHA->new(1)->addfile($file, 'b')->hexdigest;
443
0
0
  if (-e $ocr_file &&
444      -e $ocr_source_sha &&
445      open my $source_sha, '<', $ocr_source_sha) {
446
0
0
    my $last_sha = <$source_sha>;
447
0
0
    close $source_sha;
448
0
0
    if ($last_sha =~ /(.*)/) {
449
0
0
      return ($ocr_file, 1) if ($1 eq $sha);
450    }
451  }
452
0
0
  my $tesseract = dirname(dirname(dirname(__FILE__)))."/wrappers/run-tesseract";
453
0
0
  $ENV{'input'} = $file;
454
0
0
  my $text_file = `"$tesseract"`;
455
0
0
  delete $ENV{'input'};
456
0
0
  return ($file, 0) unless defined $text_file;
457
0
0
  my $file_converted = 0;
458
0
0
  chomp $text_file;
459
0
0
  if ($text_file =~ /^(.*)$/) {
460
0
0
    $text_file = $1;
461
0
0
    my $file_size = -s $text_file || 0;
462
0
0
    if ($file_size > 20) {
463
0
0
      $file_converted = 1;
464
0
0
      make_path(dirname($ocr_source_sha));
465
0
0
      open my $source_sha, '>', $ocr_source_sha;
466
0
0
      print $source_sha $sha;
467
0
0
      close $source_sha;
468
0
0
      rename($text_file, $ocr_file);
469
0
0
      $file = $ocr_file;
470    } else {
471
0
0
      unlink($text_file);
472    }
473  }
474
0
0
  return ($file, $file_converted);
475}
476
477sub split_file {
478
18
11577
  my ($file) = @_;
479  our (
480
18
10
    $unrecognized, $shortest, $largest_file, $words,
481    $word_match, %unique, %unique_unrecognized, $forbidden_re,
482    @forbidden_re_list, $patterns_re, %dictionary,
483    $begin_block_re, @begin_block_list, @end_block_list,
484    $candidates_re, @candidates_re_list, $check_file_names, $use_magic_file, $disable_minified_file,
485    $disable_single_line_file,
486    $ignore_next_line_pattern,
487    $sandbox,
488    $check_images,
489  );
490
18
36
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
491
492
18
7
  our %forbidden_re_descriptions;
493
18
13
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
494
495  # https://www.fileformat.info/info/unicode/char/2019/
496
18
16
  my $rsqm = "\xE2\x80\x99";
497
498
18
21
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
499
18
13
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
500
18
19
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
501
18
12
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
502
18
43
  my $temp_dir = tempdir(DIR=>$sandbox);
503
18
3060
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
504
18
426
  open(my $name_fh, '>', "$temp_dir/name");
505
18
31
    print $name_fh $file;
506
18
245
  close $name_fh;
507
18
225
  if (defined readlink($file) &&
508      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
509
1
4
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
510
1
4
    return $temp_dir;
511  }
512
17
35
  if ($use_magic_file) {
513
8
12593
    if (open(my $file_fh, '-|',
514              '/usr/bin/file',
515              '-b',
516              '--mime',
517              '-e', 'cdf',
518              '-e', 'compress',
519              '-e', 'csv',
520              '-e', 'elf',
521              '-e', 'json',
522              '-e', 'tar',
523              $file)) {
524
8
30933
      my $file_kind = <$file_fh>;
525
8
4845
      close $file_fh;
526
8
13
      my $file_converted = 0;
527
8
20
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
528
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
529      }
530
8
197
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
531
2
35
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
532
2
55
        return $temp_dir;
533      }
534    }
535  } elsif ($file =~ /\.(?:png|jpe?g|gif)$/) {
536
0
0
    my $file_converted = 0;
537
0
0
    ($file, $file_converted) = maybe_ocr_file($file);
538  }
539
15
91
  my $file_size = -s $file;
540
15
20
  if (defined $largest_file) {
541
15
14
    unless ($check_file_names eq $file) {
542
15
19
      if ($file_size > $largest_file) {
543
1
2
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
544
1
3
        return $temp_dir;
545      }
546    }
547  }
548
14
148
  open my $file_fh, '<', $file;
549
14
11
  binmode $file_fh;
550
14
11
  my $head;
551
14
131
  read($file_fh, $head, 4096);
552
14
861
  $head =~ s/(?:\r|\n)+$//;
553
14
71
  my $dos_new_lines = () = $head =~ /\r\n/gi;
554
14
48
  my $unix_new_lines = () = $head =~ /\n/gi;
555
14
115
  my $mac_new_lines = () = $head =~ /\r/gi;
556
14
64
  local $/;
557
14
89
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
558
3
5
    $/ = "\n";
559  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
560
1
8
    $/ = "\r\n";
561  } elsif ($mac_new_lines > $unix_new_lines) {
562
2
8
    $/ = "\r";
563  } else {
564
8
10
    $/ = "\n";
565  }
566
14
32
  seek($file_fh, 0, 0);
567
14
24
  ($words, $unrecognized) = (0, 0);
568
14
37
  %unique = ();
569
14
30
  %unique_unrecognized = ();
570
571  local $SIG{__WARN__} = sub {
572
0
0
    my $message = shift;
573
0
0
    $message =~ s/> line/> in $file - line/;
574
0
0
    chomp $message;
575
0
0
    print STDERR "$message\n";
576
14
130
  };
577
578
14
357
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
579
14
9
  our $timeout;
580
14
14
  eval {
581
14
0
106
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
582
14
45
    alarm $timeout;
583
584
14
16
    my $ignore_next_line = 0;
585
14
33
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
586
14
17
    my $offset = 0;
587
14
94
    LINE: while (<$file_fh>) {
588
1170
948
      if ($. == 1) {
589
14
27
        unless ($disable_minified_file) {
590
14
67
          if ($file_size >= 512 && length($_) == $file_size) {
591
1
11
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
592
1
1
            last;
593          }
594        }
595      }
596
1169
1800
      $_ = decode_utf8($_, FB_DEFAULT);
597
1169
2302
      if (/[\x{D800}-\x{DFFF}]/) {
598
0
0
        skip_file($temp_dir, "file contains a UTF-16 surrogate -- UTF-16 surrogates are not supported (utf16-surrogate-file)\n");
599
0
0
        last;
600      }
601
1169
1231
      s/\R$//;
602
1169
930
      s/^\x{FEFF}// if $. == 1;
603
1169
953
      next unless /./;
604
1168
708
      my $raw_line = $_;
605
1168
507
      my $parsed_block_markers;
606
607      # hook for custom multiline based text exclusions:
608
1168
748
      if ($begin_block_re) {
609
1148
516
        FIND_END_MARKER: while (1) {
610
1150
787
          while ($next_end_marker ne '') {
611
6
24
            next LINE unless /\Q$next_end_marker\E/;
612
1
6
            s/.*?\Q$next_end_marker\E//;
613
1
2
            ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
614
1
2
            $parsed_block_markers = 1;
615          }
616
1145
958
          my @captured = (/^.*?$begin_block_re/);
617
1145
828
          last unless (@captured);
618
2
3
          for my $capture (0 .. $#captured) {
619
2
2
            if ($captured[$capture]) {
620
2
7
              ($current_begin_marker, $next_end_marker, $start_marker_line) = ($begin_block_list[$capture], $end_block_list[$capture], "$.:1 ... 1");
621
2
13
              s/^.*?\Q$begin_block_list[$capture]\E//;
622
2
1
              $parsed_block_markers = 1;
623
2
4
              next FIND_END_MARKER;
624            }
625          }
626        }
627
1143
731
        next if $parsed_block_markers;
628      }
629
630
1162
546
      my $ignore_this_line = $ignore_next_line;
631
1162
887
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
632
1162
676
      next if $ignore_this_line;
633
634      # hook for custom line based text exclusions:
635
1161
671
      if (defined $patterns_re) {
636
2
6
12
8
        s/($patterns_re)/"="x length($1)/ge;
637      }
638
1161
620
      my $initial_line_state = $_;
639
1161
678
      my $previous_line_state = $_;
640
1161
521
      my $line_flagged;
641
1161
735
      if ($forbidden_re) {
642
9
5
66
10
        while (s/($forbidden_re)/"="x length($1)/e) {
643
5
5
          $line_flagged = 1;
644
5
8
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
645
5
4
          my $found_trigger_re;
646
5
6
          for my $i (0 .. $#forbidden_re_list) {
647
7
7
            my $forbidden_re_singleton = $forbidden_re_list[$i];
648
7
2
            my $test_line = $previous_line_state;
649
7
4
59
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
650
4
4
              next unless $test_line eq $_;
651
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
652
4
3
              next unless $begin == $begin_test;
653
4
4
              next unless $end == $end_test;
654
4
3
              next unless $match eq $match_test;
655
4
3
              $found_trigger_re = $forbidden_re_singleton;
656
4
9
              my $hit = "$.:$begin:$end";
657
4
3
              $forbidden_re_hits[$i]++;
658
4
5
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
659
4
6
              last;
660            }
661          }
662
5
7
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
663
5
6
          if ($found_trigger_re) {
664
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
665
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
666
4
4
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
667
4
5
            if ($description ne '') {
668
3
13
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
669            } else {
670
1
6
              print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
671            }
672          } else {
673
1
5
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
674          }
675
5
25
          $previous_line_state = $_;
676        }
677
9
9
        $_ = $initial_line_state;
678      }
679      # This is to make it easier to deal w/ rules:
680
1161
1017
      s/^/ /;
681
1161
619
      my %unrecognized_line_items = ();
682
1161
499
      our $check_homoglyphs;
683
1161
656
      if ($check_homoglyphs) {
684
1161
617
        my $check_line_for_homoglyphs = $_;
685
1161
616
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
686        # problematic characters: `\\`, `-`, `]`
687
1161
11514
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
688
1161
1353
        $homoglyphs = "[$homoglyphs]";
689
1161
489
        our ($longest_word, $shortest_word);
690
1161
1557
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
691
1161
502
        my $dollar = '$';
692
1161
1404
        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})*)";
693
1161
10127
        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) {
694
1
2
          my ($token, $token_raw, $begin, $end) = ($1, $1, $-[0], $+[0]);
695
1
50
          $token =~ s/($homoglyphs)/$CheckSpelling::Homoglyph::homoglyph_to_glyph{$1}/g;
696
1
2
          if (defined $dictionary{$token}) {
697
1
1
            my $token_raw = CheckSpelling::Util::wrap_in_backticks($token_raw);
698
1
1
            my $token = CheckSpelling::Util::wrap_in_backticks($token);
699
1
1
            my $wrapped = "$token_raw should probably be $token (homoglyph-word)";
700
1
9
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
701          }
702        }
703      }
704
1161
892
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
705
1161
564
      $words += $new_words;
706
1161
490
      $unrecognized += $new_unrecognized;
707
1161
710
      my $line_length = length($raw_line);
708
1161
1193
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
709
1021
484
        my $found_token = 0;
710
1021
458
        my $raw_token = $token;
711
1021
507
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
712
1021
416
        my $before;
713
1021
1396
        if ($token =~ /^$upper_pattern$lower_pattern/) {
714
5
5
          $before = '(?<=.)';
715        } elsif ($token =~ /^$upper_pattern/) {
716
0
0
          $before = "(?<!$upper_pattern)";
717        } else {
718
1016
508
          $before = "(?<=$not_lower_pattern)";
719        }
720
1021
1047
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
721
1021
1784
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
722
1271
585
          $line_flagged = 1;
723
1271
492
          $found_token = 1;
724
1271
1514
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
725
1271
1027
          next unless $match =~ /./;
726
1271
836
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
727
1271
4152
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
728        }
729
1021
1007
        unless ($found_token) {
730
3
29
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
731
3
5
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
732
3
4
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
733
3
10
            print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
734          } else {
735
0
0
            my $offset = $line_length + 1;
736
0
0
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
737
0
0
            print $warnings_fh ":$.:1 ... $offset, Warning - Could not identify whole word $wrapped in line (token-is-substring)\n";
738          }
739        }
740      }
741
1161
1461
      if ($line_flagged && $candidates_re) {
742
2
3
        $_ = $previous_line_state = $initial_line_state;
743
2
2
22
6
        s/($candidates_re)/"="x length($1)/ge;
744
2
3
        if ($_ ne $initial_line_state) {
745
2
1
          $_ = $previous_line_state;
746
2
3
          for my $i (0 .. $#candidates_re_list) {
747
4
4
            my $candidate_re = $candidates_re_list[$i];
748
4
25
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
749
2
2
9
5
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
750
2
3
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
751
2
5
              my $hit = "$.:$begin:$end";
752
2
2
              $_ = $previous_line_state;
753
2
2
8
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
754
2
3
              $candidates_re_hits[$i] += $replacements;
755
2
3
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
756
2
4
              $_ = $previous_line_state;
757            }
758          }
759        }
760      }
761
1161
725
      unless ($disable_minified_file) {
762
1161
860
        s/={3,}//g;
763
1161
678
        $offset += length;
764
1161
918
        my $ratio = int($offset / $.);
765
1161
536
        my $ratio_threshold = 1000;
766
1161
2797
        if ($ratio > $ratio_threshold) {
767
2
7
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
768
2
9
          last;
769        }
770      }
771    }
772
14
21
    if ($next_end_marker) {
773
1
2
      if ($start_marker_line) {
774
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($current_begin_marker);
775
1
5
        print $warnings_fh ":$start_marker_line, Warning - Failed to find matching end marker for $wrapped (unclosed-block-ignore-begin)\n";
776      }
777
1
1
      my $wrapped = CheckSpelling::Util::wrap_in_backticks($next_end_marker);
778
1
3
      print $warnings_fh ":$.:1 ... 1, Warning - Expected to find end block marker $wrapped (unclosed-block-ignore-end)\n";
779    }
780
781
14
100
    alarm 0;
782  };
783
14
13
  if ($@) {
784
0
0
    die unless $@ eq "alarm\n";
785
0
0
    print $warnings_fh ":$.:1 ... 1, Warning - Could not parse file within time limit (slow-file)\n";
786
0
0
    skip_file($temp_dir, "it could not be parsed file within time limit (slow-file)\n");
787
0
0
    return $temp_dir;
788  }
789
790
14
55
  close $file_fh;
791
14
186
  close $warnings_fh;
792
793
14
36
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
794
13
424
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
795
13
195
      print $stats_fh "{words: $words, unrecognized: $unrecognized, unknown: ".(keys %unique_unrecognized).
796      ", unique: ".(keys %unique).
797      (@candidates_re_hits ? ", candidates: [".(join ',', @candidates_re_hits)."]" : "").
798      (@candidates_re_lines ? ", candidate_lines: [".(join ',', @candidates_re_lines)."]" : "").
799      (@forbidden_re_hits ? ", forbidden: [".(join ',', @forbidden_re_hits)."]" : "").
800      (@forbidden_re_lines ? ", forbidden_lines: [".(join ',', @forbidden_re_lines)."]" : "").
801      "}";
802
13
164
    close $stats_fh;
803
13
290
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
804
13
20
48
47
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
805
13
117
    close $unknown_fh;
806  }
807
808
14
152
  return $temp_dir;
809}
810
811sub main {
812
4
413
  my ($configuration, @ARGV) = @_;
813
4
3
  our %dictionary;
814
4
5
  unless (%dictionary) {
815
1
2
    init($configuration);
816  }
817
818  # read all input
819
4
2
  my @reports;
820
821
4
4
  for my $file (@ARGV) {
822
4
4
    my $temp_dir = split_file($file);
823
4
8
    push @reports, "$temp_dir\n";
824  }
825
4
11
  print join '', @reports;
826}
827
8281;