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
109961
1
use 5.022;
11
1
1
1
2
0
54
use feature 'unicode_strings';
12
1
1
1
2
2
7
use strict;
13
1
1
1
1
0
19
use warnings;
14
1
1
1
2
0
15
no warnings qw(experimental::vlb);
15
1
1
1
1
1
2
use utf8;
16
1
1
1
11
0
26
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
28
use File::Basename;
18
1
1
1
2
0
15
use Cwd 'abs_path';
19
1
1
1
2
0
18
use File::Spec;
20
1
1
1
1
0
18
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
1
1
16
use File::Path qw/ make_path /;
22
1
1
1
341
1
20
use CheckSpelling::Util;
23
1
1
1
188
1266
980
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
24
  my ($expression) = @_;
50
32
32
14
223
  return eval { qr /$expression/ };
51}
52
53sub quote_re {
54
34
30
  my ($expression) = @_;
55
34
28
  return $expression if $expression =~ /\?\{/;
56
34
62
  $expression =~ s/
57   \G
58   (
59      (?:[^\\]|\\[^Q])*
60   )
61   (?:
62      \\Q
63      (?:[^\\]|\\[^E])*
64      (?:\\E)?
65   )?
66/
67
68
108
   $1 . (defined($2) ? quotemeta($2) : '')
68/xge;
69
34
41
  return $expression;
70}
71
72sub file_to_lists {
73
6
5
  my ($re) = @_;
74
6
5
  my @patterns;
75  my %hints;
76
6
0
  my $fh;
77
6
52
  if (open($fh, '<:utf8', $re)) {
78
6
9
    local $/=undef;
79
6
39
    my $file=<$fh>;
80
6
15
    close $fh;
81
6
5
    my $line_number = 0;
82
6
1
    my $hint = '';
83
6
25
    for (split /\R/, $file) {
84
32
13
      ++$line_number;
85
32
17
      chomp;
86
32
35
      if (/^#(?:\s(.+)|)/) {
87
12
29
        $hint = $1 if ($hint eq '' && defined $1);
88
12
10
        next;
89      }
90
20
24
      $hint = '' unless $_ ne '';
91
20
18
      next if $_ eq '$^';
92
20
13
      my $pattern = $_;
93
20
48
      next unless s/^(.+)/(?:$1)/;
94
13
13
      my $quoted = quote_re($1);
95
13
14
      unless (test_re $quoted) {
96
1
2
        my $error = $@;
97
1
43
        my $home = dirname(__FILE__);
98
1
23
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
99
1
11
        print STDERR $error;
100
1
3
        $_ = '(?:\$^ - skipped because bad-regex)';
101
1
2
        $hint = '';
102      }
103
13
18
      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
14
        push @patterns, $_;
110
12
16
        $hints{$_} = $hint;
111      }
112
13
20
      $hint = '';
113    }
114  }
115
116  return {
117
6
23
    patterns => \@patterns,
118    hints => \%hints,
119  };
120}
121
122sub file_to_list {
123
5
1237
  my ($re) = @_;
124
5
9
  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
3
7
10
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
132
5
11
5
11
  @list = grep { $_ ne '' } @list;
133
5
5
  return '$^' unless scalar @list;
134
5
12
  return join "|", (@list);
135}
136
137sub not_empty {
138
107
89
  my ($thing) = @_;
139
107
500
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
140}
141
142sub parse_block_list {
143
3
1
  my ($re) = @_;
144
3
2
  my @file;
145
3
28
  return @file unless (open(my $file_fh, '<:utf8', $re));
146
147
3
5
  local $/=undef;
148
3
21
  my $file=<$file_fh>;
149
3
4
  my $last_line = $.;
150
3
8
  close $file_fh;
151
3
9
  for (split /\R/, $file) {
152
8
11
    next if /^#/;
153
5
2
    chomp;
154
5
5
    s/^\\#/#/;
155
5
6
    next unless /^./;
156
5
6
    push @file, $_;
157  }
158
159
3
3
  my $pairs = (0+@file) / 2;
160
3
3
  my $true_pairs = $pairs | 0;
161
3
5
  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
27
    print $early_warnings_fh "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
165
1
19
    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
10
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
173
1
2
    @file = ();
174  }
175
176
3
8
  return @file;
