blib/lib/App/GitHubPullRequest.pm untested

filter: Statementstmt 0.0% 0 / 339 Branchbran 0.0% 0 / 204 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 37 Podpod 0.0% 0 / 29 totaltotal 0.0% 0 / 692 CC 103 SCAR 41.1
CC
103
Cov
0%
checkout
132.0
comment
132.0
_post_url
132.0
CRAP 61.0
1 #!perl
2  
3 use strict;
4 use warnings;
5 use feature qw(say state);
6  
7 package App::GitHubPullRequest;
8 $App::GitHubPullRequest::VERSION = '0.6.0';
9 # ABSTRACT: Command-line tool to query GitHub pull requests
10  
11 use JSON qw(decode_json encode_json);
12 use Carp qw(croak);
13 use Encode qw(encode_utf8);
14 use File::Spec;
15  
16 use constant DEBUG => $ENV{'GIT_PR_DEBUG'} || 0;
17  
18  
19 sub new {
20 my ($class) = @_;
21 return bless {}, $class;
22 }
23  
24  
25 sub run {
26 my ($self, @args) = @_;
27 my $cmd = scalar @args ? shift @args : 'list';
28 my $method = $self->can($cmd);
29 return $self->$method(@args) if $method;
30 return $self->help(@args);
31 }
32  
33  
34 sub help {
35 my ($self, @args) = @_;
36 print <<"EOM";
37 $0 [<command> <args> ...]
38  
39 Where command is one of these:
40  
41 help Show this page
42 list [<state>] Show all pull requests (state: open/closed)
43 show <number> Show details for the specified pull request
44 patch <number> Fetch a properly formatted patch for specified pull request
45 checkout <number> Create tracking branch for specified pull request
46  
47 login [<user>] [<password>] [<two-factor-auth-token>]
48 Login to GitHub and receive an access token (deprecated)
49 authorize Create a GitHub OAuth personal access token
50 comment <number> [<text>] Create a comment on the specified pull request
51 close <number> Close the specified pull request
52 open <number> Reopen the specified pull request
53  
54 EOM
55 return 1;
56 }
57  
58  
59 sub list {
60 my ($self, $state) = @_;
61 $state ||= 'open';
62 my $remote_repo = _find_github_remote();
63 my $prs = _api_read("/repos/$remote_repo/pulls?state=$state");
64 say ucfirst($state) . " pull requests for '$remote_repo':";
65 unless ( @$prs ) {
66 say "No pull requests found.";
67 return 0;
68 }
69 foreach my $pr ( @$prs ) {
70 my $number = $pr->{"number"};
71 my $title = encode_utf8( $pr->{"title"} );
72 my $date = $pr->{"updated_at"} || $pr->{'created_at'};
73 say join(" ", $number, $date, $title);
74 }
75 return 0;
76 }
77  
78  
79 sub show {
80 my ($self, $number, @args) = @_;
81 die("Please specify a pull request number.\n") unless $number;
82 my $pr = $self->_fetch_one($number);
83 die("Unable to fetch pull request $number.\n")
84 unless defined $pr;
85 {
86 my $user = $pr->{'user'}->{'login'};
87 my $title = encode_utf8( $pr->{"title"} );
88 my $body = encode_utf8( $pr->{"body"} );
89 my $date = $pr->{"updated_at"} || $pr->{'created_at'};
90 say "Date: $date";
91 say "From: $user";
92 say "Subject: $title";
93 say "Number: $number";
94 say "\n$body\n" if $body;
95 }
96 my $comments = _api_read( $pr->{'comments_url'} );
97 foreach my $comment (@$comments) {
98 my $user = $comment->{'user'}->{'login'};
99 my $date = $comment->{'updated_at'} || $comment->{'created_at'};
100 my $body = encode_utf8( $comment->{'body'} );
101 say "-" x 79;
102 say "Date: $date";
103 say "From: $user";
104 say "\n$body\n";
105 }
106 return 0;
107 }
108  
109  
110 sub patch {
111 my ($self, $number) = @_;
112 die("Please specify a pull request number.\n") unless $number;
113 my $patch = _get_url(
114 $self->_fetch_one($number)->{'patch_url'}
115 );
116 die("Unable to fetch patch for pull request $number.\n")
117 unless defined $patch;
118 print $patch;
119 return 0;
120 }
121  
122  
123 sub checkout {
124 my ($self, $number) = @_;
125 $number =~ s{[^\d]}{}g if defined $number;
126 die("Please specify a pull request number.\n") unless $number;
127 my $pr = $self->_fetch_one($number);
128  
129 # Get required contributor branch info
130 my $head_repo = $pr->{'head'}->{'repo'}->{'clone_url'};
131 my $head_branch = $pr->{'head'}->{'ref'};
132 my $head_user = $pr->{'head'}->{'user'}->{'login'};
133  
134 # Check if the remote already exists in our repo
135 my $head_remote;
136 foreach my $line ( _qx("git", "remote -v") ) {
137 my ($remote, $url, $type) = split /\s+/, $line;
138 next unless $type eq '(fetch)'; # only consider fetch remotes
139 if ( $url eq $head_repo ) {
140 $head_remote = $remote;
141 last;
142 }
143 }
144  
145 if ( $head_remote ) {
146 # Remote already exists, try to update its state
147 unless ( _qx(qw(git branch --list -r), qq{"$head_remote/$head_branch"}) ) {
148 # Create a new tracking branch, because one doesn't already exist
149 my ($content, $rc) = _run_ext(
150 qw(git remote set-branches),
151 '--add', # don't remove any other existing tracking branches
152 $head_remote, # our remote's name/alias
153 $head_branch, # the ref we want to track
154 );
155 die("git failed with error $rc when trying to add tracking branch"
156 . " to existing remote.\n")
157 if $rc != 0;
158 }
159  
160 # Fetch changes from just added remote
161 say "Fetching changes from '$head_remote/$head_branch'";
162 my ($content, $rc) = _run_ext(
163 qw(git fetch),
164 $head_remote,
165 );
166 die("git failed with error $rc when trying to update remote.\n")
167 if $rc != 0;
168 }
169 else {
170 # Create and fetch the branch info if it doesn't exist already
171 $head_remote = $head_user;
172 my ($content, $rc) = _run_ext(
173 qw(git remote add),
174 '-f', # only fetch specific refs
175 '-t', $head_branch, # add only a ref for this ref, not all
176 $head_remote, # what we'll name our remote
177 $head_repo, # URL to the head repo
178 );
179 die("git failed with error $rc when trying to add remote.\n")
180 if $rc != 0;
181 }
182  
183 # Actually checkout the ref we just updated as pr/<number>
184 my ($content, $rc) = _run_ext(
185 qw(git checkout),
186 '-b', "pr/$number",
187 '--track', "$head_remote/$head_branch",
188 );
189 die("git failed with error $rc when trying to check out branch.\n")
190 if $rc != 0;
191  
192 return 0;
193 }
194  
195  
196 sub close { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
197 my ($self, $number) = @_;
198 die("Please specify a pull request number.\n") unless $number;
199 my $pr = $self->_state($number, 'closed');
200 die("Unable to close pull request $number.\n")
201 unless defined $pr;
202 say "Pull request $number now in state: " . $pr->{'state'};
203 return 0;
204 }
205  
206  
207 sub open { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
208 my ($self, $number) = @_;
209 die("Please specify a pull request number.\n") unless $number;
210 my $pr = $self->_state($number, 'open');
211 die("Unable to open pull request $number.\n")
212 unless defined $pr;
213 say "Pull request $number now in state: " . $pr->{'state'};
214 return 0;
215 }
216  
217  
218 sub comment {
219 my ($self, $number, $text) = @_;
220 die("Please specify a pull request number.\n") unless $number;
221 my $remote_repo = _find_github_remote();
222 my $filename;
223 unless ( $text ) {
224 $filename = _tmpfile("$remote_repo-$number");
225 # Find and execute editor on temporary file
226 my $editor = $ENV{'EDITOR'};
227 unless ( $editor ) {
228 _require_binary('editor');
229 $editor = 'editor';
230 }
231 system($editor, $filename);
232 # Fetch text just edited (if any)
233 if ( -r $filename ) {
234 CORE::open my $fh, "<:encoding(UTF-8)", $filename or die "Can't open $filename: $!";
235 $text = join "", <$fh>;
236 CORE::close $fh;
237 }
238 # Abort if no text found
239 unless ( $text ) {
240 unlink $filename;
241 die("Your comment is empty. Command aborted.\n");
242 }
243 }
244 my $comment = eval {
245 _api_create(
246 "/repos/$remote_repo/issues/$number/comments",
247 { "body" => $text },
248 );
249 };
250 die($@ . ( defined $filename ? "Comment text saved in '$filename'. Please remove it manually." : "" ) ."\n")
251 if $@; # most likely network error
252 die("Unable to add comment on pull request $number.\n")
253 unless defined $comment;
254 say "Comment added. You can view it online here: " . $comment->{'html_url'};
255  
256 # Remove temporary file if everything went well
257 if ( defined $filename and -e $filename ) {
258 my $count = unlink $filename;
259 warn("Unable to remove temporary file $filename: $!\n")
260 unless $count;
261 }
262  
263 return 0;
264 }
265  
266  
267 sub login {
268 my ($self, $user, $password, $two_factor_token) = @_;
269  
270 # Add deprecation message
271 say "\nThis authorization method is deprecated and will be removed on November 13, 2020.";
272 say "Please use the 'authorize' command to authenticate with GitHub.\n";
273  
274 # Try to fetch user/password from git config (or prompt)
275 $user ||= _qx('git', "config github.user") || _prompt('GitHub username');
276 $password ||= _qx('git', "config github.password") || _prompt('GitHub password', 'hidden');
277 die("Please specify a user name.\n") unless $user;
278 die("Please specify a password.\n") unless $password;
279 # Prompt for two-factor auth token
280 $two_factor_token ||= _prompt('GitHub two-factor authentication token (if any)');
281  
282 # Perform authentication
283 my $auth = _api_create(
284 "/authorizations",
285 {
286 "scopes" => [qw( public_repo repo )],
287 "note" => __PACKAGE__,
288 "note_url" => 'https://metacpan/module/' . __PACKAGE__,
289 },
290 $user,
291 $password,
292 $two_factor_token,
293 );
294 die("Unable to authenticate with GitHub.\n")
295 unless defined $auth;
296 my $token = $auth->{'token'};
297 die("Authentication data does not include a token.\n")
298 unless $token;
299  
300 # Store authorization token
301 my ($content, $rc) = _run_ext(qw(git config --global github.pr-token), $token);
302 die("git config returned message '$content' and code $rc when trying to store your token.\n")
303 if $rc != 0;
304 say "Access token stored successfully. Go to https://github.com/settings/tokens to revoke access.";
305 return 0;
306 }
307  
308  
309 sub authorize {
310 my ($self, $token) = @_;
311 # Verify that you want to overwrite an existing token
312 my $old_token = _qx('git', "config github.pr-token");
313 if ( $old_token and not $token ) {
314 say "You're already authorized.";
315 my $q = _prompt("Do you want to generate a new token (y/N)") || "n";
316 return 0 if lc($q) ne 'y';
317 }
318 # Give instructions and ask for token if not specified on command line
319 unless ( $token ) {
320 say "Go to https://github.com/settings/tokens/new and follow the directions to generate a new token.";
321 say "Give the token a name of your choice, e.g. 'git-pr', and give it the 'repo' permission.";
322 say "The 'public_repo' permission is enough if you only plan to use it with public repositories.\n";
323 $token = _prompt('GitHub OAuth personal access token');
324 }
325 # Make sure a token is specified
326 die("No token was specified. No changes have been made to your configuration.\n")
327 unless $token;
328 # Store authorization token
329 my ($content, $rc) = _run_ext(qw(git config --global github.pr-token), $token);
330 die("git config returned message '$content' and code $rc when trying to store your token.\n")
331 if $rc != 0;
332 say "Access token stored successfully. Go to https://github.com/settings/tokens to revoke access.";
333 return 0;
334 }
335  
336 sub _state {
337 my ($self, $number, $state) = @_;
338 croak("Please specify a pull request number") unless $number;
339 croak("Please specify a pull request state") unless $state;
340 my $remote_repo = _find_github_remote();
341 return _api_update(
342 "/repos/$remote_repo/pulls/$number",
343 { "state" => $state },
344 );
345 }
346  
347 sub _fetch_one {
348 my ($self, $number) = @_;
349 my $remote_repo = _find_github_remote();
350 return _api_read("/repos/$remote_repo/pulls/$number");
351 }
352  
353 sub _find_github_remote {
354 # Parse lines from git and use first found github repo
355 my @repos;
356 my $repo_map = {};
357 foreach my $line ( _qx('git', 'remote -v') ) {
358 my ($remote, $url, $type) = split /\s+/, $line;
359 next unless $type eq '(fetch)'; # only consider fetch remotes
360 next unless $url =~ m/github\.com/; # only consider remotes to github
361 if ( $url =~ m{github.com[:/](.+?)(?:\.git)?$} ) {
362 push @repos, $1;
363 $repo_map->{$1} = $remote;
364 }
365 }
366  
367 # Allow override for testing
368 @repos = ( $ENV{"GITHUB_REPO"} ) if $ENV{'GITHUB_REPO'};
369  
370 die("No valid GitHub repos found.\n")
371 unless @repos;
372  
373 # Try each repo found in turn
374 while ( my $repo = shift @repos ) {
375 print "Fetching GitHub repo: $repo\n"
376 if DEBUG;
377 # Fetch repo information
378 my ($repo_info, $code) = _api_read("/repos/$repo", 'return_on_error');
379  
380 # Skip repo which is not found
381 if ( $code eq 404 ) {
382 print STDERR "WARNING: Skipping invalid GitHub repo: $repo\n";
383 if ( $repo_map->{$repo} ) {
384 print STDERR "WARNING:\n";
385 print STDERR "WARNING: Remove invalid git remote with command:\n";
386 print STDERR "WARNING: git remote remove $repo_map->{$repo}\n";
387 print STDERR "WARNING:\n";
388 }
389 next;
390 }
391  
392 # Return the parent repo if repo is a fork
393 return $repo_info->{'parent'}->{'full_name'}
394 if $repo_info->{'fork'};
395  
396 # Not a fork, use this repo
397 return $repo;
398 }
399  
400 die("No valid GitHub repo found. List of remotes exhausted.\n");
401 }
402  
403 # Ask the user for some information
404 # Disable local echo if $hide_echo is true (for passwords)
405 sub _prompt {
406 my ($label, $hide_echo) = @_;
407 _echo('off') if $hide_echo;
408 print "$label: " if defined $label;
409 my $input = scalar <STDIN>;
410 chomp $input;
411 print "\n";
412 _echo('on') if $hide_echo;
413 return $input;
414 }
415  
416 # Turn local echo on or off (Unix only for now)
417 sub _echo {
418 my ($state) = @_;
419 croak("Please specify an echo state of on or off") unless $state;
420  
421 # Test if we're on Unix (snatched from Platform::Unix)
422 my $is_unix = $^O =~ /^(Linux|.*BSD.*|.*UNIX.*|Darwin|Solaris|SunOS|Haiku|Next|dec_osf|svr4|sco_sv|unicos.*|.*x)$/i;
423  
424 if ( $is_unix ) {
425 return _run_ext(qw{stty -echo}) if $state eq 'off';
426 return _run_ext(qw{stty echo}) if $state eq 'on';
427 }
428  
429 # Don't know how to turn local echo on or off on other platforms.
430 # If you happen to know how, please send a pull request with a fix
431 return;
432 }
433  
434 # Generate a random temporary filename with the given prefix
435 sub _tmpfile {
436 my ($prefix) = @_;
437 $prefix = defined $prefix ? "${prefix}-" : '';
438 $prefix =~ s{[^A-Za-z0-9_-]}{-}g;
439 srand($$ + time);
440 my $random = $$;
441 $random .= int(rand(10)) for 1..10;
442 return "/tmp/git-pr-$prefix$random";
443 }
444  
445 # Return stdout from external program
446 # If called in list context, each line will be chomped
447 # In scalar context, only last line will be chomped
448 sub _qx {
449 my ($cmd, @rest) = @_;
450 _require_binary($cmd);
451 $cmd .= " " . join(" ", @rest) if @rest;
452 warn("_qx: $cmd\n") if DEBUG;
453 return map { chomp; $_ } qx{$cmd}
454 if wantarray;
455 my $content = qx{$cmd};
456 chomp $content;
457 return $content;
458 }
459  
460 # Run an external command and return STDOUT and exit code
461 ## no critic (Subroutines::RequireArgUnpacking)
462 sub _run_ext {
463 croak("Please specify a command line") unless @_;
464 my $cmd = join(" ", @_);
465 my $prg = $_[0];
466 warn("_run_ext: $cmd\n") if DEBUG;
467 _require_binary($prg);
468 CORE::open my $fh, "-|", @_ or die("Can't run command '$cmd': $!");
469 my $stdout = join("", <$fh>);
470 CORE::close $fh;
471 my $rc = $? >> 8; # exit code, see perldoc perlvar for details
472 return $stdout, $rc;
473 }
474 ## use critic
475  
476 # Make sure a program is present in path
477 sub _require_binary {
478 my ($bin) = @_;
479 croak("Please specify program to require") unless $bin;
480 state %cache;
481 unless (exists $cache{$bin}) {
482 # Cache miss, let's see if we can find that program
483 warn("Checking if '$bin' exists in path\n") if DEBUG;
484 # Figure out path elements in a cross-platform way and go through
485 # each and check if it has the executable program in it
486 my @path = File::Spec->path();
487 while (my $dir = shift @path) {
488 my $file = File::Spec->catfile($dir, $bin);
489 warn("Looking for executable bit on '$file'\n") if DEBUG;
490 ## no critic (ValuesAndExpressions::ProhibitCommaSeparatedStatements)
491 $cache{$bin} = $file, last if -x $file;
492 ## use critic
493 $cache{$bin} = 0;
494 }
495 warn("'$bin' was found at '$cache{$bin}'\n") if DEBUG and $cache{$bin};
496 }
497 return 1 if $cache{$bin};
498 die("You need the program '$bin' in your path to use this feature.\n");
499 }
500  
501 # Return the base GitHub API URL as mentioned
502 # on http://developer.github.com/v3/
503 sub _api_url {
504 my ($url) = @_;
505 my $prefix = 'https://api.github.com/';
506 # If no URL specified, just return the API URL
507 return $prefix unless defined $url;
508 # If URL already looks like a GitHub API URL, do nothing
509 return $url if _is_api_url($url);
510 # Create an API URL out of a partial URL as
511 $url =~ s{^/*}{}; # Remove initial slashes, if any
512 return $prefix . $url;
513 }
514  
515 # Check if a URL is a GitHub API URL
516 sub _is_api_url {
517 my ($url) = @_;
518 croak("Please specify a URL to verify") unless $url;
519 my $prefix = _api_url();
520 return 1 if index($url, $prefix) == 0;
521 return 0;
522 }
523  
524 # Perform an API GET request
525 sub _api_read {
526 my ($url, $return_on_error) = @_;
527 my ($response, $code) = _get_url(
528 _api_url($url),
529 $return_on_error,
530 );
531 return decode_json($response), $code
532 if $return_on_error;
533 return decode_json($response);
534 }
535  
536 # Perform an API POST request
537 sub _api_create {
538 my ($url, $data, @rest) = @_;
539 return decode_json(
540 _post_url(
541 _api_url($url),
542 'application/json',
543 encode_json($data),
544 @rest,
545 )
546 );
547 }
548  
549 # Perform an API PATCH request
550 sub _api_update {
551 my ($url, $data) = @_;
552 return decode_json(
553 _patch_url(
554 _api_url($url),
555 'application/json',
556 encode_json($data),
557 )
558 );
559 }
560  
561 # Perform HTTP GET
562 sub _get_url {
563 my ($url, $return_on_error) = @_;
564 croak("Please specify a URL") unless $url;
565  
566 # See if we should use credentials
567 my @credentials;
568 if ( _is_api_url($url) ) {
569 my $token = _qx('git', 'config github.pr-token');
570 @credentials = ( '-H', "Authorization: token $token" ) if $token;
571 }
572  
573 # Send request
574 my ($content, $rc) = _run_ext(
575 'curl',
576 '-L', # follow redirects
577 '-s', # be silent
578 '-w', '%{http_code}', # include HTTP status code at end of stdout
579 @credentials, # Logon credentials, if any
580 $url, # The URL we're GETing
581 );
582 die("curl failed to fetch $url with code $rc.\n") if $rc != 0;
583  
584 my $code = substr($content, -3, 3, '');
585  
586 return $content, $code if $return_on_error;
587  
588 if ( $code >= 400 ) {
589 die("Fetching URL $url failed with code $code:\n$content");
590 }
591  
592 return $content;
593 }
594  
595 # Perform HTTP PATCH
596 sub _patch_url {
597 my ($url, $mimetype, $data) = @_;
598 croak("Please specify a URL") unless $url;
599 croak("Please specify a mimetype") unless $mimetype;
600 croak("Please specify some data") unless $data;
601  
602 # See if we should use credentials
603 my @credentials;
604 if ( _is_api_url($url) ) {
605 my $token = _qx('git', 'config github.pr-token');
606 die("You must login before you can modify information.\n")
607 unless $token;
608 @credentials = ( '-H', "Authorization: token $token" );
609 }
610  
611 # Send request
612 my ($content, $rc) = _run_ext(
613 'curl',
614 '-s', # be silent
615 '-w', '%{http_code}', # include HTTP status code at end of stdout
616 '-X', 'PATCH', # perform an HTTP PATCH
617 '-H', "Content-Type: $mimetype", # What kind of data we're sending
618 '-d', $data, # Our data
619 @credentials, # Logon credentials, if any
620 $url, # The URL we're PATCHing
621 );
622 die("curl failed to patch $url with code $rc.\n") if $rc != 0;
623  
624 my $code = substr($content, -3, 3, '');
625 if ( $code >= 400 ) {
626 die("If you get 'Validation Failed' error without any reason,"
627 . " most likely the pull request has already been merged or closed by the repo owner.\n"
628 . "URL: $url\n"
629 . "Code: $code\n"
630 . $content
631 ) if $code == 422;
632 die("Patching URL $url failed with code $code:\n$content");
633 }
634  
635 return $content;
636 }
637  
638 # Perform HTTP POST
639 sub _post_url {
640 my ($url, $mimetype, $data, $user, $password, $two_factor_token) = @_;
641 croak("Please specify a URL") unless $url;
642 croak("Please specify a mimetype") unless $mimetype;
643 croak("Please specify some data") unless $data;
644  
645 # See if we should use credentials
646 my @credentials;
647 if ( _is_api_url($url) ) {
648 my $token = _qx('git', 'config github.pr-token');
649 die("You must login before you can modify information.\n")
650 unless $token or ( $user and $password );
651 if ( $user and $password ) {
652 @credentials = ( '-u', "$user:$password" );
653 push @credentials, '-H', "X-GitHub-OTP: $two_factor_token"
654 if $two_factor_token;
655 }
656 else {
657 @credentials = ( '-H', "Authorization: token $token" ) if $token;
658 }
659 }
660  
661 # Send request
662 my ($content, $rc) = _run_ext(
663 'curl',
664 '-s', # be silent
665 '-w', '%{http_code}', # include HTTP status code at end of stdout
666 '-X', 'POST', # perform an HTTP POST
667 '-H', "Content-Type: $mimetype", # What kind of data we're sending
668 '-d', $data, # Our data
669 @credentials, # Logon credentials, if any
670 $url, # The URL we're POSTing to
671 );
672 die("curl failed to post to $url with code $rc.\n") if $rc != 0;
673  
674 my $code = substr($content, -3, 3, '');
675 if ( $code >= 400 ) {
676 die("Posting to URL $url failed with code $code:\n$content");
677 }
678  
679 return $content;
680 }
681  
682 1;
683  
684 __END__