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