Merge remote branch 't0m/json' into json
[catagits/Gitalist.git] / lib / Gitalist / Git / Repository.pm
1 use MooseX::Declare;
2
3 class Gitalist::Git::Repository with Gitalist::Git::HasUtils {
4     # FIXME, use Types::Path::Class and coerce
5     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
6     use MooseX::Types::Moose qw/Str Maybe Bool HashRef ArrayRef/;
7     use MooseX::MultiMethods;
8     use Gitalist::Git::Types qw/SHA1 DateTime Dir/;
9     use Moose::Autobox;
10     use List::MoreUtils qw/any zip/;
11     use aliased 'DateTime' => 'DT';
12     use Encode qw/decode/;
13     use I18N::Langinfo qw/langinfo CODESET/;
14     use Gitalist::Git::Object::Blob;
15     use Gitalist::Git::Object::Tree;
16     use Gitalist::Git::Object::Commit;
17     use Gitalist::Git::Object::Tag;
18     
19     with 'Gitalist::Serializeable';
20
21     our $SHA1RE = qr/[0-9a-fA-F]{40}/;
22
23     around BUILDARGS (ClassName $class: Dir $dir) {
24         # Allows us to be called as Repository->new($dir)
25         # Last path component becomes $self->name
26         # Full path to git objects becomes $self->path
27         my $name = $dir->dir_list(-1);
28         $dir = $dir->subdir('.git') if (-f $dir->file('.git', 'HEAD'));
29         confess("Can't find a git repository at " . $dir)
30             unless ( -f $dir->file('HEAD') );
31         return $class->$orig(name => $name,
32                              path => $dir);
33     }
34
35     has name => ( isa => NonEmptySimpleStr,
36                   is => 'ro', required => 1 );
37
38     has path => ( isa => Dir,
39                   is => 'ro', required => 1,
40                   traits => [qw/ DoNotSerialize /] );
41
42     has description => ( isa => Str,
43                          is => 'ro',
44                          lazy_build => 1,
45                      );
46
47     has owner => ( isa => NonEmptySimpleStr,
48                    is => 'ro',
49                    lazy_build => 1,
50                );
51
52     has last_change => ( isa => Maybe[DateTime],
53                          is => 'ro',
54                          lazy_build => 1,
55                      );
56
57     has is_bare => ( isa => Bool,
58                      is => 'ro',
59                      lazy => 1,
60                      default => sub {
61                          -d $_[0]->path->parent->subdir($_[0]->name)
62                              ? 1 : 0
63                          },
64                      );
65     has heads => ( isa => ArrayRef[HashRef],
66                    is => 'ro',
67                    lazy_build => 1,
68                    traits => [qw/ DoNotSerialize /],
69                    );
70     has tags => ( isa => ArrayRef[HashRef],
71                    is => 'ro',
72                    lazy_build => 1);
73     has references => ( isa => HashRef[ArrayRef[Str]],
74                         is => 'ro',
75                         lazy_build => 1 );
76
77     method BUILD {
78         $self->$_() for qw/last_change owner description/; # Ensure to build early.
79     }
80
81     ## Public methods
82
83     multi method get_object_or_head (SHA1 $sha1) {
84         $self->get_object($sha1);
85     }
86     multi method get_object_or_head (NonEmptySimpleStr $ref) {
87         my $sha1 = $self->head_hash($ref);
88         $self->get_object($sha1);
89     }    
90     
91     method head_hash (Str $head?) {
92         my $output = $self->run_cmd(qw/rev-parse --verify/, $head || 'HEAD' );
93         confess("No such head: " . $head) unless defined $output;
94
95         my($sha1) = $output =~ /^($SHA1RE)$/;
96         return $sha1;
97     }
98
99     method list_tree (SHA1 $sha1?) {
100         $sha1 ||= $self->head_hash;
101         my $object = $self->get_object($sha1);
102         return @{$object->tree};
103     }
104
105     method get_object (NonEmptySimpleStr $sha1) {
106         unless (is_SHA1($sha1)) {
107             $sha1 = $self->head_hash($sha1);
108         }
109         my $type = $self->run_cmd('cat-file', '-t', $sha1);
110         chomp($type);
111         my $class = 'Gitalist::Git::Object::' . ucfirst($type);
112         $class->new(
113             repository => $self,
114             sha1 => $sha1,
115             type => $type,
116         );
117     }
118
119     method hash_by_path ($base, $path = '', $type?) {
120         $path =~ s{/+$}();
121         # FIXME should this really just take the first result?
122         my @paths = $self->run_cmd('ls-tree', $base, '--', $path)
123             or return;
124         my $line = $paths[0];
125
126         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
127         $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
128         return defined $type && $type ne $2
129             ? ()
130                 : $3;
131     }
132
133     method list_revs ( NonEmptySimpleStr :$sha1!,
134                        Int :$count?,
135                        Int :$skip?,
136                        HashRef :$search?,
137                        NonEmptySimpleStr :$file? ) {
138         $sha1 = $self->head_hash($sha1)
139             if !$sha1 || $sha1 !~ $SHA1RE;
140
141         my @search_opts;
142         if ($search and exists $search->{text}) {
143             $search->{type} = 'grep'
144                 if $search->{type} eq 'commit';
145             @search_opts = (
146                 # This seems a little fragile ...
147                 qq[--$search->{type}=$search->{text}],
148                 '--regexp-ignore-case',
149                 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
150             );
151         }
152
153         my $output = $self->run_cmd(
154             'rev-list',
155             '--header',
156             (defined $count ? "--max-count=$count" : ()),
157             (defined $skip ? "--skip=$skip"       : ()),
158             @search_opts,
159             $sha1,
160             '--',
161             ($file ? $file : ()),
162         );
163         return unless $output;
164
165         my @revs = $self->_parse_rev_list($output);
166
167         return @revs;
168     }
169
170     method snapshot (NonEmptySimpleStr :$sha1,
171                  NonEmptySimpleStr :$format
172                ) {
173         # TODO - only valid formats are 'tar' and 'zip'
174         my $formats = { tgz => 'tar', zip => 'zip' };
175         unless ($formats->exists($format)) {
176             die("No such format: $format");
177         }
178         $format = $formats->{$format};
179         my $name = $self->name;
180         $name =~ s,([^/])/*\.git$,$1,;
181         my $filename = $name;
182         $filename .= "-$sha1.$format";
183         $name =~ s/\047/\047\\\047\047/g;
184
185         my @cmd = ('archive', "--format=$format", "--prefix=$name/", $sha1);
186         return ($filename, $self->run_cmd_fh(@cmd));
187         # TODO - support compressed archives
188     }
189
190     method diff ( Gitalist::Git::Object :$commit!,
191                   Bool :$patch?,
192                   Maybe[NonEmptySimpleStr] :$parent?,
193                   NonEmptySimpleStr :$filename?
194               ) {
195               return $commit->diff( patch => $patch,
196                                     parent => $parent,
197                                     filename => $filename);
198     }
199
200     method reflog (@logargs) {
201         my @entries
202             =  $self->run_cmd(qw(log -g), @logargs)
203                 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
204
205         #  commit 02526fc15beddf2c64798a947fecdd8d11bf993d
206         #  Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
207         #  Reflog message: push
208         #  Author: Foo Barsby <fbarsby@example.com>
209         #  Date:   Thu Sep 17 12:26:05 2009 +0100
210         #
211         #      Merge branch 'abc123'
212
213         return map {
214             # XXX Stuff like this makes me want to switch to Git::PurePerl
215             my($sha1, $type, $author, $date)
216                 = m{
217                        ^ commit \s+ ($SHA1RE)$
218                        .*?
219                        Reflog[ ]message: \s+ (.+?)$ \s+
220                      Author: \s+ ([^<]+) <.*?$ \s+
221                    Date: \s+ (.+?)$
222                }xms;
223
224             pos($_) = index($_, $date) + length $date;
225
226             # Yeah, I just did that.
227             my($msg) = /\G\s+(\S.*)/sg;
228             {
229                 hash    => $sha1,
230                 type    => $type,
231                 author  => $author,
232
233                 # XXX Add DateTime goodness.
234                 date    => $date,
235                 message => $msg,
236             }
237             ;
238         } @entries;
239     }
240
241     ## BUILDERS
242     method _build_util {
243         Gitalist::Git::Util->new(
244             repository => $self,
245         );
246     }
247
248     method _build_description {
249         my $description = "";
250         eval {
251             $description = $self->path->file('description')->slurp;
252             chomp $description;
253         };
254         $description = "Unnamed repository, edit the .git/description file to set a description"
255             if $description eq "Unnamed repository; edit this file 'description' to name the repository.";
256         return $description;
257     }
258
259     method _build_owner {
260         my ($gecos, $name) = map { decode(langinfo(CODESET), $_) } (getpwuid $self->path->stat->uid)[6,0];
261         $gecos =~ s/,+$//;
262         return length($gecos) ? $gecos : $name;
263     }
264
265     method _build_last_change {
266         my $last_change;
267         my $output = $self->run_cmd(
268             qw{ for-each-ref --format=%(committer)
269                 --sort=-committerdate --count=1 refs/heads
270           });
271         if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
272             my $dt = DT->from_epoch(epoch => $epoch);
273             $dt->set_time_zone($tz);
274             $last_change = $dt;
275         }
276         return $last_change;
277     }
278
279     method _build_heads {
280         my @revlines = $self->run_cmd_list(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
281         my @ret;
282         for my $line (@revlines) {
283             my ($rev, $head, $commiter) = split /\0/, $line, 3;
284             $head =~ s!^refs/heads/!!;
285
286             push @ret, { sha1 => $rev, name => $head };
287
288             #FIXME: That isn't the time I'm looking for..
289             if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
290                 my $dt = DT->from_epoch(epoch => $epoch);
291                 $dt->set_time_zone($tz);
292                 $ret[-1]->{last_change} = $dt;
293             }
294         }
295
296         return \@ret;
297     }
298
299     method _build_tags {
300         my @revlines = $self->run_cmd_list('for-each-ref',
301           '--sort=-creatordate',
302           '--format=%(objectname) %(objecttype) %(refname) %(*objectname) %(*objecttype) %(subject)%00%(creator)',
303           'refs/tags'
304         );
305         my @ret;
306         for my $line (@revlines) {
307             my($refinfo, $creatorinfo) = split /\0/, $line;
308             my($rev, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
309             my($creator, $epoch, $tz) = ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
310             $name =~ s!^refs/tags/!!;
311
312             push @ret, { sha1 => $rev, name => $name };
313
314             #FIXME: That isn't the time I'm looking for..
315             if($epoch and $tz) {
316                 my $dt = DT->from_epoch(epoch => $epoch);
317                 $dt->set_time_zone($tz);
318                 $ret[-1]->{last_change} = $dt;
319             }
320         }
321
322         return \@ret;
323     }
324
325     method _build_references {
326         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
327         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
328         my @reflist = $self->run_cmd_list(qw(show-ref --dereference))
329             or return;
330         my %refs;
331         for (@reflist) {
332             push @{$refs{$1}}, $2
333                 if m!^($SHA1RE)\srefs/(.*)$!;
334         }
335
336         return \%refs;
337     }
338
339     ## Private methods
340     method _parse_rev_list ($output) {
341         return
342             map  $self->get_gpp_object($_),
343                 grep is_SHA1($_),
344                     map  split(/\n/, $_, 6), split /\0/, $output;
345     }
346
347 } # end class
348
349 __END__
350
351 =head1 NAME
352
353 Gitalist::Git::Repository - Model of a git repository
354
355 =head1 SYNOPSIS
356
357     my $gitrepo = dir('/repo/base/Gitalist');
358     my $repository = Gitalist::Git::Repository->new($gitrepo);
359      $repository->name;        # 'Gitalist'
360      $repository->path;        # '/repo/base/Gitalist/.git'
361      $repository->description; # 'Unnamed repository.'
362
363 =head1 DESCRIPTION
364
365 This class models a git repository, referred to in Gitalist
366 as a "Repository".
367
368
369 =head1 ATTRIBUTES
370
371 =head2 name
372
373 The name of the Repository.  If unspecified, this will be derived from the path to the git repository.
374
375 =head2 path
376
377 L<Path::Class:Dir> for the filesystem path to the git repository.
378
379 =head2 description
380
381 The contents of .git/description.
382
383 =head2 owner
384
385 Owner of the files on the filesystem.
386
387 =head2 last_change
388
389 The L<DateTime> of the last modification of the repository.  This will be C<undef> if the repository has never been used.
390
391 =head2 is_bare
392
393 True if this is a bare git repository.
394
395 =head2 heads
396
397 =head2 tags
398
399 An array of the name and sha1 of all heads/tags in the repository.
400
401 =head2 references
402
403 Hashref of ArrayRefs for each reference.
404
405
406 =head1 METHODS
407
408 =head2 head_hash ($head?)
409
410 Return the sha1 for HEAD, or any specified head.
411
412 =head2 list_tree ($sha1?)
413
414 Return an array of contents for a given tree.
415 The tree is specified by sha1, and defaults to HEAD.
416 Each item is a L<Gitalist::Git::Object>.
417
418 =head2 get_object ($sha1)
419
420 Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
421
422 =head2 hash_by_path ($sha1, $path, $type?)
423
424 Returns the sha1 for a given path, optionally limited by type.
425
426 =head2 list_revs ($sha1, $count?, $skip?, \%search?, $file?)
427
428 Returns a list of revs for the given head ($sha1).
429
430 =head2 snapshot ($sha1, $format)
431
432 Generate an archived snapshot of the repository.
433 $sha1 should be a commit or tree.
434 Returns a filehandle to read from.
435
436 =head2 diff ($commit, $patch?, $parent?, $file?)
437
438 Generate a diff from a given L<Gitalist::Git::Object>.
439
440 =head2 reflog (@lorgargs)
441
442 Return a list of hashes representing each reflog entry.
443
444 FIXME Should this return objects?
445
446
447 =head1 SEE ALSO
448
449 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
450
451
452 =head1 AUTHORS
453
454 See L<Gitalist> for authors.
455
456 =head1 LICENSE
457
458 See L<Gitalist> for the license.
459
460 =cut