File Coverage

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

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