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
109824
2
use 5.022;
11
1
1
1
2
0
40
use feature 'unicode_strings';
12
1
1
1
5
1
6
use strict;
13
1
1
1
2
0
20
use warnings;
14
1
1
1
2
0
14
no warnings qw(experimental::vlb);
15
1
1
1
2
0
2
use utf8;
16
1
1
1
10
0
26
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
2
0
25
use File::Basename;
18
1
1
1
1
1
14
use Cwd 'abs_path';
19
1
1
1
1
1
20
use File::Spec;
20
1
1
1
1
1
13
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
293
2
4008
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
201
  return eval { qr /$expression/ };
48}
49
50sub quote_re {
51
34
26
  my ($expression) = @_;
52
34
28
  return $expression if $expression =~ /\?\{/;
53
34
63
  $expression =~ s/
54   \G
55   (
56      (?:[^\\]|\\[^Q])*
57   )
58   (?:
59      \\Q
60      (?:[^\\]|\\[^E])*
61      (?:\\E)?
62   )?
63/
64
68
108
   $1 . (defined($2) ? quotemeta($2) : '')
65/xge;
66
34
40
  return $expression;
67}
68
69sub file_to_lists {
70
6
5
  my ($re) = @_;
71
6
6
  my @patterns;
72  my %hints;
73
6
0
  my $fh;
74
6
59
  if (open($fh, '<:utf8', $re)) {
75
6
10
    local $/=undef;
76
6
40
    my $file=<$fh>;
77
6
18
    close $fh;
78
6
3
    my $line_number = 0;
79
6
3
    my $hint = '';
80
6
24
    for (split /\R/, $file) {
81
32
18
      ++$line_number;
82
32
12
      chomp;
83
32
35
      if (/^#(?:\s(.+)|)/) {
84
12
30
        $hint = $1 if ($hint eq '' && defined $1);
85
12
10
        next;
86      }
87
20
20
      $hint = '' unless $_ ne '';
88
20
20
      next if $_ eq '$^';
89
20
15
      my $pattern = $_;
90
20
50
      next unless s/^(.+)/(?:$1)/;
91
13
13
      my $quoted = quote_re($1);
92
13
9
      unless (test_re $quoted) {
93
1
3
        my $error = $@;
94
1
40
        my $home = dirname(__FILE__);
95
1
19
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
96
1
11
        print STDERR $error;
97
1
4
        $_ = '(?:\$^ - skipped because bad-regex)';
98
1
1
        $hint = '';
99      }
100
13
18
      if (defined $hints{$_}) {
101
1
2
        my $pattern_length = length $pattern;
102
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
103
1
15
        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
16
        $hints{$_} = $hint;
108      }
109
13
21
      $hint = '';
110    }
111  }
112
113  return {
114
6
23
    patterns => \@patterns,
115    hints => \%hints,
116  };
117}
118
119sub file_to_list {
120
5
1267
  my ($re) = @_;
121
5
5
  my $lists = file_to_lists($re);
122
123
5
5
2
15
  return @{$lists->{'patterns'}};
124}
125
126sub list_to_re {
127
5
5
  my (@list) = @_;
128
5
11
11
5
9
10
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
129
5
11
4
11
  @list = grep { $_ ne '' } @list;
130
5
5
  return '$^' unless scalar @list;
131
5
11
  return join "|", (@list);
132}
133
134sub not_empty {
135
106
78
  my ($thing) = @_;
136
106
449
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
137}
138
139sub parse_block_list {
140
3
3
  my ($re) = @_;
141
3
3
  my @file;
142
3
24
  return @file unless (open(FILE, '<:utf8', $re));
143
144
3
6
  local $/=undef;
145
3
22
  my $file=<FILE>;
146
3
5
  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
2
    s/^\\#/#/;
152
5
6
    next unless /^./;
153
5
6
    push @file, $_;
154  }
155
156
3
4
  my $pairs = (0+@file) / 2;
157
3
3
  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
2
0
2
13
    open EARLY_WARNINGS, ">>:encoding(UTF-8)", $early_warnings;
161
1
377
    print EARLY_WARNINGS "$re:$last_line:Block delimiters must come in pairs (uneven-block-delimiters)\n";
162
1
22
    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
10
    print STDERR "block-delimiter unmatched S: `$file[$i*2]`\n";
170
1
2
    @file = ();
171  }
172
173
3
6
  return @file;
