Trivial comment change.
[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/;
27     use List::MoreUtils qw/any zip/;
28     use DateTime;
29     use aliased 'Gitalist::Git::Object';
30
31 =head1 ATTRIBUTES
32
33 =head2 name
34
35 =cut
36
37     has name => ( isa => NonEmptySimpleStr,
38                   is => 'ro', required => 1 );
39
40 =head2 path
41
42 L<Path::Class:Dir> for the location of the git repository.
43
44 =cut
45
46     has path => ( isa => Dir,
47                   is => 'ro', required => 1);
48
49 =head2 description
50
51 String containing .git/description
52
53 =cut
54
55     has description => ( isa => Str,
56                          is => 'ro',
57                          lazy_build => 1,
58                      );
59
60 =head2 owner
61
62 Owner of the files on disk.
63
64 =cut
65
66     has owner => ( isa => NonEmptySimpleStr,
67                    is => 'ro',
68                    lazy_build => 1,
69                );
70
71 =head2 last_change
72
73 L<DateTime> for the time of the last update.
74 undef if the repository has never been used.
75
76 =cut
77
78     has last_change => ( isa => Maybe['DateTime'],
79                          is => 'ro',
80                          lazy_build => 1,
81                      );
82
83 =head2 is_bare
84
85 Bool indicating whether this Project is bare.
86
87 =cut
88
89     has is_bare => ( isa => Bool,
90                      is => 'ro',
91                      lazy => 1,
92                      default => sub {
93                          -d $_[0]->path->parent->subdir->($_[0]->name)
94                              ? 1 : 0
95                          },
96                      );
97
98     method BUILD {
99         $self->$_() for qw/last_change owner description/; # Ensure to build early.
100     }
101
102     around BUILDARGS (ClassName $class: Dir $dir) {
103         # Allows us to be called as Project->new($dir)
104         # Last path component becomes $self->name
105         # Full path to git objects becomes $self->path
106         my $name = $dir->dir_list(-1);
107         $dir = $dir->subdir('.git') if (-f $dir->file('.git', 'HEAD'));
108         confess("Can't find a git repository at " . $dir)
109             unless ( -f $dir->file('HEAD') );
110         return $class->$orig(name => $name,
111                              path => $dir);
112     }
113
114     method _build__util {
115         Gitalist::Git::Util->new(
116             project => $self,
117         );
118     }
119
120     our $SHA1RE = qr/[0-9a-fA-F]{40}/;
121
122     method _build_description {
123         my $description = "";
124         eval {
125             $description = $self->{path}->file('description')->slurp;
126             chomp $description;
127         };
128         return $description;
129     }
130
131     method _build_owner {
132         my ($gecos, $name) = (getpwuid $self->{path}->stat->uid)[6,0];
133         $gecos =~ s/,+$//;
134         return length($gecos) ? $gecos : $name;
135     }
136
137     method _build_last_change {
138         my $last_change;
139         my $output = $self->run_cmd(
140             qw{ for-each-ref --format=%(committer)
141                 --sort=-committerdate --count=1 refs/heads
142           });
143         if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
144             my $dt = DateTime->from_epoch(epoch => $epoch);
145             $dt->set_time_zone($tz);
146             $last_change = $dt;
147         }
148         return $last_change;
149     }
150
151 =head2 heads
152
153 Return an array containing the list of heads.
154
155 =cut
156
157     method heads {
158         my $cmdout = $self->run_cmd(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
159         my @output = $cmdout ? split(/\n/, $cmdout) : ();
160         my @ret;
161         for my $line (@output) {
162             my ($rev, $head, $commiter) = split /\0/, $line, 3;
163             $head =~ s!^refs/heads/!!;
164
165             push @ret, { sha1 => $rev, name => $head };
166
167             #FIXME: That isn't the time I'm looking for..
168             if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
169                 my $dt = DateTime->from_epoch(epoch => $epoch);
170                 $dt->set_time_zone($tz);
171                 $ret[-1]->{last_change} = $dt;
172             }
173         }
174
175         return @ret;
176     }
177
178 =head2 references
179
180 Return a hash of references.
181
182 =cut
183
184     method references {
185         return $self->{references}
186                 if $self->{references};
187
188         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
189         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
190         my $cmdout = $self->run_cmd(qw(show-ref --dereference))
191                 or return;
192         my @reflist = $cmdout ? split(/\n/, $cmdout) : ();
193         my %refs;
194         for(@reflist) {
195                 push @{$refs{$1}}, $2
196                         if m!^($SHA1RE)\srefs/(.*)$!;
197         }
198
199         return $self->{references} = \%refs;
200 }
201
202 =head2 head_hash
203
204 Find the hash of a given head (defaults to HEAD).
205
206 =cut
207
208     method head_hash (Str $head?) {
209         my $output = $self->run_cmd(qw/rev-parse --verify/, $head || 'HEAD' );
210         return unless defined $output;
211
212         my($sha1) = $output =~ /^($SHA1RE)$/;
213         return $sha1;
214     }
215
216 =head2 list_tree
217
218 Return an array of contents for a given tree.
219 The tree is specified by sha1, and defaults to HEAD.
220 The keys for each item will be:
221
222         mode
223         type
224         object
225         file
226
227 =cut
228
229     method list_tree (Str $sha1?) {
230         $sha1 ||= $self->head_hash;
231
232         my $output = $self->run_cmd(qw/ls-tree -z/, $sha1);
233         return unless defined $output;
234
235         my @ret;
236         for my $line (split /\0/, $output) {
237             my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
238             push @ret, Object->new( mode => oct $mode,
239                                     type => $type,
240                                     sha1 => $object,
241                                     file => $file,
242                                     project => $self,
243                                   );
244         }
245         return @ret;
246     }
247
248     method get_object (NonEmptySimpleStr $sha1) {
249         unless ( $self->_is_valid_rev($sha1) ) {
250             $sha1 = $self->head_hash($sha1);
251         }
252         return Object->new(
253             project => $self,
254             sha1 => $sha1,
255         );
256     }
257
258     method _is_valid_rev (Str $rev) {
259         return ($rev =~ /^($SHA1RE)$/);
260     }
261
262     # Should be in ::Object
263     method get_object_mode_string (Gitalist::Git::Object $object) {
264         return $object->modestr;
265     }
266
267     method get_object_type (NonEmptySimpleStr $sha1) {
268         return $self->get_object($sha1)->type;
269     }
270
271     method cat_file (NonEmptySimpleStr $sha1) {
272         return $self->get_object($sha1)->contents;
273     }
274
275     method hash_by_path ($base, $path?, $type?) {
276         $path ||= '';
277         $path =~ s{/+$}();
278
279         my $output = $self->run_cmd('ls-tree', $base, '--', $path)
280             or return;
281         my($line) = $output ? split(/\n/, $output) : ();
282
283         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
284         $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
285         return defined $type && $type ne $2
286             ? ()
287                 : $3;
288     }
289
290     method list_revs ( NonEmptySimpleStr :$sha1!,
291                        Int :$count?,
292                        Int :$skip?,
293                        HashRef :$search?,
294                        NonEmptySimpleStr :$file?
295                    ) {
296         $sha1 = $self->head_hash($sha1)
297             if !$sha1 || $sha1 !~ $SHA1RE;
298
299         my @search_opts;
300         if($search) {
301             $search->{type} = 'grep'
302                 if $search->{type} eq 'commit';
303             @search_opts = (
304                 # This seems a little fragile ...
305                 qq[--$search->{type}=$search->{text}],
306                 '--regexp-ignore-case',
307                 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
308             );
309         }
310
311         my $output = $self->run_cmd(
312             'rev-list',
313             '--header',
314             (defined $count ? "--max-count=$count" : ()),
315             (defined $skip ? "--skip=$skip"       : ()),
316             @search_opts,
317             $sha1,
318             '--',
319             ($file ? $file : ()),
320         );
321         return unless $output;
322
323         my @revs = $self->parse_rev_list($output);
324
325         return @revs;
326     }
327
328     method parse_rev_list ($output) {
329         return
330             map  $self->get_gpp_object($_),
331                 grep $self->_is_valid_rev($_),
332                     map  split(/\n/, $_, 6), split /\0/, $output;
333     }
334
335     # XXX Ideally this would return a wee object instead of ad hoc structures.
336     method diff ( Gitalist::Git::Object :$commit,
337                   Bool :$patch?,
338                   Maybe[NonEmptySimpleStr] :$parent?,
339                   NonEmptySimpleStr :$file? ) {
340         # Use parent if specifed, else take the parent from the commit
341         # if there is only one, otherwise it was a merge commit.
342         $parent = $parent
343             ? $parent
344             : $commit->parents <= 1
345             ? $commit->parent_sha1
346             : '-c';
347         my @etc = (
348             ( $file  ? ('--', $file) : () ),
349         );
350
351         my @out = $self->raw_diff(
352             ( $patch ? '--patch-with-raw' : () ),
353             ( $parent ? $parent : () ),
354             $commit->sha1, @etc,
355         );
356
357         # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
358         my @difftree = $self->parse_diff_tree(\@out);
359
360         return \@difftree
361             unless $patch;
362
363         # The blank line between the tree and the patch.
364         shift @out;
365
366         # XXX And no I'm not happy about having diff return tree + patch.
367         return \@difftree, [$self->parse_diff(@out)];
368     }
369
370     method parse_diff (@diff) {
371         my @ret;
372         for (@diff) {
373             # This regex is a little pathological.
374             if(m{^diff --git (a/(.*?)) (b/\2)}) {
375                 push @ret, {
376                     head => $_,
377                     a    => $1,
378                     b    => $3,
379                     file => $2,
380                     diff => '',
381                 };
382                 next;
383             }
384
385             if(/^index (\w+)\.\.(\w+) (\d+)$/) {
386                 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
387                 next
388             }
389
390             # XXX Somewhat hacky. Ahem.
391             $ret[@ret ? -1 : 0]{diff} .= "$_\n";
392         }
393
394         return @ret;
395     }
396
397     # gitweb uses the following sort of command for diffing merges:
398 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index --cc 316cf158df3f6207afbae7270bcc5ba0 --
399 # and for regular diffs
400 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index 2e3454ca0749641b42f063730b0090e1 316cf158df3f6207afbae7270bcc5ba0 --
401
402     method raw_diff (@args) {
403         my $cmdout = $self->run_cmd(
404             qw(diff-tree -r -M --no-commit-id --full-index),
405             @args
406         );
407         return $cmdout ? split(/\n/, $cmdout) : ();
408     }
409
410     method parse_diff_tree ($diff) {
411         my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
412         my @ret;
413         while (@$diff and $diff->[0] =~ /^:\d+/) {
414             my $line = shift @$diff;
415             # see. man git-diff-tree for more info
416             # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
417             my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
418             my %line = zip @keys, @vals;
419             # Some convenience keys
420             $line{file}   = $line{src};
421             $line{sha1}   = $line{sha1dst};
422             $line{is_new} = $line{sha1src} =~ /^0+$/
423                 if $line{sha1src};
424             @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
425                 if $line{status} =~ /^R/;
426             push @ret, \%line;
427         }
428
429         return @ret;
430     }
431
432     method reflog (@logargs) {
433         my @entries
434             =  $self->run_cmd(qw(log -g), @logargs)
435                 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
436
437 =pod
438   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
439   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
440   Reflog message: push
441   Author: Foo Barsby <fbarsby@example.com>
442   Date:   Thu Sep 17 12:26:05 2009 +0100
443
444       Merge branch 'abc123'
445
446 =cut
447
448         return map {
449             # XXX Stuff like this makes me want to switch to Git::PurePerl
450             my($sha1, $type, $author, $date)
451                 = m{
452                        ^ commit \s+ ($SHA1RE)$
453                        .*?
454                        Reflog[ ]message: \s+ (.+?)$ \s+
455                      Author: \s+ ([^<]+) <.*?$ \s+
456                    Date: \s+ (.+?)$
457                }xms;
458
459             pos($_) = index($_, $date) + length $date;
460
461             # Yeah, I just did that.
462             my($msg) = /\G\s+(\S.*)/sg;
463             {
464                 hash    => $sha1,
465                 type    => $type,
466                 author  => $author,
467
468                 # XXX Add DateTime goodness.
469                 date    => $date,
470                 message => $msg,
471             }
472             ;
473         } @entries;
474     }
475
476     # Compatibility
477
478 =head2 info
479
480 Returns a hash containing properties of this project. The keys will
481 be:
482
483         name
484         description (empty if .git/description is empty/unnamed)
485         owner
486         last_change
487
488 =cut
489
490     method info {
491         return {
492             name => $self->name,
493             description => $self->description,
494             owner => $self->owner,
495             last_change => $self->last_change,
496         };
497     };
498
499 =head1 SEE ALSO
500
501 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
502
503 =head1 AUTHORS AND COPYRIGHT
504
505   Catalyst application:
506     (C) 2009 Venda Ltd and Dan Brook <dbrook@venda.com>
507
508   Original gitweb.cgi from which this was derived:
509     (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
510     (C) 2005, Christian Gierke
511
512 =head1 LICENSE
513
514 FIXME - Is this going to be GPLv2 as per gitweb? If so this is broken..
515
516 This library is free software. You can redistribute it and/or modify
517 it under the same terms as Perl itself.
518
519 =cut
520
521 } # end class