177}
178
179sub valid_word {
180  # shortest_word is an absolute
181
28
17
  our ($shortest, $longest, $shortest_word, $longest_word);
182
28
24
  $shortest = $shortest_word if $shortest_word;
183
28
24
  if ($longest_word) {
184    # longest_word is an absolute
185
26
20
    $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
17
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
192
28
84
24
185
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
193
28
23
  $word_pattern = q<\\w|'> unless $word_pattern;
194
28
47
  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
31
  $shortest = 3 unless defined $shortest;
200
28
20
  $longest = '' unless not_empty($longest);
201
28
132
  $word_match = "(?:$word_pattern){$shortest,$longest}";
202
28
228
  return qr/\b$word_match\b/;
203}
204
205sub load_dictionary {
206
15
1985
  my ($dict) = @_;
207
15
5
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
208
15
15
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
209
15
15
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', 0);
210
15
10
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
211
15
16
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
212
15
53
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
213
15
38
  $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
27
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
216
15
30
  $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
40
  if ($check_homoglyphs && $check_homoglyphs ne 'false') {
219
14
10
    my $homoglyph_list_path = CheckSpelling::Util::get_file_from_env_utf8('homoglyph_list_path', '/dev/null');
220
14
89
    if (-s $homoglyph_list_path) {
221
1
1
1
345
1
3483
      use CheckSpelling::Homoglyph;
222
14
22
      CheckSpelling::Homoglyph::init($homoglyph_list_path);
223    }
224  } else {
225
1
0
    $check_homoglyphs = 0;
226  }
227
15
27
  %dictionary = ();
228
229
15
1013
  open(my $dict_fh, '<:utf8', $dict);
230
15
70
  while (!eof($dict_fh)) {
231
53
52
    my $word = <$dict_fh>;
232
53
44
    chomp $word;
233
53
124
    next unless $word =~ $word_match;
234
50
50
    my $l = length $word;
235
50
30
    $longest = -1 unless not_empty($longest);
236
50
59
    $longest = $l if $l > $longest;
237
50
40
    $shortest = $l if $l < $shortest;
238
50
100
    $dictionary{$word}=1;
239  }
240
15
29
  close $dict_fh;
241
242
15
16
  $word_match = valid_word();
243}
244
245sub hunspell_dictionary {
246
3
4
  my ($dict) = @_;
247
3
3
  my $name = $dict;
248
3
5
  $name =~ s{/src/index/hunspell/index\.dic$}{};
249
3
10
  $name =~ s{.*/}{};
250
3
3
  my $aff = $dict;
251
3
4
  my $encoding;
252
3
11
  $aff =~ s/\.dic$/.aff/;
253
3
33
  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
326
    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
15122
  my ($configuration) = @_;
272
12
7
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
273
12
6
  our ($begin_block_re, @begin_block_list, @end_block_list);
274
12
27
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
275
12
10
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
276
12
13
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
277
12
10
  our %forbidden_re_descriptions;
278
12
14
  if ($hunspell_dictionary_path) {
279
3
36
    our @hunspell_dictionaries = ();
280
1
1
1
1
1
1
1
1
1
3
304
1041
19
5
1
14
7
2
17
159
    if (eval 'use Text::Hunspell; 1') {
281
3
120
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
282
3
8
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
283
3
11
        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
73
  if (-e "$configuration/block-delimiters.list") {
291
3
4
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
292
3
4
    if (@block_delimiters) {
293
2
2
      @begin_block_list = ();
294
2
2
      @end_block_list = ();
295
296
2
2
      while (@block_delimiters) {
297
2
3
        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
1
3
      $begin_block_re = join '|', (map { '('.quote_re("\Q$_\E").')' } @begin_block_list);
303    }
304  }
305
306
12
13
  my (@patterns_re_list, %in_patterns_re_list);
307
12
46
  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
9
    $patterns_re = undef;
313  }
314
315
12
44
  if (-e "$configuration/forbidden.txt") {
316
1
2
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
317
1
1
1
1
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
318
1
1
1
3
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
319
1
2
    $forbidden_re = list_to_re @forbidden_re_list;
320  } else {
321
11
11
    $forbidden_re = undef;
322  }
323
324
12
46
  if (-e "$configuration/candidates.txt") {
325
4
6
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
326
4
8
8
4
6
16
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
327
4
4
    $candidates_re = list_to_re @candidates_re_list;
328  } else {
329
8
6
    $candidates_re = undef;
330  }
331
332
12
19
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
333
334
12
10
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
335
12
13
  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
9
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
338
339
12
8
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
340
12
8
  $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
9
  $check_images = $check_images =~ /^(?:1|true)$/i;
344
12
12
  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
8
  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
15
  $word_match = valid_word();
354
355
12
24
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
356
12
56
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
357
12
15
  load_dictionary($base_dict);
358}
359
360sub split_line {
361
1161
490
  our (%dictionary, $word_match, $disable_word_collating);
362
1161
448
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
363
1161
455
  our @hunspell_dictionaries;
364
1161
483
  our $shortest;
365
1161
834
  my $shortest_threshold = $shortest + 2;
366
1161
630
  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
531
  my $rsqm = "\xE2\x80\x99";
371
372
1161
749
  my ($words, $unrecognized) = (0, 0);
373
1161
882
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
374
1161
5625
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
375
1161
2298
    $line =~ s/(?:$ignore_pattern)+/ /g;
376
1161
1786
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
377
1161
3380
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
378
1161
1421
    for my $token (split /\s+/, $line) {
379
3645
3302
      next unless $token =~ /$pattern/;
380
2485
2199
      $token =~ s/^(?:'|$rsqm)+//g;
381
2485
2664
      $token =~ s/(?:'|$rsqm)+s?$//g;
382
2485
1533
      my $raw_token = $token;
383
2485
1566
      $token =~ s/^[^Ii]?'+(.*)/$1/;
384
2485
1292
      $token =~ s/(.*?)'+$/$1/;
385
2485
3986
      next unless $token =~ $word_match;
386
2319
2140
      if (defined $dictionary{$token}) {
387
1039
497
        ++$words;
388
1039
552
        $unique_ref->{$token}=1;
389
1039
836
        next;
390      }
391
1280
1026
      if (@hunspell_dictionaries) {
392
1254
641
        my $found = 0;
393
1254
783
        for my $hunspell_dictionary (@hunspell_dictionaries) {
394          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
395
1254
1066
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
396
1254
3109
          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
1085
        next if $found;
404      }
405
1280
982
      my $key = lc $token;
406
1280
1145
      if (defined $dictionary{$key}) {
407
6
4
        ++$words;
408
6
5
        $unique_ref->{$key}=1;
409
6
7
        next;
410      }
411
1274
927
      unless ($disable_word_collating) {
412
1274
806
        $key =~ s/''+/'/g;
413
1274
1389
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
414      }
415
1274
1139
      if (defined $dictionary{$key}) {
416
0
0
        ++$words;
417
0
0
        $unique_ref->{$key}=1;
418
0
0
        next;
419      }
420
1274
695
      ++$unrecognized;
421
1274
873
      $unique_unrecognized_ref->{$raw_token}=1;
422
1274
1819
      $unrecognized_line_items_ref->{$raw_token}=1;
423    }
424
1161
1770
    return ($words, $unrecognized);
425}
426
427sub skip_file {
428
7
22
  my ($temp_dir, $reason) = @_;
429
7
221
  open(my $skipped_fh, '>:utf8', "$temp_dir/skipped");
430
7
38
  print $skipped_fh $reason;
431
7
109
  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
11751
  my ($file) = @_;
479  our (
480
18
12
    $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
35
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
491
492
18
10
  our %forbidden_re_descriptions;
493
18
7
  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
12
  my $rsqm = "\xE2\x80\x99";
497
498
18
34
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
499
18
15
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
500
18
17
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
501
18
15
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
502
18
36
  my $temp_dir = tempdir(DIR=>$sandbox);
503
18
2878
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
504
18
469
  open(my $name_fh, '>', "$temp_dir/name");
505
18
45
    print $name_fh $file;
506
18
247
  close $name_fh;
507
18
210
  if (defined readlink($file) &&
508      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
509
1
3
    skip_file($temp_dir, "symbolic link points outside repository (out-of-bounds-symbolic-link)\n");
510
1
5
    return $temp_dir;
511  }
512
17
23
  if ($use_magic_file) {
513
8
12317
    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
28448
      my $file_kind = <$file_fh>;
525
8
4612
      close $file_fh;
526
8
12
      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
154
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
531
2
28
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
532
2
38
        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
81
  my $file_size = -s $file;
540
15
19
  if (defined $largest_file) {
541
15
13
    unless ($check_file_names eq $file) {
542
15
20
      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
15
  binmode $file_fh;
550
14
8
  my $head;
551
14
111
  read($file_fh, $head, 4096);
552
14
809
  $head =~ s/(?:\r|\n)+$//;
553
14
54
  my $dos_new_lines = () = $head =~ /\r\n/gi;
554
14
37
  my $unix_new_lines = () = $head =~ /\n/gi;
555
14
104
  my $mac_new_lines = () = $head =~ /\r/gi;
556
14
55
  local $/;
557
14
70
  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
7
    $/ = "\r\n";
561  } elsif ($mac_new_lines > $unix_new_lines) {
562
2
6
    $/ = "\r";
563  } else {
564
8
7
    $/ = "\n";
565  }
566
14
26
  seek($file_fh, 0, 0);
567
14
13
  ($words, $unrecognized) = (0, 0);
568
14
30
  %unique = ();
569
14
26
  %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
107
  };
577
578
14
354
  open(my $warnings_fh, '>:utf8', "$temp_dir/warnings");
579
14
13
  our $timeout;
580
14
14
  eval {
581
14
0
92
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
582
14
33
    alarm $timeout;
583
584
14
16
    my $ignore_next_line = 0;
585
14
27
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
586
14
17
    my $offset = 0;
587
14
92
    LINE: while (<$file_fh>) {
588
1170
1044
      if ($. == 1) {
589
14
20
        unless ($disable_minified_file) {
590
14
51
          if ($file_size >= 512 && length($_) == $file_size) {
591
1
9
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
592
1
3
            last;
593          }
594        }
595      }
596
1169
2726
      $_ = decode_utf8($_, FB_DEFAULT);
597
1169
2922
      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
1464
      s/\R$//;
602
1169
1142
      s/^\x{FEFF}// if $. == 1;
603
1169
1113
      next unless /./;
604
1168
865
      my $raw_line = $_;
605
1168
550
      my $parsed_block_markers;
606
607      # hook for custom multiline based text exclusions:
608
1168
769
      if ($begin_block_re) {
609
1148
578
        FIND_END_MARKER: while (1) {
610
1150
989
          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
1
            ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
614
1
1
            $parsed_block_markers = 1;
615          }
616
1145
1243
          my @captured = (/^.*?$begin_block_re/);
617
1145
1142
          last unless (@captured);
618
2
2
          for my $capture (0 .. $#captured) {
619
2
2
            if ($captured[$capture]) {
620
2
5
              ($current_begin_marker, $next_end_marker, $start_marker_line) = ($begin_block_list[$capture], $end_block_list[$capture], "$.:1 ... 1");
621
2
12
              s/^.*?\Q$begin_block_list[$capture]\E//;
622
2
2
              $parsed_block_markers = 1;
623
2
4
              next FIND_END_MARKER;
624            }
625          }
626        }
627
1143
883
        next if $parsed_block_markers;
628      }
629
630
1162
704
      my $ignore_this_line = $ignore_next_line;
631
1162
1034
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
632
1162
804
      next if $ignore_this_line;
633
634      # hook for custom line based text exclusions:
635
1161
1016
      if (defined $patterns_re) {
636
2
6
10
8
        s/($patterns_re)/"="x length($1)/ge;
637      }
638
1161
633
      my $initial_line_state = $_;
639
1161
728
      my $previous_line_state = $_;
640
1161
553
      my $line_flagged;
641
1161
873
      if ($forbidden_re) {
642
9
5
62
10
        while (s/($forbidden_re)/"="x length($1)/e) {
643
5
3
          $line_flagged = 1;
644
5
11
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
645
5
3
          my $found_trigger_re;
646
5
5
          for my $i (0 .. $#forbidden_re_list) {
647
7
9
            my $forbidden_re_singleton = $forbidden_re_list[$i];
648
7
4
            my $test_line = $previous_line_state;
649
7
4
75
8
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
650
4
5
              next unless $test_line eq $_;
651
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
652
4
4
              next unless $begin == $begin_test;
653
4
4
              next unless $end == $end_test;
654
4
4
              next unless $match eq $match_test;
655
4
3
              $found_trigger_re = $forbidden_re_singleton;
656
4
10
              my $hit = "$.:$begin:$end";
657
4
2
              $forbidden_re_hits[$i]++;
658
4
6
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
659
4
7
              last;
660            }
661          }
662
5
7
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
663
5
8
          if ($found_trigger_re) {
664
4
9
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
665
4
12
            $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
3
            if ($description ne '') {
668
3
35
              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
3
            print $warnings_fh ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
674          }
675
5
27
          $previous_line_state = $_;
676        }
677
9
8
        $_ = $initial_line_state;
678      }
679      # This is to make it easier to deal w/ rules:
680
1161
1180
      s/^/ /;
681
1161
712
      my %unrecognized_line_items = ();
682
1161
472
      our $check_homoglyphs;
683
1161
802
      if ($check_homoglyphs) {
684
1161
697
        my $check_line_for_homoglyphs = $_;
685
1161
799
        my $homoglyphs = $CheckSpelling::Homoglyph::homoglyphs;
686        # problematic characters: `\\`, `-`, `]`
687
1161
11088
        $homoglyphs =~ s/([-\\\]])/\\$1/g;
688
1161
1609
        $homoglyphs = "[$homoglyphs]";
689
1161
526
        our ($longest_word, $shortest_word);
690
1161
2033
        my $longest_word_string = defined $longest_word && ($longest_word =~ /^\d+$/) ? $longest_word : '';
691
1161
554
        my $dollar = '$';
692
1161
1776
        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
11022
        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
10
            print $warnings_fh ":$.:$begin ... $end, Error - $wrapped\n";
701          }
702        }
703      }
704
1161
1097
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
705
1161
653
      $words += $new_words;
706
1161
533
      $unrecognized += $new_unrecognized;
707
1161
845
      my $line_length = length($raw_line);
708
1161
1719
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
709
1021
584
        my $found_token = 0;
710
1021
499
        my $raw_token = $token;
711
1021
637
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
712
1021
475
        my $before;
713
1021
1724
        if ($token =~ /^$upper_pattern$lower_pattern/) {
714
5
3
          $before = '(?<=.)';
715        } elsif ($token =~ /^$upper_pattern/) {
716
0
0
          $before = "(?<!$upper_pattern)";
717        } else {
718
1016
609
          $before = "(?<=$not_lower_pattern)";
719        }
720
1021
1258
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
721
1021
2193
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
722
1271
612
          $line_flagged = 1;
723
1271
553
          $found_token = 1;
724
1271
1763
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
725
1271
1221
          next unless $match =~ /./;
726
1271
1018
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
727
1271
4994
          print $warnings_fh ":$.:$begin ... $end: $wrapped\n";
728        }
729
1021
1208
        unless ($found_token) {
730
3
27
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
731
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
732
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
733
3
13
            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
1871
      if ($line_flagged && $candidates_re) {
742
2
3
        $_ = $previous_line_state = $initial_line_state;
743
2
2
20
4
        s/($candidates_re)/"="x length($1)/ge;
744
2
4
        if ($_ ne $initial_line_state) {
745
2
1
          $_ = $previous_line_state;
746
2
2
          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
3
            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
22
              $_ = $previous_line_state;
753
2
2
9
3
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
754
2
2
              $candidates_re_hits[$i] += $replacements;
755
2
7
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
756
2
4
              $_ = $previous_line_state;
757            }
758          }
759        }
760      }
761
1161
969
      unless ($disable_minified_file) {
762
1161
958
        s/={3,}//g;
763
1161
810
        $offset += length;
764
1161
1122
        my $ratio = int($offset / $.);
765
1161
630
        my $ratio_threshold = 1000;
766
1161
3356
        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
7
          last;
769        }
770      }
771    }
772
14
20
    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
3
        print $warnings_fh ":$start_marker_line, Warning - Failed to find matching end marker for $wrapped (unclosed-block-ignore-begin)\n";
776      }
777
1
2
      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
89
    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
43
  close $file_fh;
791
14
175
  close $warnings_fh;
792
793
14
34
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
794
13
384
    open(my $stats_fh, '>:utf8', "$temp_dir/stats");
795
13
210
      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
168
    close $stats_fh;
803
13
280
    open(my $unknown_fh, '>:utf8', "$temp_dir/unknown");
804
13
20
47
37
      print $unknown_fh map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
805
13
138
    close $unknown_fh;
806  }
807
808
14
143
  return $temp_dir;
809}
810
811sub main {
812
4
368
  my ($configuration, @ARGV) = @_;
813
4
1
  our %dictionary;
814
4
4
  unless (%dictionary) {
815
1
1
    init($configuration);
816  }
817
818  # read all input
819
4
4
  my @reports;
820
821
4
3
  for my $file (@ARGV) {
822
4
2
    my $temp_dir = split_file($file);
823
4
6
    push @reports, "$temp_dir\n";
824  }
825
4
12
  print join '', @reports;
826}
827
8281;