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