File Coverage

File:lib/CheckSpelling/Apply.pm
Coverage:46.8%

linestmtbrancondsubtimecode
1package CheckSpelling::Apply;
2sub tear_here {
3
8
20
  my ($exit) = @_;
4
8
18
  our $exited;
5
8
44
  return if defined $exited;
6
6
51
  print STDERR "\n<<<TEAR HERE<<<exit: $exit\n";
7
6
33
  print STDOUT "\n<<<TEAR HERE<<<exit: $exit\n";
8
6
25
  $exited = $exit;
9}
10sub die_custom {
11
4
15
  my ($line, $message) = @_;
12
4
3
  our $program;
13
4
43
  print STDERR "$message at $program line $line.\n";
14
4
12
  tear_here(1);
15}
16#!/usr/bin/env perl
17":" || q@<<"=END_OF_PERL"@;
18
19
1
1
1
318781
1
30
use Symbol 'gensym';
20
1
1
1
152
1174
25
use IPC::Open3;
21
1
1
1
4
0
22
use File::Basename qw(dirname);
22
1
1
1
2
0
16
use File::Path qw(make_path);
23
1
1
1
157
303
29
use File::Spec::Functions qw(catfile path);
24
1
1
1
2
1
16
use File::Temp qw/ tempfile tempdir /;
25
1
1
1
1
1
23
use JSON::PP;
26
1
1
1
2
0
2517
use warnings;
27
28my @safe_path = qw(
29    /opt/homebrew/bin
30    /opt/homebrew/sbin
31    /usr/local/bin
32    /usr/bin
33    /bin
34    /usr/sbin
35    /sbin
36);
37
38my $bin = glob("~/bin");
39push @safe_path, $bin if -d $bin;
40
41my $ua = 'check-spelling-agent/0.0.4';
42
43$ENV{'PATH'} = join ':', @safe_path unless defined $ENV{SYSTEMROOT};
44
45sub check_exists_command {
46
6
7
    my ($program) = @_;
47
48
6
9
    my @path = path;
49
6
49
    my @pathext = ('');
50
51
6
10
    if ($^O eq 'MSWin32') {
52
0
0
0
0
        push @pathext, map { lc } split /;/, $ENV{PATHEXT};
53    }
54
55
6
6
    for my $dir (@path) {
56
27
11
        for my $suffix (@pathext) {
57
27
35
            my $f = catfile $dir, "$program$suffix";
58
27
124
            return $f if -x $f;
59        }
60    }
61}
62
63sub needs_command_because {
64
5
2037
    my ($program, $reason) = @_;
65
5
3
    return if check_exists_command($program);
66
1
5
    die_custom 51, 'Please install `'.$program.'` - it is needed to '.$reason;
67}
68
69sub check_basic_tools {
70
1
1383
    needs_command_because('git', 'interact with git repositories');
71
1
1
    needs_command_because('curl', 'download other tools');
72
1
10
    $ENV{GH_NO_UPDATE_NOTIFIER}=1;
73
1
3
    $ENV{GH_NO_EXTENSION_UPDATE_NOTIFIER}=1;
74
1
2
    needs_command_because('gh', 'interact with github');
75}
76
77sub get_token {
78
4
3
    our $token;
79
4
18
    return $token if defined $token && $token ne '';
80
1
3
    $token = $ENV{'GH_TOKEN'} || $ENV{'GITHUB_TOKEN'};
81
1
7
    return $token if defined $token && $token ne '';
82
0
0
    $token = `gh auth token`;
83
0
0
    chomp $token;
84
0
0
    return $token;
85};
86
87sub download_with_curl {
88
1
2
    my ($url, $dest, $flags) = @_;
89
1
2
    $flags = '-fsL' unless defined $flags;
90
1
48578
    system('curl',
91        '--connect-timeout', 3,
92        '-A', $ua,
93        $flags,
94        '-o', $dest,
95        $url
96    );
97}
98
99sub tempfile_name {
100
6
27
    my ($fh, $filename) = tempfile();
101
6
1183
    close $fh;
102
6
14
    return $filename;
103}
104
105sub strip_comments {
106
4
4
    my ($file) = @_;
107
4
23
    my ($fh, $filename) = tempfile();
108
4
723
    open INPUT, '<', $file;
109
4
53
    while (<INPUT>) {
110
1845
1027
        next if /^\s*(?:#.*)/;
111
1819
1244
        print $fh $_;
112    }
113
4
13
    close INPUT;
114
4
52
    close $fh;
115
4
11
    return $filename;
116}
117
118sub capture_system {
119
21
65
    my @args = @_;
120
21
108
    my $pid = open3(my $child_in, my $child_out, my $child_err = gensym, @args);
121
21
54023
    my (@err, @out);
122
21
2683929
    while (my $output = <$child_out>) {
123
3
1692
        push @out, $output;
124    }
125
21
518
    while (my $error = <$child_err>) {
126
24
105
        push @err, $error;
127    }
128
21
362
    waitpid( $pid, 0 );
129
21
127
    my $child_exit_status = $?;
130
21
73
    my $output_joined = join '', @out;
131
21
50
    my $error_joined = join '', @err;
132
21
697
    return ($output_joined, $error_joined, $child_exit_status);
133}
134
135sub capture_merged_system {
136
14
31
    my ($output_joined, $error_joined, $child_exit_status) = capture_system(@_);
137
14
60
    my $joiner = ($output_joined ne '') ? "\n" : '';
138
14
81
    return ($output_joined.$joiner.$error_joined, $child_exit_status);
139}
140
141sub compare_files {
142
2
953
    my ($one, $two) = @_;
143
2
6
    my $one_stripped = strip_comments($one);
144
2
2
    my $two_stripped = strip_comments($two);
145
2
1
    my $exit_code;
146
2
4
    (undef, undef, $exit_code) = capture_system(
147            'diff',
148            '-qwB',
149            $one_stripped, $two_stripped
150        );
151
2
7
    if ($? == -1) {
152
0
0
        print "could not compare '$one' and '$two': $!\n";
153
0
0
        return 0;
154    }
155
2
3
    if ($? & 127) {
156
0
0
        printf "child died with signal %d, %s core dump\n",
157        ($? & 127),  ($? & 128) ? 'with' : 'without';
158
0
0
        return 0;
159    }
160
2
4
    return 0 if $? == 0;
161
2
11
    return 1;
162}
163
164my $bash_script=q{
165=END_OF_PERL@
166# bash
167set -e
168if [ "$OUTPUT" = "$ERROR" ]; then
169    ("$@" 2>&1) > "$OUTPUT"
170else
171    "$@" > "$OUTPUT" 2> "$ERROR"
172fi
173exit
174};
175
176sub check_current_script {
177
2
121145
    return if defined $ENV{'APPLY_SKIP_UPDATE_CHECK'};
178
1
3
    if ("$0" eq '-') {
179
0
0
        my ($bash_script) = @_;
180
0
0
        my $fh;
181
0
0
        ($fh, $0) = tempfile();
182
0
0
        $bash_script =~ s/^=.*\@$//m;
183
0
0
        print $fh $bash_script;
184
0
0
        close $fh;
185
0
0
        return;
186    }
187
1
5
    my $filename = tempfile_name();
188
1
1
    my $source = 'https://raw.githubusercontent.com/check-spelling/check-spelling/prerelease/apply.pl';
189
1
5
    download_with_curl($source, $filename);
190
1
32
    if ($? == 0) {
191
1
7
        if (compare_files($filename, $0)) {
192
1
16
            print "Current apply script differs from '$source' (locally downloaded to `$filename`). You may wish to upgrade.\n";
193        }
194    }
195}
196
197sub die_with_message {
198
5
5
    our $program;
199
5
7
    my ($gh_err_text) = @_;
200
5
25
    if ($gh_err_text =~ /error connecting to / && $gh_err_text =~ /check your internet connection/) {
201
0
0
        print "$program: Internet access may be limited. Check your connection (this often happens with lousy cable internet service providers where their CG-NAT or whatever strands the modem).\n\n$gh_err_text";
202
0
0
0
0
        tear_here(5); return -1000;
203    }
204
5
21
    if ($gh_err_text =~ /proxyconnect tcp:.*connect: connection refused/) {
205
1
31
        print "$program: Proxy is not accepting connections.\n";
206
1
2
        for my $proxy (qw(http_proxy HTTP_PROXY https_proxy HTTPS_PROXY)) {
207
4
9
            if (defined $ENV{$proxy}) {
208
1
4
                print "  $proxy: '$ENV{$proxy}'\n";
209            }
210        }
211
1
4
        print "\n$gh_err_text";
212
1
1
7
1
        tear_here(6); return -1000;
213    }
214
4
14
    if ($gh_err_text =~ /dial unix .*: connect: .*/) {
215
1
35
        print "$program: Unix http socket is not working.\n";
216
1
32972
        my $gh_http_unix_socket = `gh config get http_unix_socket`;
217
1
30
        print "  http_unix_socket: $gh_http_unix_socket\n";
218
1
5
        print "\n$gh_err_text";
219
1
1
11
5
        tear_here(7); return -1000;
220    }
221}
222
223sub gh_is_happy_internal {
224
7
22
    my ($output, $exit_code) = capture_merged_system(qw(gh api /installation/repositories));
225
7
19
    return ($exit_code, $output) if $exit_code == 0;
226
7
17
    ($output, $exit_code) = capture_merged_system(qw(gh api /user));
227
7
22
    return ($exit_code, $output);
228}
229
230sub gh_is_happy {
231
3
4
    my ($program) = @_;
232
3
7
    my ($gh_auth_status, $gh_status_lines) = gh_is_happy_internal();
233
3
13
    return 1 if $gh_auth_status == 0;
234
3
14
    die_with_message($gh_status_lines);
235
236
3
5
    my @problematic_env_variables;
237
3
9
    for my $variable (qw(GH_TOKEN GITHUB_TOKEN GITHUB_ACTIONS CI)) {
238
12
28
        if (defined $ENV{$variable}) {
239
4
50
            delete $ENV{$variable};
240
4
12
            push @problematic_env_variables, $variable;
241
4
7
            ($gh_auth_status, $gh_status_lines) = gh_is_happy_internal();
242
4
21
            if ($gh_auth_status == 0) {
243
0
0
                print STDERR "$0: gh program did not like these environment variables: ".join(', ', @problematic_env_variables)." -- consider unsetting them.\n";
244
0
0
                return 1;
245            }
246        }
247    }
248
249
3
62
    print $gh_status_lines;
250
3
29
    return 0;
251}
252
253sub tools_are_ready {
254
3
114578
    my ($program) = @_;
255
3
10
    unless (gh_is_happy($program)) {
256
3
12
        $! = 1;
257
3
13
        my $or_gh_token = (defined $ENV{CI} && $ENV{CI}) ? ' or set the GH_TOKEN environment variable' : '';
258
3
17
        die_custom 243, "$program requires a happy gh, please try 'gh auth login'$or_gh_token\n";
259    }
260}
261
262sub run_pipe {
263
1
4
    my @args = @_;
264
1
2
    my ($out, undef, $exit_code) = capture_system(@args);
265
1
7
    return $out;
266}
267
268sub unzip_pipe {
269
0
0
    my ($artifact, $file) = @_;
270
0
0
    return run_pipe(
271        'unzip',
272        '-p', $artifact,
273        $file
274    );
275}
276
277sub retrieve_spell_check_this {
278
0
0
    my ($artifact, $config_ref) = @_;
279
0
0
    my $spell_check_this_config = unzip_pipe($artifact, 'spell_check_this.json');
280
0
0
    return unless $spell_check_this_config =~ /\{.*\}/s;
281
0
0
    my %config;
282
0
0
0
0
0
0
    eval { %config = %{decode_json $spell_check_this_config}; } || die_custom 267, "decode_json failed in retrieve_spell_check_this with '$spell_check_this_config'";
283
0
0
    my ($repo, $branch, $destination, $path) = ($config{url}, $config{branch}, $config{config}, $config{path});
284
0
0
    my $spell_check_this_dir = tempdir();
285
0
0
    my $exit_code;
286
0
0
    (undef, undef, $exit_code) = capture_system(
287            'git', 'clone',
288            '--depth', '1',
289            '--no-tags',
290            $repo,
291            '--branch', $branch,
292            $spell_check_this_dir
293        );
294
0
0
    if ($?) {
295
0
0
        die_custom 280, "git clone $repo#$branch failed";
296    }
297
298
0
0
    make_path($destination);
299
0
0
    system('cp', '-i', '-R', glob("$spell_check_this_dir/$path/*"), $destination);
300
0
0
    system('git', 'add', '-f', $destination);
301}
302
303sub case_biased {
304
0
0
    lc($a)."-".$a cmp lc($b)."-".$b;
305}
306
307sub add_to_excludes {
308
0
0
    my ($artifact, $config_ref) = @_;
309
0
0
0
0
    my %config = %{$config_ref};
310
0
0
    my $excludes = $config{"excludes_file"};
311
0
0
    my $should_exclude_patterns = unzip_pipe($artifact, 'should_exclude.patterns');
312
0
0
    unless ($should_exclude_patterns =~ /\w/) {
313
0
0
        $should_exclude_patterns = unzip_pipe($artifact, 'should_exclude.txt');
314
0
0
        return unless $should_exclude_patterns =~ /\w/;
315
0
0
        $should_exclude_patterns =~ s{^(.*)}{^\\Q$1\\E\$}gm;
316    }
317
0
0
    my $need_to_add_excludes;
318    my %excludes;
319
0
0
    if (-f $excludes) {
320
0
0
        open EXCLUDES, '<', $excludes;
321
0
0
        while (<EXCLUDES>) {
322
0
0
            chomp;
323
0
0
            next unless /./;
324
0
0
            $excludes{$_."\n"} = 1;
325        }
326
0
0
        close EXCLUDES;
327    } else {
328
0
0
        $need_to_add_excludes = 1;
329    }
330
0
0
    for $pattern (split /\n/, $should_exclude_patterns) {
331
0
0
        next unless $pattern =~ /./;
332
0
0
        $excludes{$pattern."\n"} = 1;
333    }
334
0
0
    open EXCLUDES, '>', $excludes;
335
0
0
    print EXCLUDES join "", sort case_biased keys %excludes;
336
0
0
    close EXCLUDES;
337
0
0
    system('git', 'add', '--', $excludes) if $need_to_add_excludes;
338}
339
340sub remove_stale {
341
0
0
    my ($artifact, $config_ref) = @_;
342
0
0
    my @stale = split /\s+/s, unzip_pipe($artifact, 'remove_words.txt');
343
0
0
    return unless @stale;
344
0
0
0
0
    my %config = %{$config_ref};
345
0
0
0
0
    my @expect_files = @{$config{"expect_files"}};
346    @expect_files = grep {
347
0
0
0
0
        print STDERR "Could not find $_\n" unless -f $_;
348
0
0
        -f $_;
349    } @expect_files;
350
0
0
    unless (@expect_files) {
351
0
0
        die_custom 336, "Could not find any of the processed expect files, are you on the wrong branch?";
352    }
353
354
0
0
    my $re = join "|", @stale;
355
0
0
    for my $file (@expect_files) {
356
0
0
        open INPUT, '<', $file;
357
0
0
        my @keep;
358
0
0
        while (<INPUT>) {
359
0
0
            next if /^(?:$re)(?:(?:\r|\n)*$|[# ].*)/;
360
0
0
            push @keep, $_;
361        }
362
0
0
        close INPUT;
363
364
0
0
        open OUTPUT, '>', $file;
365
0
0
        print OUTPUT join '', @keep;
366
0
0
        close OUTPUT;
367    };
368}
369
370sub add_expect {
371
0
0
    my ($artifact, $config_ref) = @_;
372
0
0
    my @add = split /\s+/s, (unzip_pipe($artifact, 'tokens.txt'));
373
0
0
    return unless @add;
374
0
0
0
0
    my %config = %{$config_ref};
375
0
0
    my $new_expect_file = $config{"new_expect_file"};
376
0
0
    my @words;
377
0
0
    make_path (dirname($new_expect_file));
378
0
0
    if (-s $new_expect_file) {
379
0
0
        open FILE, q{<}, $new_expect_file;
380
0
0
        local $/ = undef;
381
0
0
        @words = split /\s+/, <FILE>;
382
0
0
        close FILE;
383    }
384
0
0
    my %items;
385
0
0
    @items{@words} = @words x (1);
386
0
0
    @items{@add} = @add x (1);
387
0
0
    @words = sort case_biased keys %items;
388
0
0
    open FILE, q{>}, $new_expect_file;
389
0
0
    for my $word (@words) {
390
0
0
        print FILE "$word\n" if $word =~ /\S/;
391    };
392
0
0
    close FILE;
393
0
0
    system("git", "add", $new_expect_file);
394}
395
396sub get_artifact_metadata {
397
3
5
    my ($url) = @_;
398
3
6
    my $json_file = tempfile_name();
399
3
2
    my ($curl_stdout, $curl_stderr, $curl_result);
400
3
13
    my @curl_args = (
401        'curl',
402        $url,
403        '-A',
404        $ua,
405        '-s',
406        '--fail-with-body',
407    );
408
3
8
    my $gh_token = get_token();
409
3
7
    push @curl_args, '-u', "token:$gh_token" if defined $gh_token;
410
3
3
    push @curl_args, (
411        '-o',
412        $json_file
413    );
414
3
6
    ($curl_stdout, $curl_stderr, $curl_result) = capture_system(
415        @curl_args
416    );
417
3
16
    unless ($curl_result == 0) {
418
1
8
        if ($curl_stdout eq '') {
419
1
6
            local $/;
420
1
23
            open my $error_fh, '<', $json_file;
421
1
10
            $curl_stdout = <$error_fh>;
422
1
4
            close $error_fh;
423        }
424        return (
425
1
13
            out    => $curl_stdout,
426            err    => $curl_stderr,
427            result => $curl_result,
428        );
429    }
430
2
8
    my $link;
431
2
47
    open my $json_file_fh, '<', $json_file;
432
2
18
    my ($id, $download_url, $count);
433    {
434
2
2
3
10
        local $/;
435
2
23
        my $content = <$json_file_fh>;
436
2
16
        my $json = decode_json $content;
437
2
5485
        my $artifact = $json->{'artifacts'}->[0];
438
2
2
        $id = $artifact->{'id'};
439
2
4
        $download_url = $artifact->{'archive_download_url'};
440
2
8
        $count = $json->{'total_count'};
441    }
442
2
7
    close $json_file_fh;
443
2
10
    if ($count == 0) {
444        return (
445
0
0
            out => '',
446            err => 'no artifact matches any of the names or patterns provided',
447            result => (3 << 8),
448        );
449    }
450    return (
451
2
18
        id       => $id,
452        download => $download_url,
453        count    => $count,
454    );
455}
456
457sub get_latest_artifact_metadata {
458
2
3
    my ($artifact_dir, $repo, $run, $artifact_name) = @_;
459
2
2
    my $page = 1;
460
2
5
    my $url = "$ENV{GITHUB_API_URL}/repos/$repo/actions/runs/$run/artifacts?name=$artifact_name&per_page=1&page=";
461
2
6
    my %first = get_artifact_metadata($url.$page);
462
2
4
    $page = $first{'count'};
463
2
3
    if (defined $page) {
464
1
3
        my %second = get_artifact_metadata($url.$page);
465
1
4
        my ($id_1, $id_2) = ($first{'id'}, $second{'id'});
466
1
22
        if (defined $id_1 && defined $id_2) {
467
1
5
            if ($id_2 > $id_1) {
468                return (
469
0
0
                    download => $second{'download'},
470                );
471            }
472        }
473    }
474
2
3
    my $download = $first{'download'};
475
2
5
    if (defined $download) {
476        return (
477
1
6
            download => $download,
478        );
479    }
480
1
9
    return %first;
481}
482
483sub download_latest_artifact {
484
2
7
    my %maybe_download = get_latest_artifact_metadata(@_);
485
2
4
    my $download = $maybe_download{'download'};
486
2
6
    my $zip_file = tempfile_name();
487
2
3
    if (defined $download) {
488
1
5
        my @curl_args = (
489            'curl',
490            $download,
491            '-L',
492            '-A',
493            $ua,
494            '-s',
495            '--fail-with-body',
496        );
497
1
3
        my $gh_token = get_token();
498
1
3
        push @curl_args, '-u', "token:$gh_token" if defined $gh_token;
499
1
1
        push @curl_args, (
500            '-o',
501            $zip_file
502        );
503
1
2
        ($curl_stdout, $curl_stderr, $curl_result) = capture_system(
504            @curl_args
505        );
506
1
7
        if ($curl_result != 0) {
507
1
4
            if ($curl_stdout eq '') {
508
1
8
                local $/;
509
1
24
                open my $error_fh, '<', $zip_file;
510
1
9
                $curl_stdout = <$error_fh>;
511
1
4
                close $error_fh;
512            }
513
1
11
            return ("$curl_stdout\n$curl_stderr", $curl_result);
514        }
515
0
0
        my ($artifact_dir, $repo, $run, $artifact_name) = @_;
516
0
0
        ($out, $err, $result) = capture_system(
517            'unzip',
518            '-q',
519            $zip_file,
520            '-d',
521            $artifact_dir,
522            );
523
0
0
        return ("$out\n$err", $result);
524    }
525
1
2
    my ($out, $err, $result) = ($maybe_download{'out'}, $maybe_download{'err'}, $maybe_download{'result'});
526
1
5
    return ("$out\n$err", $result);
527}
528
529sub get_artifacts {
530
2
3542
    my ($repo, $run, $suffix) = @_;
531
2
1
    our $program;
532
2
4
    my $artifact_dir = tempdir(CLEANUP => 1);
533
2
329
    my $gh_err_text;
534
2
2
    my $artifact_name = 'check-spelling-comment';
535
2
2
    if ($suffix) {
536
0
0
        $artifact_name .= "-$suffix";
537    }
538
2
2
    my $retries_remaining = 3;
539
2
7
    while ($retries_remaining-- > 0) {
540
2
3
        ($gh_err_text, $ret) = download_latest_artifact(
541            $artifact_dir,
542            $repo,
543            $run,
544            $artifact_name
545        );
546
2
6
        return glob("$artifact_dir/artifact*.zip") unless ($ret >> 8);
547
548
2
15
        die_with_message($gh_err_text);
549
2
16
        if ($gh_err_text =~ /no valid artifacts found to download|"Artifact has expired"/) {
550
1
6
            my $expired_json = run_pipe(
551                'gh', 'api',
552                "/repos/$repo/actions/runs/$run/artifacts",
553                '-q',
554                '.artifacts.[]|select(.name=="'.$artifact_name.'")|.expired'
555            );
556
1
4
            if ($expired_json ne '') {
557
1
2
                chomp $expired_json;
558
1
2
                my $expired;
559
1
1
2
8
                eval { $expired = decode_json $expired_json } || die_custom 544, "decode_json failed in update_repository with '$expired_json'";
560
1
124
                if ($expired) {
561
1
33
                    print "$program: GitHub Run Artifact expired. You will need to trigger a new run.\n";
562
1
1
6
13
                    tear_here(1); return -1000;
563                }
564            }
565
0
0
            print "$program: GitHub Run may not have completed. If so, please wait for it to finish and try again.\n";
566
0
0
0
0
            tear_here(2); return -1000;
567        }
568
1
2
        if ($gh_err_text =~ /no artifact matches any of the names or patterns provided/) {
569
0
0
            $github_server_url = $ENV{GITHUB_SERVER_URL} || '';
570
0
0
            my $run_link;
571
0
0
            if ($github_server_url) {
572
0
0
                $run_link = "[$run]($github_server_url/$repo/actions/runs/$run)";
573            } else {
574
0
0
                $run_link = "$run";
575            }
576
0
0
            print "$program: The referenced repository ($repo) run ($run_link) does not have a corresponding artifact ($artifact_name). If it was deleted, that's unfortunate. Consider pushing a change to the branch to trigger a new run?\n";
577
0
0
            print "If you don't think anyone deleted the artifact, please file a bug to https://github.com/check-spelling/check-spelling/issues/new including as much information about how you triggered this error as possible.\n";
578
0
0
0
0
            tear_here(3); return -1000;
579        }
580
1
6
        if ($gh_err_text =~ /HTTP 404: Not Found|"status":"404"/) {
581
1
16
            print "$program: The referenced repository ($repo) may not exist, perhaps you do not have permission to see it. If the repository is hosted by GitHub Enterprise, check-spelling does not know how to integrate with it.\n";
582
1
1
5
9
            tear_here(8); return -1000;
583        }
584
0
        if ($gh_err_text =~ /HTTP 403: API rate limit exceeded for .*?./) {
585        } elsif ($gh_err_text =~ m{dial tcp \S+:\d+: i/o timeout$}) {
586
0
            if ($retries_remaining <= 0) {
587
0
                print "$program: Timeout connecting to GitHub. This is probably caused by an outage of sorts.\nCheck https://www.githubstatus.com/history\nTry again later.";
588
0
0
                tear_here(9); return -1000;
589            }
590        } else {
591
0
            print "$program: Unknown error, please check the list of known issues https://github.com/check-spelling/check-spelling/issues?q=is%3Aissue%20apply.pl and file a bug to https://github.com/check-spelling/check-spelling/issues/new?title=%60apply.pl%60%20scenario&body=Please%20provide%20details+preferably%20including%20a%20link%20to%20a%20workflow%20run,%20the%20configuration%20of%20the%20repository,%20and%20anything%20else%20you%20may%20know%20about%20the%20problem%2e\n";
592
0
            print $gh_err_text;
593
0
0
            tear_here(4); return -1000;
594        }
595
0
        my $request_id = $1 if ($gh_err_text =~ /\brequest ID\s+(\S+)/);
596
0
        my $timestamp = $1 if ($gh_err_text =~ /\btimestamp\s+(.*? UTC)/);
597
0
        my $has_gh_token = defined $ENV{GH_TOKEN} || defined $ENV{GITHUB_TOKEN};
598
0
        my $meta_url = 'https://api.github.com/meta';
599
0
        while (1) {
600
0
            my @curl_args = qw(curl);
601
0
            unless ($has_gh_token) {
602
0
                my $gh_token = get_token();
603
0
                push @curl_args, '-u', "token:$gh_token" if defined $gh_token;
604            }
605
0
            push @curl_args, '-I', $meta_url;
606
0
            my ($curl_stdout, $curl_stderr, $curl_result);
607
0
            ($curl_stdout, $curl_stderr, $curl_result) = capture_system(@curl_args);
608
0
            my $delay = 1;
609
0
            if ($curl_stdout =~ m{^HTTP/\S+\s+200}) {
610
0
                if ($curl_stdout =~ m{^x-ratelimit-remaining:\s+(\d+)$}m) {
611
0
                    my $ratelimit_remaining = $1;
612
0
                    last if ($ratelimit_remaining > 10);
613
614
0
                    $delay = 5;
615
0
                    print STDERR "Sleeping for $delay seconds because $ratelimit_remaining is close to 0\n";
616                } else {
617
0
                    print STDERR "Couldn't find x-ratelimit-remaining, will sleep for $delay\n";
618                }
619            } elsif ($curl_stdout =~ m{^HTTP/\S+\s+403}) {
620
0
                if ($curl_stdout =~ /^retry-after:\s+(\d+)/m) {
621
0
                    $delay = $1;
622
0
                    print STDERR "Sleeping for $delay seconds (presumably due to API rate limit)\n";
623                } else {
624
0
                    print STDERR "Couldn't find retry-after, will sleep for $delay\n";
625                }
626            } else {
627
0
                my $response = $1 if $curl_stdout =~ m{^(HTTP/\S+)};
628
0
                print STDERR "Unexpected response ($response) from $meta_url; sleeping for $delay\n";
629            }
630
0
            sleep $delay;
631        }
632    }
633}
634
635sub update_repository {
636
0
    my ($artifact) = @_;
637
0
    die_custom 622, if $artifact =~ /'/;
638
0
    our $program;
639
0
    my $apply = unzip_pipe($artifact, 'apply.json');
640
0
    unless ($apply =~ /\{.*\}/s) {
641
0
        print STDERR "$program: Could not retrieve valid apply.json from artifact\n";
642
0
        $apply = '{
643            "expect_files": [".github/actions/spelling/expect.txt"],
644            "new_expect_file": ".github/actions/spelling/expect.txt",
645            "excludes_file": ".github/actions/spelling/excludes.txt",
646            "spelling_config": ".github/actions/spelling"
647        }';
648    }
649
0
    my $config_ref;
650
0
0
    eval { $config_ref = decode_json($apply); } ||
651        die_custom 636, "$program: decode_json failed in update_repository with '$apply'";
652
653
0
    my $git_repo_root = run_pipe('git', 'rev-parse', '--show-toplevel');
654
0
    chomp $git_repo_root;
655
0
    die_custom 640, "$program: Could not find git repo root..." unless $git_repo_root =~ /\w/;
656
0
    chdir $git_repo_root;
657
658
0
    retrieve_spell_check_this($artifact, $config_ref);
659
0
    remove_stale($artifact, $config_ref);
660
0
    add_expect($artifact, $config_ref);
661
0
    add_to_excludes($artifact, $config_ref);
662
0
    system('git', 'add', '-u', '--', $config_ref->{'spelling_config'});
663}
664
665sub extract_artifacts_from_file {
666
0
    my ($artifact) = @_;
667
0
    open my $artifact_reader, '-|', 'unzip', '-l', $artifact;
668
0
    my ($has_artifact, $only_file) = (0, 0);
669
0
    while (my $line = <$artifact_reader>) {
670
0
        chomp $line;
671
0
        if ($line =~ /\s+artifact\.zip$/) {
672
0
            $has_artifact = 1;
673
0
            next;
674        }
675
0
        if ($line =~ /\s+1 file$/) {
676
0
            $only_file = 1;
677
0
            next;
678        }
679
0
        $only_file = 0 if $only_file;
680    }
681
0
    close $artifact_reader;
682
0
    my @artifacts;
683
0
    if ($has_artifact && $only_file) {
684
0
        my $artifact_dir = tempdir(CLEANUP => 1);
685
0
        my ($fh, $gh_err) = tempfile();
686
0
        close $fh;
687
0
        system('unzip', '-q', '-d', $artifact_dir, $artifact, 'artifact.zip');
688
0
        @artifacts = ("$artifact_dir/artifact.zip");
689    } else {
690
0
        @artifacts = ($artifact);
691    }
692
0
    return @artifacts;
693}
694
695sub main {
696
0
    our $program;
697
0
    my ($bash_script, $first, $run);
698
0
    ($program, $bash_script, $first, $run) = @_;
699
0
    my $syntax = "$program <RUN_URL | OWNER/REPO RUN | ARTIFACT.zip>";
700    # Stages
701    # - 1 check for tools basic
702
0
    check_basic_tools();
703    # - 2 check for current
704    # -> 1. download the latest version to a temp file
705    # -> 2. parse current and latest (stripping comments) and compare (whitespace insensitively)
706    # -> 3. offer to update if the latest version is different
707
0
    check_current_script($bash_script);
708    # - 4 parse arguments
709
0
    die_custom 694, $syntax unless defined $first;
710
0
    $ENV{'GITHUB_API_URL'} ||= 'https://api.github.com';
711
0
    my $repo;
712    my @artifacts;
713
0
    if (-s $first) {
714
0
        @artifacts = extract_artifacts_from_file($first);
715    } else {
716
0
        my $suffix;
717
0
        if ($first =~ m{^\s*https://.*/([^/]+/[^/]+)/actions/runs/(\d+)(?:/attempts/\d+|)(?:#(\S+)|)\s*$}) {
718
0
            ($repo, $run, $suffix) = ($1, $2, $3);
719        } else {
720
0
            $repo = $first;
721        }
722
0
        die_custom 707, $syntax unless defined $repo && defined $run;
723        # - 3 check for tool readiness (is `gh` working)
724
0
        tools_are_ready($program);
725
0
        @artifacts = get_artifacts($repo, $run, $suffix);
726    }
727
728    # - 5 do work
729
0
    for my $artifact (@artifacts) {
730
0
        update_repository($artifact);
731    }
732}
733