Relocate diff method from ::Project to ::Object.
[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         # Allows us to be called as Project->new($dir)
35         # Last path component becomes $self->name
36         # Full path to git objects becomes $self->path
37         my $name = $dir->dir_list(-1);
38         $dir = $dir->subdir('.git') if (-f $dir->file('.git', 'HEAD'));
39         confess("Can't find a git repository at " . $dir)
40             unless ( -f $dir->file('HEAD') );
41         return $class->$orig(name => $name,
42                              path => $dir);
43     }
44
45 =head1 ATTRIBUTES
46
47 =head2 name
48
49 The name of the Project.  By default, this is derived from the path to the git repository.
50
51 =cut
52     has name => ( isa => NonEmptySimpleStr,
53                   is => 'ro', required => 1 );
54
55 =head2 path
56
57 L<Path::Class:Dir> for the location of the git repository.
58
59 =cut
60     has path => ( isa => Dir,
61                   is => 'ro', required => 1);
62
63 =head2 description
64
65 String containing .git/description
66
67 =cut
68     has description => ( isa => Str,
69                          is => 'ro',
70                          lazy_build => 1,
71                      );
72
73 =head2 owner
74
75 Owner of the files on disk.
76
77 =cut
78     has owner => ( isa => NonEmptySimpleStr,
79                    is => 'ro',
80                    lazy_build => 1,
81                );
82
83 =head2 last_change
84
85 L<DateTime> for the time of the last update.
86 undef if the repository has never been used.
87
88 =cut
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     has is_bare => ( isa => Bool,
100                      is => 'ro',
101                      lazy => 1,
102                      default => sub {
103                          -d $_[0]->path->parent->subdir->($_[0]->name)
104                              ? 1 : 0
105                          },
106                      );
107
108 =head2 heads
109
110 ArrayRef of hashes containing the name and sha1 of all heads.
111
112 =cut
113     has heads => ( isa => ArrayRef[HashRef],
114                    is => 'ro',
115                    lazy_build => 1);
116
117 =head2 references
118
119 Hashref of ArrayRefs for each reference.
120
121 =cut
122     has references => ( isa => HashRef[ArrayRef[Str]],
123                         is => 'ro',
124                         lazy_build => 1 );
125
126     method BUILD {
127         $self->$_() for qw/last_change owner description/; # Ensure to build early.
128     }
129
130 =head1 METHODS
131
132 =head2 head_hash ($head?)
133
134 Return the sha1 for HEAD, or any specified head.
135
136 =cut
137     method head_hash (Str $head?) {
138         my $output = $self->run_cmd(qw/rev-parse --verify/, $head || 'HEAD' );
139         confess("No such head: " . $head) unless defined $output;
140
141         my($sha1) = $output =~ /^($SHA1RE)$/;
142         return $sha1;
143     }
144
145 =head2 list_tree ($sha1?)
146
147 Return an array of contents for a given tree.
148 The tree is specified by sha1, and defaults to HEAD.
149 Each item is a L<Gitalist::Git::Object>.
150
151 =cut
152     method list_tree (Str $sha1?) {
153         $sha1 ||= $self->head_hash;
154
155         my $output = $self->run_cmd(qw/ls-tree -z/, $sha1);
156         return unless defined $output;
157
158         my @ret;
159         for my $line (split /\0/, $output) {
160             my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
161             push @ret, Object->new( mode => oct $mode,
162                                     type => $type,
163                                     sha1 => $object,
164                                     file => $file,
165                                     project => $self,
166                                   );
167         }
168         return @ret;
169     }
170
171 =head2 get_object ($sha1)
172
173 Return a L<Gitalist::Git::Object> for the given sha1.
174
175 =cut
176     method get_object (NonEmptySimpleStr $sha1) {
177         unless ( $self->_is_valid_rev($sha1) ) {
178             $sha1 = $self->head_hash($sha1);
179         }
180         return Object->new(
181             project => $self,
182             sha1 => $sha1,
183         );
184     }
185
186 =head2 hash_by_path($sha1, $path, $type?)
187
188 Returns the sha1 for a given path, optionally limited by type.
189
190 =cut
191     method hash_by_path ($base, $path = '', $type?) {
192         $path =~ s{/+$}();
193         # FIXME should this really just take the first result?
194         my @paths = $self->run_cmd('ls-tree', $base, '--', $path)
195             or return;
196         my $line = $paths[0];
197
198         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
199         $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
200         return defined $type && $type ne $2
201             ? ()
202                 : $3;
203     }
204
205 =head2 list_revs($sha1, $count?, $skip?, \%search?, $file?)
206
207 Returns a list of revs for the given head ($sha1).
208
209 =cut
210     method list_revs ( NonEmptySimpleStr :$sha1!,
211                        Int :$count?,
212                        Int :$skip?,
213                        HashRef :$search?,
214                        NonEmptySimpleStr :$file?
215                    ) {
216         $sha1 = $self->head_hash($sha1)
217             if !$sha1 || $sha1 !~ $SHA1RE;
218
219         my @search_opts;
220         if($search) {
221             $search->{type} = 'grep'
222                 if $search->{type} eq 'commit';
223             @search_opts = (
224                 # This seems a little fragile ...
225                 qq[--$search->{type}=$search->{text}],
226                 '--regexp-ignore-case',
227                 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
228             );
229         }
230
231         my $output = $self->run_cmd(
232             'rev-list',
233             '--header',
234             (defined $count ? "--max-count=$count" : ()),
235             (defined $skip ? "--skip=$skip"       : ()),
236             @search_opts,
237             $sha1,
238             '--',
239             ($file ? $file : ()),
240         );
241         return unless $output;
242
243         my @revs = $self->_parse_rev_list($output);
244
245         return @revs;
246     }
247
248 =head2 diff($commit, $patch?, $parent?, $file?)
249
250 Generate a diff from a given L<Gitalist::Git::Object>.
251
252 =cut
253
254     method diff ( Gitalist::Git::Object :$commit!,
255                   Bool :$patch?,
256                   Maybe[NonEmptySimpleStr] :$parent?,
257                   NonEmptySimpleStr :$file?
258               ) {
259               return $commit->diff( patch => $patch,
260                                     parent => $parent,
261                                     file => $file);
262     }
263
264 =head2 reflog(@lorgargs)
265
266 Return a list of hashes representing each reflog entry.
267
268 FIXME Should this return objects?
269
270 =cut
271     method reflog (@logargs) {
272         my @entries
273             =  $self->run_cmd(qw(log -g), @logargs)
274                 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
275
276 #  commit 02526fc15beddf2c64798a947fecdd8d11bf993d
277 #  Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
278 #  Reflog message: push
279 #  Author: Foo Barsby <fbarsby@example.com>
280 #  Date:   Thu Sep 17 12:26:05 2009 +0100
281 #
282 #      Merge branch 'abc123'
283
284         return map {
285             # XXX Stuff like this makes me want to switch to Git::PurePerl
286             my($sha1, $type, $author, $date)
287                 = m{
288                        ^ commit \s+ ($SHA1RE)$
289                        .*?
290                        Reflog[ ]message: \s+ (.+?)$ \s+
291                      Author: \s+ ([^<]+) <.*?$ \s+
292                    Date: \s+ (.+?)$
293                }xms;
294
295             pos($_) = index($_, $date) + length $date;
296
297             # Yeah, I just did that.
298             my($msg) = /\G\s+(\S.*)/sg;
299             {
300                 hash    => $sha1,
301                 type    => $type,
302                 author  => $author,
303
304                 # XXX Add DateTime goodness.
305                 date    => $date,
306                 message => $msg,
307             }
308             ;
309         } @entries;
310     }
311
312     ## BUILDERS
313     method _build__util {
314         Gitalist::Git::Util->new(
315             project => $self,
316         );
317     }
318
319     method _build_description {
320         return $self->gpp->description;
321     }
322
323     method _build_owner {
324         my ($gecos, $name) = (getpwuid $self->path->stat->uid)[6,0];
325         $gecos =~ s/,+$//;
326         return length($gecos) ? $gecos : $name;
327     }
328
329     method _build_last_change {
330         my $last_change;
331         my $output = $self->run_cmd(
332             qw{ for-each-ref --format=%(committer)
333                 --sort=-committerdate --count=1 refs/heads
334           });
335         if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
336             my $dt = DateTime->from_epoch(epoch => $epoch);
337             $dt->set_time_zone($tz);
338             $last_change = $dt;
339         }
340         return $last_change;
341     }
342
343     method _build_heads {
344         my @revlines = $self->run_cmd_list(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
345         my @ret;
346         for my $line (@revlines) {
347             my ($rev, $head, $commiter) = split /\0/, $line, 3;
348             $head =~ s!^refs/heads/!!;
349
350             push @ret, { sha1 => $rev, name => $head };
351
352             #FIXME: That isn't the time I'm looking for..
353             if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
354                 my $dt = DateTime->from_epoch(epoch => $epoch);
355                 $dt->set_time_zone($tz);
356                 $ret[-1]->{last_change} = $dt;
357             }
358         }
359
360         return \@ret;
361     }
362
363     method _build_references {
364         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
365         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
366         my @reflist = $self->run_cmd_list(qw(show-ref --dereference))
367                 or return;
368         my %refs;
369             for(@reflist) {
370                     push @{$refs{$1}}, $2
371                             if m!^($SHA1RE)\srefs/(.*)$!;
372             }
373
374             return \%refs;
375     }
376
377     ## Private methods
378     method _is_valid_rev (Str $rev) {
379         return ($rev =~ /^($SHA1RE)$/);
380     }
381
382     method _parse_rev_list ($output) {
383         return
384             map  $self->get_gpp_object($_),
385                 grep $self->_is_valid_rev($_),
386                     map  split(/\n/, $_, 6), split /\0/, $output;
387     }
388
389 =head1 SEE ALSO
390
391 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
392
393 =head1 AUTHORS AND COPYRIGHT
394
395   Catalyst application:
396     (C) 2009 Venda Ltd and Dan Brook <dbrook@venda.com>
397
398   Original gitweb.cgi from which this was derived:
399     (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
400     (C) 2005, Christian Gierke
401
402 =head1 LICENSE
403
404 FIXME - Is this going to be GPLv2 as per gitweb? If so this is broken..
405
406 This library is free software. You can redistribute it and/or modify
407 it under the same terms as Perl itself.
408
409 =cut
410
411 } # end class