Merge branch 'action-snapshot' of github.com:zts/Gitalist into action-snapshot
[catagits/Gitalist.git] / lib / Gitalist / Git / Project.pm
CommitLineData
56b6dbe6 1use MooseX::Declare;
2
b5b638f7 3=head1 NAME
4
894bff59 5Gitalist::Git::Project - Model of a git repository
b5b638f7 6
7=head1 SYNOPSIS
8
561a3f14 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.'
b5b638f7 14
15=head1 DESCRIPTION
16
17This class models a git repository, referred to in Gitalist
18as a "Project".
19
20=cut
21
38b9e5c8 22class Gitalist::Git::Project with Gitalist::Git::HasUtils {
56b6dbe6 23 # FIXME, use Types::Path::Class and coerce
24 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
84f31a44 25 use MooseX::Types::Path::Class qw/Dir/;
829d41ed 26 use MooseX::Types::Moose qw/Str Maybe Bool HashRef ArrayRef/;
2e79039a 27 use Moose::Autobox;
77edf882 28 use List::MoreUtils qw/any zip/;
b5b638f7 29 use DateTime;
2e79039a 30 use Gitalist::Util qw(to_utf8);
f3083570 31 use Gitalist::Git::Object::Blob;
467fa7d9 32 use Gitalist::Git::Object::Tree;
33 use Gitalist::Git::Object::Commit;
34 use Gitalist::Git::Object::Tag;
56b6dbe6 35
32a371cc 36 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
37
38 around BUILDARGS (ClassName $class: Dir $dir) {
4b6bcf44 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
32a371cc 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
b5b638f7 50=head1 ATTRIBUTES
51
52=head2 name
53
cc88eca5 54The name of the Project. By default, this is derived from the path to the git repository.
29debefd 55
cc88eca5 56=cut
56b6dbe6 57 has name => ( isa => NonEmptySimpleStr,
01ced85b 58 is => 'ro', required => 1 );
b5b638f7 59
60=head2 path
61
62L<Path::Class:Dir> for the location of the git repository.
63
64=cut
84f31a44 65 has path => ( isa => Dir,
01ced85b 66 is => 'ro', required => 1);
56b6dbe6 67
b5b638f7 68=head2 description
69
70String containing .git/description
71
72=cut
0617cbd0 73 has description => ( isa => Str,
56b6dbe6 74 is => 'ro',
75 lazy_build => 1,
76 );
b5b638f7 77
78=head2 owner
79
80Owner of the files on disk.
81
82=cut
56b6dbe6 83 has owner => ( isa => NonEmptySimpleStr,
84 is => 'ro',
85 lazy_build => 1,
86 );
b5b638f7 87
88=head2 last_change
89
90L<DateTime> for the time of the last update.
91undef if the repository has never been used.
92
93=cut
0617cbd0 94 has last_change => ( isa => Maybe['DateTime'],
56b6dbe6 95 is => 'ro',
96 lazy_build => 1,
97 );
98
b5b638f7 99=head2 is_bare
100
101Bool indicating whether this Project is bare.
102
103=cut
b5b638f7 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 );
84f31a44 112
cc88eca5 113=head2 heads
114
115ArrayRef 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
124Hashref of ArrayRefs for each reference.
125
126=cut
127 has references => ( isa => HashRef[ArrayRef[Str]],
128 is => 'ro',
129 lazy_build => 1 );
130
01ced85b 131 method BUILD {
38b9e5c8 132 $self->$_() for qw/last_change owner description/; # Ensure to build early.
01ced85b 133 }
134
32a371cc 135=head1 METHODS
8dbe8024 136
cc88eca5 137=head2 head_hash ($head?)
894bff59 138
32a371cc 139Return the sha1 for HEAD, or any specified head.
894bff59 140
32a371cc 141=cut
32a371cc 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;
29debefd 145
32a371cc 146 my($sha1) = $output =~ /^($SHA1RE)$/;
147 return $sha1;
56b6dbe6 148 }
149
cc88eca5 150=head2 list_tree ($sha1?)
a8a8f8f9 151
152Return an array of contents for a given tree.
153The tree is specified by sha1, and defaults to HEAD.
cc88eca5 154Each item is a L<Gitalist::Git::Object>.
a8a8f8f9 155
156=cut
a8a8f8f9 157 method list_tree (Str $sha1?) {
158 $sha1 ||= $self->head_hash;
b36b7e0b 159 my $object = $self->get_object($sha1);
160 return @{$object->tree};
a8a8f8f9 161 }
162
cc88eca5 163=head2 get_object ($sha1)
164
467fa7d9 165Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
cc88eca5 166
167=cut
8bb7649b 168 method get_object (NonEmptySimpleStr $sha1) {
894bff59 169 unless ( $self->_is_valid_rev($sha1) ) {
8bb7649b 170 $sha1 = $self->head_hash($sha1);
171 }
e1307124 172 my $type = $self->run_cmd('cat-file', '-t', $sha1);
173 chomp($type);
467fa7d9 174 my $class = 'Gitalist::Git::Object::' . ucfirst($type);
175 $class->new(
54368e9d 176 project => $self,
177 sha1 => $sha1,
f3083570 178 type => $type,
54368e9d 179 );
180 }
8bb7649b 181
cc88eca5 182=head2 hash_by_path($sha1, $path, $type?)
894bff59 183
cc88eca5 184Returns the sha1 for a given path, optionally limited by type.
185
186=cut
fc11c7f1 187 method hash_by_path ($base, $path = '', $type?) {
54368e9d 188 $path =~ s{/+$}();
32a371cc 189 # FIXME should this really just take the first result?
190 my @paths = $self->run_cmd('ls-tree', $base, '--', $path)
54368e9d 191 or return;
32a371cc 192 my $line = $paths[0];
54368e9d 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
cc88eca5 201=head2 list_revs($sha1, $count?, $skip?, \%search?, $file?)
202
203Returns a list of revs for the given head ($sha1).
204
205=cut
4111e151 206 method list_revs ( NonEmptySimpleStr :$sha1!,
207 Int :$count?,
208 Int :$skip?,
209 HashRef :$search?,
05e8b4d0 210 NonEmptySimpleStr :$file? ) {
4111e151 211 $sha1 = $self->head_hash($sha1)
212 if !$sha1 || $sha1 !~ $SHA1RE;
213
214 my @search_opts;
05e8b4d0 215 if ($search) {
4111e151 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
cc88eca5 238 my @revs = $self->_parse_rev_list($output);
4111e151 239
240 return @revs;
241 }
242
2e79039a 243=head2 snapshot($sha1, $format)
30db8f5b 244
245Generate an archived snapshot of the repository.
2e79039a 246$sha1 should be a commit or tree.
30db8f5b 247Returns a filehandle to read from.
248
249=cut
250
2e79039a 251method snapshot (NonEmptySimpleStr :$sha1,
30db8f5b 252 NonEmptySimpleStr :$format
253 ) {
2e79039a 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 $self->run_cmd_fh(@cmd);
269 # TODO - support compressed archives
270}
30db8f5b 271
cc88eca5 272=head2 diff($commit, $patch?, $parent?, $file?)
273
1501cb4e 274Generate a diff from a given L<Gitalist::Git::Object>.
cc88eca5 275
276=cut
54368e9d 277
cc88eca5 278 method diff ( Gitalist::Git::Object :$commit!,
77edf882 279 Bool :$patch?,
fc948aee 280 Maybe[NonEmptySimpleStr] :$parent?,
1501cb4e 281 NonEmptySimpleStr :$file?
282 ) {
283 return $commit->diff( patch => $patch,
284 parent => $parent,
285 file => $file);
77edf882 286 }
287
cc88eca5 288=head2 reflog(@lorgargs)
77edf882 289
cc88eca5 290Return a list of hashes representing each reflog entry.
77edf882 291
cc88eca5 292FIXME Should this return objects?
54368e9d 293
cc88eca5 294=cut
d8abdf1c 295 method reflog (@logargs) {
296 my @entries
297 = $self->run_cmd(qw(log -g), @logargs)
298 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
299
05e8b4d0 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'
d8abdf1c 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
cc88eca5 336 ## BUILDERS
32a371cc 337 method _build__util {
338 Gitalist::Git::Util->new(
339 project => $self,
340 );
341 }
342
343 method _build_description {
76c97bf6 344 my $description = "";
5d8568c6 345 eval {
76c97bf6 346 $description = $self->path->file('description')->slurp;
347 chomp $description;
5d8568c6 348 };
76c97bf6 349 return $description;
32a371cc 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
cc88eca5 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))
05e8b4d0 396 or return;
cc88eca5 397 my %refs;
05e8b4d0 398 for (@reflist) {
399 push @{$refs{$1}}, $2
400 if m!^($SHA1RE)\srefs/(.*)$!;
401 }
cc88eca5 402
05e8b4d0 403 return \%refs;
cc88eca5 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
b5b638f7 418=head1 SEE ALSO
419
420L<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
433FIXME - Is this going to be GPLv2 as per gitweb? If so this is broken..
434
435This library is free software. You can redistribute it and/or modify
436it under the same terms as Perl itself.
437
438=cut
439
56b6dbe6 440} # end class