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