GitHubBackup module for backup github project
authorKen-ichi Mito <mitty@mitty.jp>
Sat, 17 Aug 2013 12:15:33 +0000 (21:15 +0900)
committerKen-ichi Mito <mitty@mitty.jp>
Sat, 17 Aug 2013 12:15:33 +0000 (21:15 +0900)
 * work in progress
 * GitHubBackup->new->repos returns repository list

Dev/github/GitHubBackup.pm [new file with mode: 0644]

diff --git a/Dev/github/GitHubBackup.pm b/Dev/github/GitHubBackup.pm
new file mode 100644 (file)
index 0000000..c0427e6
--- /dev/null
@@ -0,0 +1,98 @@
+package utils;
+use strict;
+use warnings;
+use utf8;
+use Carp qw(croak);
+
+use LWP::UserAgent;
+use JSON;
+my $ua = LWP::UserAgent->new;
+my $json = JSON->new->utf8->indent;
+
+sub json_api {
+    my $url = shift;
+    
+    my $res = $ua->get(
+        "https://api.github.com$url"
+    );
+    
+    $res->is_success or croak $res->status_line;
+    
+    return $json->decode($res->content);
+}
+
+package GitHubBackup;
+use base qw(Class::Accessor::Fast);
+
+use strict;
+use warnings;
+use utf8;
+use Carp qw(croak);
+
+__PACKAGE__->mk_accessors( qw(
+    directory
+    account
+    repository
+));
+
+
+# both hash and hashref are acceptable
+sub new {
+    my $class = shift;
+    
+    my $args = (ref $_[0] eq 'HASH') ? $_[0] : {@_};
+    return $class->SUPER::new($args);
+}
+
+sub repos {
+    my $self = shift;
+    
+    my $account = $self->account or croak "account is not set";
+    if (my $repository = $self->repository) {
+        $self->{repos} = [
+            GitHubBackup::Repository->new(
+                {full_name => "$account/$repository"}
+            )
+        ];
+        
+        return $self->{repos};
+    }
+    
+    my $page = 1;
+    my @repos;
+    while (1) {
+        my $result = utils::json_api("/users/$account/repos?per_page=100&page=$page");
+        if (ref($result) eq 'ARRAY' && scalar @$result > 0) {
+            push @repos, @$result;
+            $page++;
+            
+            next;
+        }
+        last;
+    }
+    
+    foreach my $repos (@repos) {
+        push @{$self->{repos}},
+            GitHubBackup::Repository->new({
+                full_name => $repos->{full_name},
+                clone_url => $repos->{clone_url},
+            })
+        ;
+    }
+    
+    return $self->{repos};
+}
+
+
+package GitHubBackup::Repository;
+use base qw(Class::Accessor::Fast);
+
+use strict;
+use warnings;
+use utf8;
+use Carp qw(croak);
+
+
+
+1;
+__END__