File Coverage

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

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
113011
2
use 5.022;
11
1
1
1
2
0
74
use feature 'unicode_strings';
12
1
1
1
2
0
9
use strict;
13
1
1
1
2
0
21
use warnings;
14
1
1
1
1
0
16
no warnings qw(experimental::vlb);
15
1
1
1
2
0
3
use utf8;
16
1
1
1
13
0
38
use Encode qw/decode_utf8 encode FB_DEFAULT/;
17
1
1
1
1
1
31
use File::Basename;
18
1
1
1
1
1
16
use Cwd 'abs_path';
19
1
1
1
2
0
23
use File::Spec;
20
1
1
1
2
0
20
use File::Temp qw/ tempfile tempdir /;
21
1
1
1
277
1
3474
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 ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
26my ($shortest, $longest) = (255, 0);
27my @forbidden_re_list;
28my %forbidden_re_descriptions;
29my @candidates_re_list;
30my $hunspell_dictionary_path;
31my @hunspell_dictionaries;
32my %dictionary = ();
33my $base_dict;
34my %unique;
35my %unique_unrecognized;
36my ($last_file, $words, $unrecognized) = ('', 0, 0);
37my ($ignore_next_line_pattern);
38my ($check_images);
39
40my $disable_flags;
41
42sub test_re {
43
14
12
  my ($expression) = @_;
44
14
14
7
112
  return eval { qr /$expression/ };
45}
46
47sub quote_re {
48
14
9
  my ($expression) = @_;
49
14
16
  return $expression if $expression =~ /\?\{/;
50
14
34
  $expression =~ s/
51   \G
52   (
53      (?:[^\\]|\\[^Q])*
54   )
55   (?:
56      \\Q
57      (?:[^\\]|\\[^E])*
58      (?:\\E)?
59   )?
60/
61
28
48
   $1 . (defined($2) ? quotemeta($2) : '')
62/xge;
63
14
18
  return $expression;
64}
65
66sub file_to_lists {
67
3
2
  my ($re) = @_;
68
3
6
  my @patterns;
69  my %hints;
70
3
0
  my $fh;
71
3
30
  if (open($fh, '<:utf8', $re)) {
72
3
7
    local $/=undef;
73
3
24
    my $file=<$fh>;
74
3
28
    close $fh;
75
3
4
    my $line_number = 0;
76
3
3
    my $hint = '';
77
3
16
    for (split /\R/, $file) {
78
17
11
      ++$line_number;
79
17
8
      chomp;
80
17
24
      if (/^#(?:\s(.+)|)/) {
81
6
11
        $hint = $1 if ($hint eq '' && defined $1);
82
6
6
        next;
83      }
84
11
14
      $hint = '' unless $_ ne '';
85
11
11
      next if $_ eq '$^';
86
11
9
      my $pattern = $_;
87
11
34
      next unless s/^(.+)/(?:$1)/;
88
7
9
      my $quoted = quote_re($1);
89
7
8
      unless (test_re $quoted) {
90
1
2
        my $error = $@;
91
1
52
        my $home = dirname(__FILE__);
92
1
36
        $error =~ s/$home.*?\.pm line \d+\./$re line $line_number (bad-regex)/;
93
1
15
        print STDERR $error;
94
1
1
        $_ = '(?:\$^ - skipped because bad-regex)';
95
1
2
        $hint = '';
96      }
97
7
13
      if (defined $hints{$_}) {
98
1
1
        my $pattern_length = length $pattern;
99
1
1
        my $wrapped = CheckSpelling::Util::wrap_in_backticks($pattern);
100
1
16
        print STDERR "$re:$line_number:1 ... $pattern_length, Warning - duplicate pattern: $wrapped (duplicate-pattern)\n";
101
1
2
        $_ = '(?:\$^ - skipped because duplicate-pattern on $line_number)';
102      } else {
103
6
7
        push @patterns, $_;
104
6
9
        $hints{$_} = $hint;
105      }
106
7
13
      $hint = '';
107    }
108  }
109
110  return {
111
3
19
    patterns => \@patterns,
112    hints => \%hints,
113  };
114}
115
116sub file_to_list {
117
2
1858
  my ($re) = @_;
118
2
5
  my $lists = file_to_lists($re);
119
120
2
2
1
8
  return @{$lists->{'patterns'}};
121}
122
123sub list_to_re {
124
2
3
  my (@list) = @_;
125
2
5
5
1
4
5
  @list = map { my $quoted = quote_re($_); test_re($quoted) ? $quoted : '' } @list;
126
2
5
2
5
  @list = grep { $_ ne '' } @list;
127
2
3
  return '$^' unless scalar @list;
128
2
6
  return join "|", (@list);
129}
130
131sub not_empty {
132
73
60
  my ($thing) = @_;
133
73
366
  return defined $thing && $thing ne '' && $thing =~ /^\d+$/;
134}
135
136sub valid_word {
137  # shortest_word is an absolute
138
22
12
  our ($shortest, $longest, $shortest_word, $longest_word);
139
22
27
  $shortest = $shortest_word if $shortest_word;
140
22
20
  if ($longest_word) {
141    # longest_word is an absolute
142
20
25
    $longest = $longest_word;
143  } elsif (not_empty($longest)) {
144    # we allow for some sloppiness (a couple of stuck keys per word)
145    # it's possible that this should scale with word length
146
1
1
    $longest += 2;
147  }
148
22
16
  our ($upper_pattern, $lower_pattern, $punctuation_pattern);
149
22
66
17
147
  my $word_pattern = join '|', (grep { defined $_ && /./ } ($upper_pattern, $lower_pattern, $punctuation_pattern));
150
22
44
  $word_pattern = q<\\w|'> unless $word_pattern;
151
22
52
  if ((defined $shortest && not_empty($longest)) &&
152      ($shortest > $longest)) {
153
0
0
    $word_pattern = "(?:$word_pattern){3}";
154
0
0
    return qr/$word_pattern/;
155  }
156
22
29
  $shortest = 3 unless defined $shortest;
157
22
18
  $longest = '' unless not_empty($longest);
158
22
76
  $word_match = "(?:$word_pattern){$shortest,$longest}";
159
22
204
  return qr/\b$word_match\b/;
160}
161
162sub load_dictionary {
163
12
2028
  my ($dict) = @_;
164
12
5
  our ($word_match, $longest, $shortest, $longest_word, $shortest_word, %dictionary);
165
12
15
  $longest_word = CheckSpelling::Util::get_val_from_env('INPUT_LONGEST_WORD', undef);
166
12
12
  $shortest_word = CheckSpelling::Util::get_val_from_env('INPUT_SHORTEST_WORD', undef);
167
12
7
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
168
12
14
  $ignore_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_IGNORE_PATTERN', q<[^a-zA-Z']>);
169
12
46
  $upper_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_UPPER_PATTERN', '[A-Z]');
170
12
58
  $lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_LOWER_PATTERN', '[a-z]');
171
12
26
  $not_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_LOWER_PATTERN', '[^a-z]');
172
12
25
  $not_upper_or_lower_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_NOT_UPPER_OR_LOWER_PATTERN', '[^A-Za-z]');
173
12
31
  $punctuation_pattern = CheckSpelling::Util::get_file_from_env_utf8('INPUT_PUNCTUATION_PATTERN', q<'>);
174
12
28
  %dictionary = ();
175
176
12
1345
  open(DICT, '<:utf8', $dict);
177
12
52
  while (!eof(DICT)) {
178
31
35
    my $word = <DICT>;
179
31
25
    chomp $word;
180
31
79
    next unless $word =~ $word_match;
181
28
33
    my $l = length $word;
182
28
18
    $longest = -1 unless not_empty($longest);
183
28
32
    $longest = $l if $l > $longest;
184
28
36
    $shortest = $l if $l < $shortest;
185
28
57
    $dictionary{$word}=1;
186  }
187
12
27
  close DICT;
188
189
12
10
  $word_match = valid_word();
190}
191
192sub hunspell_dictionary {
193
3
7
  my ($dict) = @_;
194
3
3
  my $name = $dict;
195
3
5
  $name =~ s{/src/index/hunspell/index\.dic$}{};
196
3
13
  $name =~ s{.*/}{};
197
3
7
  my $aff = $dict;
198
3
3
  my $encoding;
199
3
12
  $aff =~ s/\.dic$/.aff/;
200
3
28
  if (open AFF, '<', $aff) {
201
3
19
    while (<AFF>) {
202
0
0
      next unless /^SET\s+(\S+)/;
203
0
0
      $encoding = $1 if ($1 !~ /utf-8/i);
204
0
0
      last;
205    }
206
3
9
    close AFF;
207  }
208  return {
209
3
315
    name => $name,
210    dict => $dict,
211    aff => $aff,
212    encoding => $encoding,
213    engine => Text::Hunspell->new($aff, $dict),
214  }
215}
216
217sub init {
218
9
11797
  my ($configuration) = @_;
219
9
11
  our ($word_match, %unique, $patterns_re, @forbidden_re_list, $forbidden_re, @candidates_re_list, $candidates_re);
220
9
22
  our $sandbox = CheckSpelling::Util::get_file_from_env('sandbox', '');
221
9
10
  our $hunspell_dictionary_path = CheckSpelling::Util::get_file_from_env('hunspell_dictionary_path', '');
222
9
20
  our $timeout = CheckSpelling::Util::get_val_from_env('splitter_timeout', 30);
223
9
6
  our %forbidden_re_descriptions;
224
9
11
  if ($hunspell_dictionary_path) {
225
3
36
    our @hunspell_dictionaries = ();
226
1
1
1
1
1
1
1
1
1
3
202
1075
21
6
2
12
9
3
18
164
    if (eval 'use Text::Hunspell; 1') {
227
3
119
      my @hunspell_dictionaries_list = glob("$hunspell_dictionary_path/*.dic");
228
3
10
      for my $hunspell_dictionary_file (@hunspell_dictionaries_list) {
229
3
12
        push @hunspell_dictionaries, hunspell_dictionary($hunspell_dictionary_file);
230      }
231    } else {
232
0
0
      print STDERR "Could not load Text::Hunspell for dictionaries (hunspell-unavailable)\n";
233    }
234  }
235
9
16
  my (@patterns_re_list, %in_patterns_re_list);
236
9
61
  if (-e "$configuration/patterns.txt") {
237
0
0
    @patterns_re_list = file_to_list "$configuration/patterns.txt";
238
0
0
    $patterns_re = list_to_re @patterns_re_list;
239
0
0
0
0
    %in_patterns_re_list = map {$_ => 1} @patterns_re_list;
240  } else {
241
9
10
    $patterns_re = undef;
242  }
243
244
9
37
  if (-e "$configuration/forbidden.txt") {
245
1
3
    my $forbidden_re_info = file_to_lists "$configuration/forbidden.txt";
246
1
1
1
2
    @forbidden_re_list = @{$forbidden_re_info->{'patterns'}};
247
1
1
1
2
    %forbidden_re_descriptions = %{$forbidden_re_info->{'hints'}};
248
1
2
    $forbidden_re = list_to_re @forbidden_re_list;
249  } else {
250
8
9
    $forbidden_re = undef;
251  }
252
253
9
42
  if (-e "$configuration/candidates.txt") {
254
1
3
    @candidates_re_list = file_to_list "$configuration/candidates.txt";
255
1
2
2
1
2
4
    @candidates_re_list = map { my $quoted = quote_re($_); $in_patterns_re_list{$_} || !test_re($quoted) ? '' : $quoted } @candidates_re_list;
256
1
1
    $candidates_re = list_to_re @candidates_re_list;
257  } else {
258
8
7
    $candidates_re = undef;
259  }
260
261
9
18
  our $largest_file = CheckSpelling::Util::get_val_from_env('INPUT_LARGEST_FILE', 1024*1024);
262
263
9
10
  my $disable_flags = CheckSpelling::Util::get_file_from_env('INPUT_DISABLE_CHECKS', '');
264
9
14
  our $disable_word_collating = $disable_flags =~ /(?:^|,|\s)word-collating(?:,|\s|$)/;
265
9
13
  our $disable_minified_file = $disable_flags =~ /(?:^|,|\s)minified-file(?:,|\s|$)/;
266
9
5
  our $disable_single_line_file = $disable_flags =~ /(?:^|,|\s)single-line-file(?:,|\s|$)/;
267
268
9
8
  our $ignore_next_line_pattern = CheckSpelling::Util::get_file_from_env('INPUT_IGNORE_NEXT_LINE', '');
269
9
7
  $ignore_next_line_pattern =~ s/\s+/|/g;
270
271
9
7
  our $check_images = CheckSpelling::Util::get_val_from_env('INPUT_CHECK_IMAGES', '');
272
9
10
  $check_images = $check_images =~ /^(?:1|true)$/i;
273
274
9
9
  our $check_file_names = CheckSpelling::Util::get_file_from_env('check_file_names', '');
275
276
9
9
  our $use_magic_file = CheckSpelling::Util::get_val_from_env('INPUT_USE_MAGIC_FILE', '');
277
278
9
10
  $word_match = valid_word();
279
280
9
21
  our $base_dict = CheckSpelling::Util::get_file_from_env('dict', "$configuration/words");
281
9
47
  $base_dict = '/usr/share/dict/words' unless -e $base_dict;
282
9
11
  load_dictionary($base_dict);
283}
284
285sub split_line {
286
1156
495
  our (%dictionary, $word_match, $disable_word_collating);
287
1156
477
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
288
1156
512
  our @hunspell_dictionaries;
289
1156
572
  our $shortest;
290
1156
755
  my $shortest_threshold = $shortest + 2;
291
1156
642
  my $pattern = '.';
292  # $pattern = "(?:$upper_pattern){$shortest,}|$upper_pattern(?:$lower_pattern){2,}\n";
293
294  # https://www.fileformat.info/info/unicode/char/2019/
295
1156
547
  my $rsqm = "\xE2\x80\x99";
296
297
1156
696
  my ($words, $unrecognized) = (0, 0);
298
1156
799
  my ($line, $unique_ref, $unique_unrecognized_ref, $unrecognized_line_items_ref) = @_;
299
1156
5343
    $line =~ s/(?:$rsqm|&apos;|&#39;|\%27|&#8217;|&#x2019;|&rsquo;|\\u2019|\x{2019}|')+/'/g;
300
1156
2162
    $line =~ s/(?:$ignore_pattern)+/ /g;
301
1156
1681
    while ($line =~ s/($upper_pattern{2,})($upper_pattern$lower_pattern{2,})/ $1 $2 /g) {}
302
1156
3268
    while ($line =~ s/((?:$lower_pattern|$punctuation_pattern)+)($upper_pattern)/$1 $2/g) {}
303
1156
1284
    for my $token (split /\s+/, $line) {
304
3619
3303
      next unless $token =~ /$pattern/;
305
2464
1991
      $token =~ s/^(?:'|$rsqm)+//g;
306
2464
2412
      $token =~ s/(?:'|$rsqm)+s?$//g;
307
2464
1417
      my $raw_token = $token;
308
2464
1467
      $token =~ s/^[^Ii]?'+(.*)/$1/;
309
2464
1298
      $token =~ s/(.*?)'+$/$1/;
310
2464
3621
      next unless $token =~ $word_match;
311
2311
2153
      if (defined $dictionary{$token}) {
312
1032
486
        ++$words;
313
1032
541
        $unique_ref->{$token}=1;
314
1032
839
        next;
315      }
316
1279
975
      if (@hunspell_dictionaries) {
317
1254
607
        my $found = 0;
318
1254
788
        for my $hunspell_dictionary (@hunspell_dictionaries) {
319          my $token_encoded = defined $hunspell_dictionary->{'encoding'} ?
320
1254
1164
            encode($hunspell_dictionary->{'encoding'}, $token) : $token;
321
1254
2906
          next unless ($hunspell_dictionary->{'engine'}->check($token_encoded));
322
0
0
          ++$words;
323
0
0
          $dictionary{$token} = 1;
324
0
0
          $unique_ref->{$token}=1;
325
0
0
          $found = 1;
326
0
0
          last;
327        }
328
1254
965
        next if $found;
329      }
330
1279
952
      my $key = lc $token;
331
1279
1113
      if (defined $dictionary{$key}) {
332
6
6
        ++$words;
333
6
4
        $unique_ref->{$key}=1;
334
6
6
        next;
335      }
336
1273
841
      unless ($disable_word_collating) {
337
1273
812
        $key =~ s/''+/'/g;
338
1273
1322
        $key =~ s/'[sd]$// unless length $key >= $shortest_threshold;
339      }
340
1273
1146
      if (defined $dictionary{$key}) {
341
0
0
        ++$words;
342
0
0
        $unique_ref->{$key}=1;
343
0
0
        next;
344      }
345
1273
627
      ++$unrecognized;
346
1273
810
      $unique_unrecognized_ref->{$raw_token}=1;
347
1273
1716
      $unrecognized_line_items_ref->{$raw_token}=1;
348    }
349
1156
1655
    return ($words, $unrecognized);
350}
351
352sub skip_file {
353
7
25
  my ($temp_dir, $reason) = @_;
354
7
235
  open(SKIPPED, '>:utf8', "$temp_dir/skipped");
355
7
36
  print SKIPPED $reason;
356
7
120
  close SKIPPED;
357}
358
359sub maybe_ocr_file {
360
0
0
  my ($file) = @_;
361
0
0
  my $tesseract = dirname(dirname(dirname(__FILE__)))."/wrappers/run-tesseract";
362
0
0
  $ENV{'input'} = $file;
363
0
0
  my $text_file = `"$tesseract"`;
364
0
0
  delete $ENV{'input'};
365
0
0
  return ($file, 0) unless defined $text_file;
366
0
0
  my $file_converted = 0;
367
0
0
  chomp $text_file;
368
0
0
  if ($text_file =~ /^(.*)$/) {
369
0
0
    $text_file = $1;
370
0
0
    my $file_size = -s $text_file || 0;
371
0
0
    if ($file_size > 20) {
372
0
0
      $file_converted = 1;
373
0
0
      $file = $text_file;
374    } else {
375
0
0
      unlink($text_file);
376    }
377  }
378
0
0
  return ($file, $file_converted);
379}
380
381sub split_file {
382
16
12546
  my ($file) = @_;
383  our (
384
16
11
    $unrecognized, $shortest, $largest_file, $words,
385    $word_match, %unique, %unique_unrecognized, $forbidden_re,
386    @forbidden_re_list, $patterns_re, %dictionary,
387    $candidates_re, @candidates_re_list, $check_file_names, $use_magic_file, $disable_minified_file,
388    $disable_single_line_file,
389    $ignore_next_line_pattern,
390    $sandbox,
391    $check_images,
392  );
393
16
39
  $ignore_next_line_pattern = '$^' unless $ignore_next_line_pattern =~ /./;
394
395
16
9
  our %forbidden_re_descriptions;
396
16
13
  our ($ignore_pattern, $upper_pattern, $lower_pattern, $not_lower_pattern, $not_upper_or_lower_pattern, $punctuation_pattern);
397
398  # https://www.fileformat.info/info/unicode/char/2019/
399
16
9
  my $rsqm = "\xE2\x80\x99";
400
401
16
20
  my @candidates_re_hits = (0) x scalar @candidates_re_list;
402
16
12
  my @candidates_re_lines = (0) x scalar @candidates_re_list;
403
16
16
  my @forbidden_re_hits = (0) x scalar @forbidden_re_list;
404
16
19
  my @forbidden_re_lines = (0) x scalar @forbidden_re_list;
405
16
42
  my $temp_dir = tempdir(DIR=>$sandbox);
406
16
2661
  print STDERR "checking file: $file\n" if defined $ENV{'DEBUG'};
407
16
376
  open(NAME, '>', "$temp_dir/name");
408
16
37
    print NAME $file;
409
16
210
  close NAME;
410
16
179
  if (defined readlink($file) &&
411      rindex(File::Spec->abs2rel(abs_path($file)), '../', 0) == 0) {
412
1
4
    skip_file($temp_dir, "file only has a single line (out-of-bounds-symbolic-link)\n");
413
1
4
    return $temp_dir;
414  }
415
15
29
  if ($use_magic_file) {
416
8
13169
    if (open(my $file_fh, '-|',
417              '/usr/bin/file',
418              '-b',
419              '--mime',
420              '-e', 'cdf',
421              '-e', 'compress',
422              '-e', 'csv',
423              '-e', 'elf',
424              '-e', 'json',
425              '-e', 'tar',
426              $file)) {
427
8
29999
      my $file_kind = <$file_fh>;
428
8
5039
      close $file_fh;
429
8
12
      my $file_converted = 0;
430
8
35
      if ($check_images && $file_kind =~ m<^image/(?!svg)>) {
431
0
0
        ($file, $file_converted) = maybe_ocr_file($file);
432      }
433
8
208
      if ($file_converted == 0 && $file_kind =~ /^(.*?); charset=binary/) {
434
2
29
        skip_file($temp_dir, "it appears to be a binary file (`$1`) (binary-file)\n");
435
2
41
        return $temp_dir;
436      }
437    }
438  } elsif ($file =~ /\.(?:png|jpe?g|gif)$/) {
439
0
0
    my $file_converted = 0;
440
0
0
    ($file, $file_converted) = maybe_ocr_file($file);
441  }
442
13
84
  my $file_size = -s $file;
443
13
21
  if (defined $largest_file) {
444
13
16
    unless ($check_file_names eq $file) {
445
13
13
      if ($file_size > $largest_file) {
446
1
3
        skip_file($temp_dir, "size `$file_size` exceeds limit `$largest_file` (large-file)\n");
447
1
3
        return $temp_dir;
448      }
449    }
450  }
451
12
97
  open FILE, '<', $file;
452
12
13
  binmode FILE;
453
12
11
  my $head;
454
12
107
  read(FILE, $head, 4096);
455
12
890
  $head =~ s/(?:\r|\n)+$//;
456
12
58
  my $dos_new_lines = () = $head =~ /\r\n/gi;
457
12
39
  my $unix_new_lines = () = $head =~ /\n/gi;
458
12
113
  my $mac_new_lines = () = $head =~ /\r/gi;
459
12
57
  local $/;
460
12
82
  if ($unix_new_lines == 0 && $mac_new_lines == 0) {
461
3
8
    $/ = "\n";
462  } elsif ($dos_new_lines >= $unix_new_lines && $dos_new_lines >= $mac_new_lines) {
463
1
7
    $/ = "\r\n";
464  } elsif ($mac_new_lines > $unix_new_lines) {
465
2
5
    $/ = "\r";
466  } else {
467
6
7
    $/ = "\n";
468  }
469
12
25
  seek(FILE, 0, 0);
470
12
18
  ($words, $unrecognized) = (0, 0);
471
12
65
  %unique = ();
472
12
35
  %unique_unrecognized = ();
473
474  local $SIG{__WARN__} = sub {
475
0
0
    my $message = shift;
476
0
0
    $message =~ s/> line/> in $file - line/;
477
0
0
    chomp $message;
478
0
0
    print STDERR "$message\n";
479
12
123
  };
480
481
12
354
  open(WARNINGS, '>:utf8', "$temp_dir/warnings");
482
12
13
  our $timeout;
483
12
19
  eval {
484
12
0
104
0
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
485
12
41
    alarm $timeout;
486
487
12
24
    my $ignore_next_line = 0;
488
12
14
    my $offset = 0;
489
12
82
    while (<FILE>) {
490
1159
1035
      if ($. == 1) {
491
12
22
        unless ($disable_minified_file) {
492
12
62
          if ($file_size >= 512 && length($_) == $file_size) {
493
1
13
            skip_file($temp_dir, "file only has a single line (single-line-file)\n");
494
1
5
            last;
495          }
496        }
497      }
498
1158
2409
      $_ = decode_utf8($_, FB_DEFAULT);
499
1158
2718
      if (/[\x{D800}-\x{DFFF}]/) {
500
0
0
        skip_file($temp_dir, "file contains a UTF-16 surrogate -- UTF-16 surrogates are not supported (utf16-surrogate-file)\n");
501
0
0
        last;
502      }
503
1158
1420
      s/\R$//;
504
1158
1104
      s/^\x{FEFF}// if $. == 1;
505
1158
1161
      next unless /./;
506
1157
805
      my $raw_line = $_;
507
508
1157
603
      my $ignore_this_line = $ignore_next_line;
509
1157
1035
      $ignore_next_line = ($_ =~ /$ignore_next_line_pattern/);
510
1157
823
      next if $ignore_this_line;
511
512      # hook for custom line based text exclusions:
513
1156
774
      if (defined $patterns_re) {
514
2
6
11
8
        s/($patterns_re)/"="x length($1)/ge;
515      }
516
1156
645
      my $initial_line_state = $_;
517
1156
707
      my $previous_line_state = $_;
518
1156
553
      my $line_flagged;
519
1156
803
      if ($forbidden_re) {
520
9
5
60
11
        while (s/($forbidden_re)/"="x length($1)/e) {
521
5
3
          $line_flagged = 1;
522
5
10
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
523
5
4
          my $found_trigger_re;
524
5
7
          for my $i (0 .. $#forbidden_re_list) {
525
7
5
            my $forbidden_re_singleton = $forbidden_re_list[$i];
526
7
6
            my $test_line = $previous_line_state;
527
7
4
58
6
            if ($test_line =~ s/($forbidden_re_singleton)/"="x length($1)/e) {
528
4
5
              next unless $test_line eq $_;
529
4
8
              my ($begin_test, $end_test, $match_test) = ($-[0] + 1, $+[0] + 1, $1);
530
4
5
              next unless $begin == $begin_test;
531
4
3
              next unless $end == $end_test;
532
4
2
              next unless $match eq $match_test;
533
4
4
              $found_trigger_re = $forbidden_re_singleton;
534
4
8
              my $hit = "$.:$begin:$end";
535
4
3
              $forbidden_re_hits[$i]++;
536
4
6
              $forbidden_re_lines[$i] = $hit unless $forbidden_re_lines[$i];
537
4
6
              last;
538            }
539          }
540
5
7
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
541
5
19
          if ($found_trigger_re) {
542
4
11
            my $description = $forbidden_re_descriptions{$found_trigger_re} || '';
543
4
11
            $found_trigger_re =~ s/^\(\?:(.*)\)$/$1/;
544
4
2
            my $quoted_trigger_re = CheckSpelling::Util::truncate_with_ellipsis(CheckSpelling::Util::wrap_in_backticks($found_trigger_re), 99);
545
4
5
            if ($description ne '') {
546
3
14
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns rule: $description - $quoted_trigger_re (forbidden-pattern)\n";
547            } else {
548
1
6
              print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry: $quoted_trigger_re (forbidden-pattern)\n";
549            }
550          } else {
551
1
4
            print WARNINGS ":$.:$begin ... $end, Warning - $wrapped matches a line_forbidden.patterns entry (forbidden-pattern)\n";
552          }
553
5
25
          $previous_line_state = $_;
554        }
555
9
10
        $_ = $initial_line_state;
556      }
557      # This is to make it easier to deal w/ rules:
558
1156
1102
      s/^/ /;
559
1156
726
      my %unrecognized_line_items = ();
560
1156
968
      my ($new_words, $new_unrecognized) = split_line($_, \%unique, \%unique_unrecognized, \%unrecognized_line_items);
561
1156
663
      $words += $new_words;
562
1156
600
      $unrecognized += $new_unrecognized;
563
1156
778
      my $line_length = length($raw_line);
564
1156
1474
      for my $token (sort CheckSpelling::Util::case_biased keys %unrecognized_line_items) {
565
1020
537
        my $found_token = 0;
566
1020
455
        my $raw_token = $token;
567
1020
592
        $token =~ s/'/(?:'|\x{2019}|\&apos;|\&#39;)+/g;
568
1020
393
        my $before;
569
1020
1640
        if ($token =~ /^$upper_pattern$lower_pattern/) {
570
5
5
          $before = '(?<=.)';
571        } elsif ($token =~ /^$upper_pattern/) {
572
0
0
          $before = "(?<!$upper_pattern)";
573        } else {
574
1015
561
          $before = "(?<=$not_lower_pattern)";
575        }
576
1020
1125
        my $after = ($token =~ /$upper_pattern$/) ? "(?=$not_upper_or_lower_pattern)|(?=$upper_pattern$lower_pattern)" : "(?=$not_lower_pattern)";
577
1020
2179
        while ($raw_line =~ /(?:\b|$before)($token)(?:\b|$after)/g) {
578
1270
644
          $line_flagged = 1;
579
1270
562
          $found_token = 1;
580
1270
1699
          my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
581
1270
1216
          next unless $match =~ /./;
582
1270
1012
          my $wrapped = CheckSpelling::Util::wrap_in_backticks($match);
583
1270
4847
          print WARNINGS ":$.:$begin ... $end: $wrapped\n";
584        }
585
1020
1170
        unless ($found_token) {
586
3
27
          if ($raw_line !~ /$token.*$token/ && $raw_line =~ /($token)/) {
587
3
6
            my ($begin, $end, $match) = ($-[0] + 1, $+[0] + 1, $1);
588
3
3
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
589
3
12
            print WARNINGS ":$.:$begin ... $end: $wrapped\n";
590          } else {
591
0
0
            my $offset = $line_length + 1;
592
0
0
            my $wrapped = CheckSpelling::Util::wrap_in_backticks($raw_token);
593
0
0
            print WARNINGS ":$.:1 ... $offset, Warning - Could not identify whole word $wrapped in line (token-is-substring)\n";
594          }
595        }
596      }
597
1156
1939
      if ($line_flagged && $candidates_re) {
598
1
1
        $_ = $previous_line_state = $initial_line_state;
599
1
1
19
2
        s/($candidates_re)/"="x length($1)/ge;
600
1
2
        if ($_ ne $initial_line_state) {
601
1
2
          $_ = $previous_line_state;
602
1
1
          for my $i (0 .. $#candidates_re_list) {
603
2
3
            my $candidate_re = $candidates_re_list[$i];
604
2
16
            next unless $candidate_re =~ /./ && $raw_line =~ /$candidate_re/;
605
1
1
6
3
            if (($_ =~ s/($candidate_re)/"="x length($1)/e)) {
606
1
2
              my ($begin, $end) = ($-[0] + 1, $+[0] + 1);
607
1
3
              my $hit = "$.:$begin:$end";
608
1
1
              $_ = $previous_line_state;
609
1
1
6
2
              my $replacements = ($_ =~ s/($candidate_re)/"="x length($1)/ge);
610
1
3
              $candidates_re_hits[$i] += $replacements;
611
1
2
              $candidates_re_lines[$i] = $hit unless $candidates_re_lines[$i];
612
1
2
              $_ = $previous_line_state;
613            }
614          }
615        }
616      }
617
1156
907
      unless ($disable_minified_file) {
618
1156
921
        s/={3,}//g;
619
1156
779
        $offset += length;
620
1156
1091
        my $ratio = int($offset / $.);
621
1156
585
        my $ratio_threshold = 1000;
622
1156
3053
        if ($ratio > $ratio_threshold) {
623
2
7
          skip_file($temp_dir, "average line width ($ratio) exceeds the threshold ($ratio_threshold) (minified-file)\n");
624
2
7
          last;
625        }
626      }
627    }
628
629
12
81
    alarm 0;
630  };
631
12
14
  if ($@) {
632
0
0
    die unless $@ eq "alarm\n";
633
0
0
    print WARNINGS ":$.:1 ... 1, Warning - Could not parse file within time limit (slow-file)\n";
634
0
0
    skip_file($temp_dir, "it could not be parsed file within time limit (slow-file)\n");
635
0
0
    return $temp_dir;
636  }
637
638
12
44
  close FILE;
639
12
153
  close WARNINGS;
640
641
12
34
  if ($unrecognized || @candidates_re_hits || @forbidden_re_hits) {
642
11
312
    open(STATS, '>:utf8', "$temp_dir/stats");
643
11
180
      print STATS "{words: $words, unrecognized: $unrecognized, unknown: ".(keys %unique_unrecognized).
644      ", unique: ".(keys %unique).
645      (@candidates_re_hits ? ", candidates: [".(join ',', @candidates_re_hits)."]" : "").
646      (@candidates_re_lines ? ", candidate_lines: [".(join ',', @candidates_re_lines)."]" : "").
647      (@forbidden_re_hits ? ", forbidden: [".(join ',', @forbidden_re_hits)."]" : "").
648      (@forbidden_re_lines ? ", forbidden_lines: [".(join ',', @forbidden_re_lines)."]" : "").
649      "}";
650
11
179
    close STATS;
651
11
253
    open(UNKNOWN, '>:utf8', "$temp_dir/unknown");
652
11
19
56
34
      print UNKNOWN map { "$_\n" } sort CheckSpelling::Util::case_biased keys %unique_unrecognized;
653
11
113
    close UNKNOWN;
654  }
655
656
12
125
  return $temp_dir;
657}
658
659sub main {
660
2
404
  my ($configuration, @ARGV) = @_;
661
2
2
  our %dictionary;
662
2
2
  unless (%dictionary) {
663
1
1
    init($configuration);
664  }
665
666  # read all input
667
2
3
  my @reports;
668
669
2
3
  for my $file (@ARGV) {
670
2
3
    my $temp_dir = split_file($file);
671
2
4
    push @reports, "$temp_dir\n";
672  }
673
2
27
  print join '', @reports;
674}
675
6761;