File Coverage

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

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