File Coverage

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

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