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