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