Skip to content

Instantly share code, notes, and snippets.

@ugexe
Last active September 1, 2015 18:28
Show Gist options
  • Save ugexe/23026e421b6b3a9c697b to your computer and use it in GitHub Desktop.
Save ugexe/23026e421b6b3a9c697b to your computer and use it in GitHub Desktop.
perl6 CompUnitRepo::Github - ish type demo (Github API + use use IO::Path does URI to allow `cloud` like behavior, downloading to temp file, possibly allowing CompUnitRepo::Local::Installation to install it)
use Zef::Net::URI;
use Zef::Net::HTTP::Client;
use Zef::Utils::Base64;
require IO::Socket::SSL;
role IO::URI[::UA, :$dir = $*TMPDIR.child('perl6-io-uri')] {
try mkdir($dir) unless $dir.IO.e;
my %uri2path;
my $ua = UA.new(:headers(:User-Agent('perl6/zef')));
method IO {
with $.Str -> $uri-str {
# todo: validate $uri
without %uri2path{$uri-str} -> $p is rw {
$p = IO::Path.new-from-absolute-path( ~$dir.IO.child(".{time}.{(1..1000).pick(1)}") );
try {
my $c = $ua.get($uri-str).content(:bin).decode('utf8');
$p.IO.spurt($c);
}
}
%uri2path{$uri-str};
}
}
}
role Github::API::Repos::Trees {
method trees-uri { "{$.api-uri}{$.owner}/{$.repo}/git/trees/" }
method trees(Bool :$recursive) {
my $tail = $recursive.so
?? "{$.branch}?recursive=1"
!! $.branch;
my $uri = $.trees-uri ~ $tail;
my $content = Zef::Net::HTTP::Client.new(:headers( :User-Agent('perl6/zef') ))\
.get(~$uri).content(:bin).decode;
my $json = from-json($content);
my %trees = $json.hash;
}
}
class Github::API {
has $.api-uri;
submethod BUILD(:$!api-uri) {
$!api-uri = 'https://api.github.com/repos/' unless $!api-uri.so;
}
}
class Github::API::Repos is Github::API does Github::API::Repos::Trees {
has $.owner;
has $.repo;
has $.branch;
submethod BUILD(:$!owner!, :$!repo!, :$!branch = 'master') { }
}
###############################################################################
my $owner = 'ugexe';
my $repo = 'zef';
my $branch = 'master';
my $g = Github::API::Repos.new(:$owner, :$repo, :$branch);
my %t = $g.trees(:recursive);
for %t<tree>.list -> %item is copy {
if %item<type>.lc eq 'blob' {
%item<url> = Zef::Net::URI.new( :url(%item<url>) );
%item<url> does IO::URI[Zef::Net::HTTP::Client];
say '-------------------------------';
say %item<path>;
say %item<url>.Str;
my $json = %item<url>.IO.slurp;
my %data = %(from-json($json));
my $content = %data<content>.subst(/\n/, '', :g);
my $decoded = b64decode($content).decode('utf-8');
say $decoded;
say '===============================';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment