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