File Coverage

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

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