174}
175
176sub valid_word {
177  # shortest_word is an absolute
178
28
17
  our ($shortest, $longest, $shortest_word, $longest_word);
179
28
23
  $shortest = $shortest_word if $shortest_word;
180
28
20
  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
17
216
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
190
28
24
  $word_pattern = q<\\w|'> unless $word_pattern;
191
28
73
  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
17
  $longest = '' unless not_empty($longest);
198
28
94
  $word_match = "(?:$word_pattern){$shortest,$longest}";
199
28
211
  return qr/\b$word_match\b/;
200}
201
202sub load_dictionary {
203
15
1944
  my ($dict) = @_;
204
15
10
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
205
15
13
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
206
15
13
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
207
15
6
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
208
15
13
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
209
15
51
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
210
15
35
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
211
15
22
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
212
15
20
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
213
15
28
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
214
15
35
  %dictionary = ();
215
216
15
514
  open(DICT, '<:utf8', $dict);
217
15
66
  while (!eof(DICT)) {
218
52
47
    my $word = <DICT>;
219
52
51
    chomp $word;
220
52
121
    next unless $word =~ $word_match;
221
49
43
    my $l = length $word;
222
49
29
    $longest = -1 unless not_empty($longest);
223
49
47
    $longest = $l if $l > $longest;
224
49
35
    $shortest = $l if $l < $shortest;
225
49
94
    $dictionary{$word}=1;
226  }
227
15
38
  close DICT;
228
229
15
11
  $word_match = valid_word();
230}
231
232sub hunspell_dictionary {
233
3
6
  my ($dict) = @_;
234
3
3
  my $name = $dict;
235
3
5
  $name =~ s{/src/index/hunspell/index\.dic$}{};
236
3
12
  $name =~ s{.*/}{};
237
3
3
  my $aff = $dict;
238
3
3
  my $encoding;
239
3
8
  $aff =~ s/\.dic$/.aff/;
240
3
29
  if (open AFF, '<', $aff) {
241
3
28
    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
7
    close AFF;
247  }
248  return {
249
3
341
    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
15169
  my ($configuration) = @_;
259
12
15
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
260
12
3
  our ($begin_block_re, @begin_block_list, @end_block_list);
261
12
25
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
262
12
11
  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
9
  our %forbidden_re_descriptions;
265
12
12
  if ($hunspell_dictionary_path) {
266
3
34
    our @hunspell_dictionaries = ();
267
1
1
1
1
1
1
1
1
1
3
271
1021
22
6
0
13
6
2
16
151
    if (eval 'use Text::Hunspell; 1') {
268
3
148
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
269
3
9
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
270
3
5
        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
119
  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
2
      @end_block_list = ();
282
283
2
2
      while (@block_delimiters) {
284
2
2
        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
20
  my (@patterns_re_list, %in_patterns_re_list);
294
12
53
  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
16
    $patterns_re = undef;
300  }
301
302
12
44
  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
2
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
306
1
1
    $forbidden_re = list_to_re @forbidden_re_list;
307  } else {
308
11
9
    $forbidden_re = undef;
309  }
310
311
12
49
  if (-e "$configuration/candidates.txt") {
312
4
5
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
313
4
8
8
4
3
14
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
314
4
2
    $candidates_re = list_to_re @candidates_re_list;
315  } else {
316
8
7
    $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
11
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
322
12
10
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
323
12
7
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
324
12
5
  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
8
  $ignore_next_line_pattern =~ s/\s+/|/g;
328
329
12
7
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
330
12
8
  $check_images = $check_images =~ /^(?:1|true)$/i;
331
332
12
12
  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
14
  $word_match = valid_word();
337
338
12
19
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
339
12
53
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
340
12
12
  load_dictionary($base_dict);
341}
342
343sub split_line {
344
1160
517
  our (%dictionary, $word_match, $disable_word_collating);
345
1160
510
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
346
1160
468
  our @hunspell_dictionaries;
347
1160
563
  our $shortest;
348
1160
793
  my $shortest_threshold = $shortest + 2;
349
1160
607
  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
563
  my $rsqm = "\xE2\x80\x99";
354
355
1160
649
  my ($words, $unrecognized) = (0, 0);
356
1160
775
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
357
1160
5742
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
358
1160
2243
    $line =~ s/(?:$ignore_pattern)+/ /g;
359
1160
1745
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
360
1160
3391
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
361
1160
1423
    for my $token (split /\s+/, $line) {
362
3642
3308
      next unless $token =~ /$pattern/;
363
2483
2208
      $token =~ s/^(?:'|$rsqm)+//g;
364
2483
2504
      $token =~ s/(?:'|$rsqm)+s?$//g;
365
2483
1421
      my $raw_token = $token;
366
2483
1407
      $token =~ s/^[^Ii]?'+(.*)/$1/;
367
2483
1248
      $token =~ s/(.*?)'+$/$1/;
368
2483
3762
      next unless $token =~ $word_match;
369
2318
2079
      if (defined $dictionary{$token}) {
370
1038
486
        ++$words;
371
1038
570
        $unique_ref->{$token}=1;
372
1038
853
        next;
373      }
374
1280
906
      if (@hunspell_dictionaries) {
375
1254
615
        my $found = 0;
376
1254
721
        for my $hunspell_dictionary (@hunspell_dictionaries) {
377          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
378
1254
1070
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
379
1254
3133
          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
1024
        next if $found;
387      }
388
1280
961
      my $key = lc $token;
389
1280
1200
      if (defined $dictionary{$key}) {
390
6
4
        ++$words;
391
6
5
        $unique_ref->{$key}=1;
392
6
6
        next;
393      }
394
1274
883
      unless ($disable_word_collating) {
395
1274
733
        $key =~ s/''+/'/g;
396
1274
1379
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
397      }
398
1274
1063
      if (defined $dictionary{$key}) {
399
0
0
        ++$words;
400
0
0
        $unique_ref->{$key}=1;
401
0
0
        next;
402      }
403
1274
578
      ++$unrecognized;
404
1274
872
      $unique_unrecognized_ref->{$raw_token}=1;
405
1274
1654
      $unrecognized_line_items_ref->{$raw_token}=1;
406    }
407
1160
1633
    return ($words, $unrecognized);
408}
409
410sub skip_file {
411
7
27
  my ($temp_dir, $reason) = @_;
412
7
194
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
413
7
33
  print SKIPPED $reason;
414
7
100
  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
11667
  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
35
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
452
453
18
5
  our %forbidden_re_descriptions;
454
18
11
  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
9
  my $rsqm = "\xE2\x80\x99";
458
459
18
17
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
460
18
13
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
461
18
9
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
462
18
13
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
463
18
30
  my $temp_dir = tempdir(DIR=>$sandbox);
464
18
2582
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
465
18
396
  open(NAME, '>', "$temp_dir/name");
466
18
60
    print NAME $file;
467
18
255
  close NAME;
468
18
178
  if (defined readlink($file) &&
469      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
470
1
12
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
471
1
4
    return $temp_dir;
472  }
473
17
35
  if ($use_magic_file) {
474
8
11100
    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
29598
      my $file_kind = <$file_fh>;
486
8
4876
      close $file_fh;
487
8
11
      my $file_converted = 0;
488
8
14
      if ($check_images && $file_kind =~ m<^image/>) {
489
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
490      }
491
8
190
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
492
2
30
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
493
2
53
        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
80
  my $file_size = -s $file;
501
15
19
  if (defined $largest_file) {
502
15
16
    unless ($check_file_names eq $file) {
503
15
13
      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
119
  open FILE, '<', $file;
510
14
11
  binmode FILE;
511
14
8
  my $head;
512
14
153
  read(FILE, $head, 4096);
513
14
798
  $head =~ s/(?:\r|\n)+$//;
514
14
56
  my $dos_new_lines = () = $head =~ /\r\n/gi;
515
14
42
  my $unix_new_lines = () = $head =~ /\n/gi;
516
14
108
  my $mac_new_lines = () = $head =~ /\r/gi;
517
14
57
  local $/;
518
14
70
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
519
3
3
    $/ = "\n";
520  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
521
1
5
    $/ = "\r\n";
522  } elsif ($mac_new_lines > $unix_new_lines) {
523
2
5
    $/ = "\r";
524  } else {
525
8
8
    $/ = "\n";
526  }
527
14
35
  seek(FILE, 0, 0);
528
14
16
  ($words, $unrecognized) = (0, 0);
529
14
31
  %unique = ();
530
14
28
  %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
112
  };
538
539
14
350
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
540
14
9
  our $timeout;
541
14
10
  eval {
542
14
0
107
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
543
14
40
    alarm $timeout;
544
545
14
13
    my $ignore_next_line = 0;
546
14
26
    my ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
547
14
16
    my $offset = 0;
548
14
112
    LINE: while (<FILE>) {
549
1169
1094
      if ($. == 1) {
550
14
23
        unless ($disable_minified_file) {
551
14
80
          if ($file_size >= 512 && length($_) == $file_size) {
552
1
9
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
553
1
3
            last;
554          }
555        }
556      }
557
1168
2418
      $_ = decode_utf8($_, FB_DEFAULT);
558
1168
2787
      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
1446
      s/\R$//;
563
1168
1110
      s/^\x{FEFF}// if $. == 1;
564
1168
1076
      next unless /./;
565
1167
777
      my $raw_line = $_;
566
1167
574
      my $parsed_block_markers;
567
568      # hook for custom multiline based text exclusions:
569
1167
768
      if ($begin_block_re) {
570
1148
565
        FIND_END_MARKER: while (1) {
571
1150
1003
          while ($next_end_marker ne '') {
572
6
43
            next LINE unless /\Q$next_end_marker\E/;
573
1
5
            s/.*?\Q$next_end_marker\E//;
574
1
2
            ($current_begin_marker, $next_end_marker, $start_marker_line) = ('', '', '');
575
1
1
            $parsed_block_markers = 1;
576          }
577
1145
1203
          my @captured = (/^.*?$begin_block_re/);
578
1145
1011
          last unless (@captured);
579
2
2
          for my $capture (0 .. $#captured) {
580
2
2
            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
11
              s/^.*?\Q$begin_block_list[$capture]\E//;
583
2
2
              $parsed_block_markers = 1;
584
2
3
              next FIND_END_MARKER;
585            }
586          }
587        }
588
1143
802
        next if $parsed_block_markers;
589      }
590
591
1161
674
      my $ignore_this_line = $ignore_next_line;
592
1161
1123
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
593
1161
725
      next if $ignore_this_line;
594
595      # hook for custom line based text exclusions:
596
1160
828
      if (defined $patterns_re) {
597
2
6
10
8
        s/($patterns_re)/"="x length($1)/ge;
598      }
599
1160
699
      my $initial_line_state = $_;
600
1160
753
      my $previous_line_state = $_;
601
1160
537
      my $line_flagged;
602
1160
820
      if ($forbidden_re) {
603
9
5
63
11
        while (s/($forbidden_re)/"="x length($1)/e) {
604
5
3
          $line_flagged = 1;
605
5
9
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
606
5
3
          my $found_trigger_re;
607
5
6
          for my $i (0 .. $#forbidden_re_list) {
608
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
609
7
4
            my $test_line = $previous_line_state;
610
7
4
61
7
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
611
4
3
              next unless $test_line eq $_;
612
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
613
4
3
              next unless $begin == $begin_test;
614
4
4
              next unless $end == $end_test;
615
4
3
              next unless $match eq $match_test;
616
4
2
              $found_trigger_re = $forbidden_re_singleton;
617
4
8
              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
6
              last;
621            }
622          }
623
5
5
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
624
5
6
          if ($found_trigger_re) {
625
4
7
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
626
4
9
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
627
4
3
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
628
4
6
            if ($description ne '') {
629
3
15
              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
25
          $previous_line_state = $_;
637        }
638
9
6
        $_ = $initial_line_state;
639      }
640      # This is to make it easier to deal w/ rules:
641
1160
1118
      s/^/ /;
642
1160
680
      my %unrecognized_line_items = ();
643
1160
959
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
644
1160
675
      $words += $new_words;
645
1160
554
      $unrecognized += $new_unrecognized;
646
1160
768
      my $line_length = length($raw_line);
647
1160
1587
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
648
1021
500
        my $found_token = 0;
649
1021
490
        my $raw_token = $token;
650
1021
622
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
651
1021
436
        my $before;
652
1021
1553
        if ($token =~ /^$upper_pattern$lower_pattern/) {
653
5
13
          $before = '(?<=.)';
654        } elsif ($token =~ /^$upper_pattern/) {
655
0
0
          $before = "(?<!$upper_pattern)";
656        } else {
657
1016
578
          $before = "(?<=$not_lower_pattern)";
658        }
659
1021
1133
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
660
1021
2115
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
661
1271
688
          $line_flagged = 1;
662
1271
595
          $found_token = 1;
663
1271
1740
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
664
1271
1162
          next unless $match =~ /./;
665
1271
914
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
666
1271
4879
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
667        }
668
1021
1151
        unless ($found_token) {
669
3
29
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
670
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
671
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
672
3
12
            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
1946
      if ($line_flagged && $candidates_re) {
681
2
2
        $_ = $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
2
          for my $i (0 .. $#candidates_re_list) {
686
4
4
            my $candidate_re = $candidates_re_list[$i];
687
4
25
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
688
2
2
9
3
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
689
2
3
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
690
2
5
              my $hit = "$.:$begin:$end";
691
2
1
              $_ = $previous_line_state;
692
2
2
6
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
693
2
2
              $candidates_re_hits[$i] += $replacements;
694
2
4
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
695
2
4
              $_ = $previous_line_state;
696            }
697          }
698        }
699      }
700
1160
838
      unless ($disable_minified_file) {
701
1160
935
        s/={3,}//g;
702
1160
821
        $offset += length;
703
1160
1096
        my $ratio = int($offset / $.);
704
1160
610
        my $ratio_threshold = 1000;
705
1160
3166
        if ($ratio > $ratio_threshold) {
706
2
6
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
707
2
7
          last;
708        }
709      }
710    }
711
14
17
    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
8
        print WARNINGS ":$start_marker_line, Warning - Failed to find matching end marker for $wrapped (unclosed-block-ignore-begin)\n";
715      }
716
1
1
      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
97
    alarm 0;
721  };
722
14
12
  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
47
  close FILE;
730
14
166
  close WARNINGS;
731
732
14
23
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
733
13
334
    open(STATS, '>:utf8', "$temp_dir/stats");
734
13
191
      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
164
    close STATS;
742
13
246
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
743
13
20
47
47
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
744
13
114
    close UNKNOWN;
745  }
746
747
14
121
  return $temp_dir;
748}
749
750sub main {
751
4
387
  my ($configuration, @ARGV) = @_;
752
4
2
  our %dictionary;
753
4
10
  unless (%dictionary) {
754
1
1
    init($configuration);
755  }
756
757  # read all input
758
4
2
  my @reports;
759
760
4
3
  for my $file (@ARGV) {
761
4
4
    my $temp_dir = split_file($file);
762
4
7
    push @reports, "$temp_dir\n";
763  }
764
4
9
  print join '', @reports;
765}
766
7671;