File Coverage

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

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