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