File Coverage

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