Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Last active June 30, 2023 12:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandfoy/cf13542ca12128b5d870042c38cd1fb0 to your computer and use it in GitHub Desktop.
Save briandfoy/cf13542ca12128b5d870042c38cd1fb0 to your computer and use it in GitHub Desktop.
A Mojo::UserAgent program to grab all the files in a gist
#!/usr/bin/perl
=encoding utf8;
=head1 NAME
grab-gist - download all the files in a gist
=head1 SYNOPSIS
# by the URL
$ grab-gist https://gist.github.com/briandfoy/cf13542ca12128b5d870042c38cd1fb0
# by the ID
$ grab-gist cf13542ca12128b5d870042c38cd1fb0
=head1 DESCRITION
I don't want to do a bunch of pointy-clicky in the web sites, so if
I have the gist ID, like in a link from chat, I can grab all the files
in a local dir.
Since a gist is actually a git repo and the gists can be revised, the
actual link to the current revsion needs more information than just the
link. Just try that "raw" button in the web UI and see what else it tags
on.
=head1 AUTHOR
brian d foy, bdfoy@cpan.org
=head1 COPYRIGHT AND LICENSE
You can use and distribute this program under the terms of the Artistic
License 2.0.
=cut
use Mojo::UserAgent;
my $id = do {
if( $ARGV[0] =~ /\A [a-f0-9]+ \z/xi ) { $ARGV[0] }
elsif( $ARGV[0] =~ m| \A https://gist.github.com /[a-z0-9]+/ ([a-f0-9]+) \z |xi ) { $1 }
else {
die "Argument should be an gist ID or a gist URL\n";
}
};
my $url = sprintf 'https://api.github.com/gists/%s', $id;
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get($url);
unless( $tx->res->is_success ) {
die "Could not fetch gist\n";
}
my $json = eval { $tx->res->json };
unless( defined $json ) {
die "Could not extract JSON: $@\n";
}
FILE: foreach my $filename ( keys $json->{files}->%* ) {
print "Extracting $filename\n";
open my $fh, '>:utf8', $filename or do {
warn "Could not open $filename for writing: $!\n";
next FILE;
};
print {$fh} $json->{files}{$filename}{content};
close $fh;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment