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