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