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