File Coverage

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

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