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
111980
2
use 5.022;
11
1
1
1
2
1
52
use feature 'unicode_strings';
12
1
1
1
2
0
9
use strict;
13
1
1
1
2
1
20
use warnings;
14
1
1
1
1
1
13
no warnings qw(experimental::vlb);
15
1
1
1
1
1
2
use utf8;
16
1
1
1
13
1
27
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
1
25
use File::Basename;
18
1
1
1
1
1
13
use Cwd 'abs_path';
19
1
1
1
1
0
21
use File::Spec;
20
1
1
1
1
1
17
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
2
0
13
use File::Path qw/ make_path /;
22
1
1
1
315
1
19
use CheckSpelling::Util;
23
1
1
1
209
1244
4049
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
19
  my ($expression) = @_;
49
32
32
20
204
  return eval { qr /$expression/ };
50}
51
52sub quote_re {
53
34
24
  my ($expression) = @_;
54
34
32
  return $expression if $expression =~ /\?\{/;
55
34
64
  $expression =~ s/
56   \G
57   (
58      (?:[^\\]|\\[^Q])*
59   )
60   (?:
61      \\Q
62      (?:[^\\]|\\[^E])*
63      (?:\\E)?
64   )?
65/
66
68
109
   $1 . (defined($2) ? quotemeta($2) : '')
67/xge;
68
34
40
  return $expression;
69}
70
71sub file_to_lists {
72
6
6
  my ($re) = @_;
73
6
7
  my @patterns;
74  my %hints;
75
6
0
  my $fh;
76
6
59
  if (open($fh, '<:utf8', $re)) {
77
6
8
    local $/=undef;
78
6
43
    my $file=<$fh>;
79
6
16
    close $fh;
80
6
5
    my $line_number = 0;
81
6
5
    my $hint = '';
82
6
23
    for (split /\R/, $file) {
83
32
17
      ++$line_number;
84
32
17
      chomp;
85
32
33
      if (/^#(?:\s(.+)|)/) {
86
12
26
        $hint = $1 if ($hint eq '' && defined $1);
87
12
12
        next;
88      }
89
20
31
      $hint = '' unless $_ ne '';
90
20
20
      next if $_ eq '$^';
91
20
16
      my $pattern = $_;
92
20
49
      next unless s/^(.+)/(?:$1)/;
93
13
13
      my $quoted = quote_re($1);
94
13
16
      unless (test_re $quoted) {
95
1
2
        my $error = $@;
96
1
51
        my $home = dirname(__FILE__);
97
1
21
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
98
1
40
        print STDERR $error;
99
1
4
        $_ = '(?:\$^ - skipped because bad-regex)';
100
1
2
        $hint = '';
101      }
102
13
35
      if (defined $hints{$_}) {
103
1
1
        my $pattern_length = length $pattern;
104
1
2
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
105
1
16
        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
13
        push @patterns, $_;
109
12
17
        $hints{$_} = $hint;
110      }
111
13
21
      $hint = '';
112    }
113  }
114
115  return {
116
6
22
    patterns => \@patterns,
117    hints => \%hints,
118  };
119}
120
121sub file_to_list {
122
5
1283
  my ($re) = @_;
123
5
9
  my $lists = file_to_lists($re);
124
125
5
5
3
16
  return @{$lists->{'patterns'}};
126}
127
128sub list_to_re {
129
5
5
  my (@list) = @_;
130
5
11
11
3
10
10
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
131
5
11
5
11
  @list = grep { $_ ne '' } @list;
132
5
8
  return '$^' unless scalar @list;
133
5
12
  return join "|", (@list);
134}
135
136sub not_empty {
137
106
99
  my ($thing) = @_;
138
106
454
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
139}
140
141sub parse_block_list {
142
3
2
  my ($re) = @_;
143
3
2
  my @file;
144
3
25
  return @file unless (open(FILE, '<:utf8', $re));
145
146
3
6
  local $/=undef;
147
3
23
  my $file=<FILE>;
148
3
4
  my $last_line = $.;
149
3
8
  close FILE;
150
3
11
  for (split /\R/, $file) {
151
8
9
    next if /^#/;
152
5
3
    chomp;
153
5
5
    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
3
  unless ($pairs == $true_pairs) {
161
1
2
    my $early_warnings = CheckSpelling::Util::get_file_from_env('early_warnings', '/dev/null');
162
1
1
1
1
2
0
3
15
    open EARLY_WARNINGS, ">>:encoding(UTF-8)", $early_warnings;
163
1
455
    print EARLY_WARNINGS "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
164
1
24
    close EARLY_WARNINGS;
165
1
1
    my $i = 0;
166
1
2
    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
8
  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
29
  $shortest = $shortest_word if $shortest_word;
182
28
43
  if ($longest_word) {
183    # longest_word is an absolute
184
26
19
    $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
4
    $longest += 2;
189  }
190
28
24
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
191
28
84
24
190
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
192
28
21
  $word_pattern = q<\\w|'> unless $word_pattern;
193
28
44
  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
27
  $shortest = 3 unless defined $shortest;
199
28
25
  $longest = '' unless not_empty($longest);
200
28
85
  $word_match = "(?:$word_pattern){$shortest,$longest}";
201
28
215
  return qr/\b$word_match\b/;
202}
203
204sub load_dictionary {
205
15
1979
  my ($dict) = @_;
206
15
6
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
207
15
13
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
208
15
11
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
209
15
7
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
210
15
14
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
211
15
51
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
212
15
31
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
213
15
27
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
214
15
33
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
215
15
32
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
216
15
36
  %dictionary = ();
217
218
15
465
  open(DICT, '<:utf8', $dict);
219
15
71
  while (!eof(DICT)) {
220
52
60
    my $word = <DICT>;
221
52
34
    chomp $word;
222
52
125
    next unless $word =~ $word_match;
223
49
39
    my $l = length $word;
224
49
31
    $longest = -1 unless not_empty($longest);
225
49
50
    $longest = $l if $l > $longest;
226
49
41
    $shortest = $l if $l < $shortest;
227
49
107
    $dictionary{$word}=1;
228  }
229
15
40
  close DICT;
230
231
15
9
  $word_match = valid_word();
232}
233
234sub hunspell_dictionary {
235
3
7
  my ($dict) = @_;
236
3
4
  my $name = $dict;
237
3
3
  $name =~ s{/src/index/hunspell/index\.dic$}{};
238
3
14
  $name =~ s{.*/}{};
239
3
5
  my $aff = $dict;
240
3
2
  my $encoding;
241
3
31
  $aff =~ s/\.dic$/.aff/;
242
3
34
  if (open AFF, '<', $aff) {
243
3
23
    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
8
    close AFF;
249  }
250  return {
251
3
299
    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
15618
  my ($configuration) = @_;
261
12
10
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
262
12
7
  our ($begin_block_re, @begin_block_list, @end_block_list);
263
12
34
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
264
12
11
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
265
12
21
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
266
12
6
  our %forbidden_re_descriptions;
267
12
13
  if ($hunspell_dictionary_path) {
268
3
32
    our @hunspell_dictionaries = ();
269
1
1
1
1
1
1
1
1
1
3
271
1070
21
7
0
14
6
3
32
149
    if (eval 'use Text::Hunspell; 1') {
270
3
116
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
271
3
6
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
272
3
4
        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
108
  if (-e "$configuration/block-delimiters.list") {
280
3
5
    my @block_delimiters = parse_block_list "$configuration/block-delimiters.list";
281
3
3
    if (@block_delimiters) {
282
2
2
      @begin_block_list = ();
283
2
0
      @end_block_list = ();
284
285
2
2
      while (@block_delimiters) {
286
2
3
        my ($begin, $end) = splice @block_delimiters, 0, 2;
287
2
2
        push @begin_block_list, $begin;
288
2
3
        push @end_block_list, $end;
289      }
290
291
2
2
2
2
      $begin_block_re = join '|', (map { '('.quote_re("\Q$_\E").')' } @begin_block_list);
292    }
293  }
294
295
12
18
  my (@patterns_re_list, %in_patterns_re_list);
296
12
48
  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
9
    $patterns_re = undef;
302  }
303
304
12
45
  if (-e "$configuration/forbidden.txt") {
305
1
2
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
306
1
1
1
2
    @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
7
    $forbidden_re = undef;
311  }
312
313
12
56
  if (-e "$configuration/candidates.txt") {
314
4
6
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
315
4
8
8
5
6
15
    @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
4
    $candidates_re = undef;
319  }
320
321
12
19
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
322
323
12
11
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
324
12
11
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
325
12
10
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
326
12
6
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
327
328
12
10
  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
9
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
332
12
7
  $check_images = $check_images =~ /^(?:1|true)$/i;
333
12
9
  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
8
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
339
340
12
11
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
341
342
12
10
  $word_match = valid_word();
343
344
12
20
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
345
12
56
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
346
12
23
  load_dictionary($base_dict);
347}
348
349sub split_line {
350
1160
560
  our (%dictionary, $word_match, $disable_word_collating);
351
1160
433
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
352
1160
470
  our @hunspell_dictionaries;
353
1160
437
  our $shortest;
354
1160
720
  my $shortest_threshold = $shortest + 2;
355
1160
610
  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
589
  my $rsqm = "\xE2\x80\x99";
360
361
1160
727
  my ($words, $unrecognized) = (0, 0);
362
1160
801
  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
2208
    $line =~ s/(?:$ignore_pattern)+/ /g;
365
1160
1760
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
366
1160
3332
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
367
1160
1367
    for my $token (split /\s+/, $line) {
368
3642
3407
      next unless $token =~ /$pattern/;
369
2483
2021
      $token =~ s/^(?:'|$rsqm)+//g;
370
2483
2427
      $token =~ s/(?:'|$rsqm)+s?$//g;
371
2483
1492
      my $raw_token = $token;
372
2483
1408
      $token =~ s/^[^Ii]?'+(.*)/$1/;
373
2483
1377
      $token =~ s/(.*?)'+$/$1/;
374
2483
3843
      next unless $token =~ $word_match;
375
2318
2111
      if (defined $dictionary{$token}) {
376
1038
405
        ++$words;
377
1038
654
        $unique_ref->{$token}=1;
378
1038
805
        next;
379      }
380
1280
998
      if (@hunspell_dictionaries) {
381
1254
656
        my $found = 0;
382
1254
756
        for my $hunspell_dictionary (@hunspell_dictionaries) {
383          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
384
1254
1092
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
385
1254
2843
          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
1022
        next if $found;
393      }
394
1280
967
      my $key = lc $token;
395
1280
1147
      if (defined $dictionary{$key}) {
396
6
2
        ++$words;
397
6
5
        $unique_ref->{$key}=1;
398
6
7
        next;
399      }
400
1274
960
      unless ($disable_word_collating) {
401
1274
737
        $key =~ s/''+/'/g;
402
1274
1378
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
403      }
404
1274
1090
      if (defined $dictionary{$key}) {
405
0
0
        ++$words;
406
0
0
        $unique_ref->{$key}=1;
407
0
0
        next;
408      }
409
1274
659
      ++$unrecognized;
410
1274
804
      $unique_unrecognized_ref->{$raw_token}=1;
411
1274
1657
      $unrecognized_line_items_ref->{$raw_token}=1;
412    }
413
1160
1610
    return ($words, $unrecognized);
414}
415
416sub skip_file {
417
7
30
  my ($temp_dir, $reason) = @_;
418
7
205
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
419
7
43
  print SKIPPED $reason;
420
7
115
  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
12000
  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
34
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
480
481
18
9
  our %forbidden_re_descriptions;
482
18
8
  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
8
  my $rsqm = "\xE2\x80\x99";
486
487
18
22
  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
16
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
490
18
16
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
491
18
34
  my $temp_dir = tempdir(DIR=>$sandbox);
492
18
2736
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
493
18
418
  open(NAME, '>', "$temp_dir/name");
494
18
48
    print NAME $file;
495
18
250
  close NAME;
496
18
201
  if (defined readlink($file) &&
497      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
498
1
3
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
499
1
3
    return $temp_dir;
500  }
501
17
26
  if ($use_magic_file) {
502
8
12530
    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
30768
      my $file_kind = <$file_fh>;
514
8
5060
      close $file_fh;
515
8
13
      my $file_converted = 0;
516
8
24
      if ($check_images && $file_kind =~ m<^image/>) {
517
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
518      }
519
8
199
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
520
2
32
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
521
2
53
        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
86
  my $file_size = -s $file;
529
15
13
  if (defined $largest_file) {
530
15
14
    unless ($check_file_names eq $file) {
531
15
14
      if ($file_size > $largest_file) {
532
1
18
        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
123
  open FILE, '<', $file;
538
14
10
  binmode FILE;
539
14
8
  my $head;
540
14
119
  read(FILE, $head, 4096);
541
14
890
  $head =~ s/(?:\r|\n)+$//;
542
14
60
  my $dos_new_lines = () = $head =~ /\r\n/gi;
543
14
42
  my $unix_new_lines = () = $head =~ /\n/gi;
544
14
104
  my $mac_new_lines = () = $head =~ /\r/gi;
545
14
59
  local $/;
546
14
71
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
547
3
7
    $/ = "\n";
548  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
549
1
5
    $/ = "\r\n";
550  } elsif ($mac_new_lines > $unix_new_lines) {
551
2
9
    $/ = "\r";
552  } else {
553
8
9
    $/ = "\n";
554  }
555
14
35
  seek(FILE, 0, 0);
556
14
18
  ($words, $unrecognized) = (0, 0);
557
14
39
  %unique = ();
558
14
26
  %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
127
  };
566
567
14
374
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
568
14
15
  our $timeout;
569
14
12
  eval {
570
14
0
107
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
28
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
575
14
15
    my $offset = 0;
576
14
98
    LINE: while (<FILE>) {
577
1169
1012
      if ($. == 1) {
578
14
14
        unless ($disable_minified_file) {
579
14
63
          if ($file_size >= 512 && length($_) == $file_size) {
580
1
12
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
581
1
6
            last;
582          }
583        }
584      }
585
1168
2368
      $_ = decode_utf8($_, FB_DEFAULT);
586
1168
2714
      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
1498
      s/\R$//;
591
1168
1082
      s/^\x{FEFF}// if $. == 1;
592
1168
1089
      next unless /./;
593
1167
770
      my $raw_line = $_;
594
1167
571
      my $parsed_block_markers;
595
596      # hook for custom multiline based text exclusions:
597
1167
786
      if ($begin_block_re) {
598
1148
567
        FIND_END_MARKER: while (1) {
599
1150
918
          while ($next_end_marker ne '') {
600
6
49
            next LINE unless /\Q$next_end_marker\E/;
601
1
5
            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
1148
          my @captured = (/^.*?$begin_block_re/);
606
1145
1052
          last unless (@captured);
607
2
2
          for my $capture (0 .. $#captured) {
608
2
2
            if ($captured[$capture]) {
609
2
6
              ($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
3
              next FIND_END_MARKER;
613            }
614          }
615        }
616
1143
804
        next if $parsed_block_markers;
617      }
618
619
1161
631
      my $ignore_this_line = $ignore_next_line;
620
1161
979
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
621
1161
826
      next if $ignore_this_line;
622
623      # hook for custom line based text exclusions:
624
1160
851
      if (defined $patterns_re) {
625
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
626      }
627
1160
639
      my $initial_line_state = $_;
628
1160
741
      my $previous_line_state = $_;
629
1160
613
      my $line_flagged;
630
1160
786
      if ($forbidden_re) {
631
9
5
60
11
        while (s/($forbidden_re)/"="x length($1)/e) {
632
5
4
          $line_flagged = 1;
633
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
634
5
2
          my $found_trigger_re;
635
5
5
          for my $i (0 .. $#forbidden_re_list) {
636
7
6
            my $forbidden_re_singleton = $forbidden_re_list[$i];
637
7
4
            my $test_line = $previous_line_state;
638
7
4
57
9
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
639
4
5
              next unless $test_line eq $_;
640
4
5
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
641
4
4
              next unless $begin == $begin_test;
642
4
3
              next unless $end == $end_test;
643
4
4
              next unless $match eq $match_test;
644
4
3
              $found_trigger_re = $forbidden_re_singleton;
645
4
7
              my $hit = "$.:$begin:$end";
646
4
4
              $forbidden_re_hits[$i]++;
647
4
4
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
648
4
6
              last;
649            }
650          }
651
5
7
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
652
5
5
          if ($found_trigger_re) {
653
4
8
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
654
4
8
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
655
4
5
            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
6
              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
25
          $previous_line_state = $_;
665        }
666
9
10
        $_ = $initial_line_state;
667      }
668      # This is to make it easier to deal w/ rules:
669
1160
1135
      s/^/ /;
670
1160
699
      my %unrecognized_line_items = ();
671
1160
898
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
672
1160
653
      $words += $new_words;
673
1160
595
      $unrecognized += $new_unrecognized;
674
1160
726
      my $line_length = length($raw_line);
675
1160
1629
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
676
1021
489
        my $found_token = 0;
677
1021
483
        my $raw_token = $token;
678
1021
539
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
679
1021
436
        my $before;
680
1021
1594
        if ($token =~ /^$upper_pattern$lower_pattern/) {
681
5
3
          $before = '(?<=.)';
682        } elsif ($token =~ /^$upper_pattern/) {
683
0
0
          $before = "(?<!$upper_pattern)";
684        } else {
685
1016
566
          $before = "(?<=$not_lower_pattern)";
686        }
687
1021
1144
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
688
1021
2170
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
689
1271
615
          $line_flagged = 1;
690
1271
575
          $found_token = 1;
691
1271
1699
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
692
1271
1245
          next unless $match =~ /./;
693
1271
1009
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
694
1271
4916
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
695        }
696
1021
1136
        unless ($found_token) {
697
3
28
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
698
3
22
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
699
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
700
3
12
            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
1885
      if ($line_flagged && $candidates_re) {
709
2
2
        $_ = $previous_line_state = $initial_line_state;
710
2
2
20
5
        s/($candidates_re)/"="x length($1)/ge;
711
2
3
        if ($_ ne $initial_line_state) {
712
2
1
          $_ = $previous_line_state;
713
2
3
          for my $i (0 .. $#candidates_re_list) {
714
4
4
            my $candidate_re = $candidates_re_list[$i];
715
4
26
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
716
2
2
7
3
            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
2
              $_ = $previous_line_state;
720
2
2
7
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
721
2
3
              $candidates_re_hits[$i] += $replacements;
722
2
2
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
723
2
5
              $_ = $previous_line_state;
724            }
725          }
726        }
727      }
728
1160
912
      unless ($disable_minified_file) {
729
1160
974
        s/={3,}//g;
730
1160
803
        $offset += length;
731
1160
1013
        my $ratio = int($offset / $.);
732
1160
662
        my $ratio_threshold = 1000;
733
1160
3157
        if ($ratio > $ratio_threshold) {
734
2
8
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
735
2
7
          last;
736        }
737      }
738    }
739
14
14
    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
1
      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
106
    alarm 0;
749  };
750
14
14
  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
50
  close FILE;
758
14
165
  close WARNINGS;
759
760
14
31
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
761
13
337
    open(STATS, '>:utf8', "$temp_dir/stats");
762
13
195
      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
176
    close STATS;
770
13
261
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
771
13
20
49
32
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
772
13
122
    close UNKNOWN;
773  }
774
775
14
138
  return $temp_dir;
776}
777
778sub main {
779
4
425
  my ($configuration, @ARGV) = @_;
780
4
2
  our %dictionary;
781
4
4
  unless (%dictionary) {
782
1
1
    init($configuration);
783  }
784
785  # read all input
786
4
4
  my @reports;
787
788
4
3
  for my $file (@ARGV) {
789
4
2
    my $temp_dir = split_file($file);
790
4
6
    push @reports, "$temp_dir\n";
791  }
792
4
11
  print join '', @reports;
793}
794
7951;