File Coverage

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