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