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