Add a branch to the test repository.
[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/;
77edf882 27 use List::MoreUtils qw/any zip/;
b5b638f7 28 use DateTime;
a8a8f8f9 29 use aliased 'Gitalist::Git::Object';
56b6dbe6 30
b5b638f7 31=head1 ATTRIBUTES
32
33=head2 name
34
35=cut
29debefd 36
56b6dbe6 37 has name => ( isa => NonEmptySimpleStr,
01ced85b 38 is => 'ro', required => 1 );
b5b638f7 39
40=head2 path
41
42L<Path::Class:Dir> for the location of the git repository.
43
44=cut
45
84f31a44 46 has path => ( isa => Dir,
01ced85b 47 is => 'ro', required => 1);
56b6dbe6 48
b5b638f7 49=head2 description
50
51String containing .git/description
52
53=cut
54
0617cbd0 55 has description => ( isa => Str,
56b6dbe6 56 is => 'ro',
57 lazy_build => 1,
58 );
b5b638f7 59
60=head2 owner
61
62Owner of the files on disk.
63
64=cut
65
56b6dbe6 66 has owner => ( isa => NonEmptySimpleStr,
67 is => 'ro',
68 lazy_build => 1,
69 );
b5b638f7 70
71=head2 last_change
72
73L<DateTime> for the time of the last update.
74undef if the repository has never been used.
75
76=cut
77
0617cbd0 78 has last_change => ( isa => Maybe['DateTime'],
56b6dbe6 79 is => 'ro',
80 lazy_build => 1,
81 );
82
b5b638f7 83=head2 is_bare
84
85Bool indicating whether this Project is bare.
86
87=cut
88
89 has is_bare => ( isa => Bool,
90 is => 'ro',
91 lazy => 1,
92 default => sub {
93 -d $_[0]->path->parent->subdir->($_[0]->name)
94 ? 1 : 0
95 },
96 );
84f31a44 97
01ced85b 98 method BUILD {
38b9e5c8 99 $self->$_() for qw/last_change owner description/; # Ensure to build early.
01ced85b 100 }
101
b5b638f7 102 around BUILDARGS (ClassName $class: Dir $dir) {
103 my $name = $dir->dir_list(-1);
104 $dir = $dir->subdir('.git') if (-f $dir->file('.git', 'HEAD'));
105 confess("Can't find a git repository at " . $dir)
106 unless ( -f $dir->file('HEAD') );
107 return $class->$orig(name => $name,
108 path => $dir);
8dbe8024 109 }
110
941bb5a1 111 method _build__util {
255ee743 112 Gitalist::Git::Util->new(
84f31a44 113 project => $self,
941bb5a1 114 );
941bb5a1 115 }
894bff59 116
b5b638f7 117 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
894bff59 118
56b6dbe6 119 method _build_description {
4ce9e8a0 120 my $description = "";
d9a9b56b 121 eval {
b719ff6a 122 $description = $self->path->file('description')->slurp;
d9a9b56b 123 chomp $description;
124 };
56b6dbe6 125 return $description;
126 }
127
128 method _build_owner {
b719ff6a 129 my ($gecos, $name) = (getpwuid $self->path->stat->uid)[6,0];
263e2578 130 $gecos =~ s/,+$//;
131 return length($gecos) ? $gecos : $name;
56b6dbe6 132 }
29debefd 133
56b6dbe6 134 method _build_last_change {
135 my $last_change;
136 my $output = $self->run_cmd(
137 qw{ for-each-ref --format=%(committer)
138 --sort=-committerdate --count=1 refs/heads
139 });
140 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
141 my $dt = DateTime->from_epoch(epoch => $epoch);
142 $dt->set_time_zone($tz);
143 $last_change = $dt;
144 }
145 return $last_change;
146 }
147
894bff59 148=head2 heads
149
150Return an array containing the list of heads.
151
152=cut
153
8dbe8024 154 method heads {
155 my $cmdout = $self->run_cmd(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
156 my @output = $cmdout ? split(/\n/, $cmdout) : ();
157 my @ret;
158 for my $line (@output) {
159 my ($rev, $head, $commiter) = split /\0/, $line, 3;
160 $head =~ s!^refs/heads/!!;
161
162 push @ret, { sha1 => $rev, name => $head };
163
164 #FIXME: That isn't the time I'm looking for..
165 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
166 my $dt = DateTime->from_epoch(epoch => $epoch);
167 $dt->set_time_zone($tz);
168 $ret[-1]->{last_change} = $dt;
169 }
170 }
171
172 return @ret;
173 }
174
894bff59 175=head2 references
176
177Return a hash of references.
178
179=cut
180
829d41ed 181 has references => ( isa => HashRef[ArrayRef[Str]], is => 'ro', lazy_build => 1 );
4111e151 182
b719ff6a 183 method _build_references {
4111e151 184
b719ff6a 185 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
186 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
187 my $cmdout = $self->run_cmd(qw(show-ref --dereference))
188 or return;
189 my @reflist = $cmdout ? split(/\n/, $cmdout) : ();
190 my %refs;
191 for(@reflist) {
192 push @{$refs{$1}}, $2
193 if m!^($SHA1RE)\srefs/(.*)$!;
194 }
195
196 return \%refs;
197 }
4111e151 198
4baaeeef 199=head2 head_hash
200
201Find the hash of a given head (defaults to HEAD).
202
203=cut
204
205 method head_hash (Str $head?) {
206 my $output = $self->run_cmd(qw/rev-parse --verify/, $head || 'HEAD' );
207 return unless defined $output;
208
209 my($sha1) = $output =~ /^($SHA1RE)$/;
210 return $sha1;
211 }
212
a8a8f8f9 213=head2 list_tree
214
215Return an array of contents for a given tree.
216The tree is specified by sha1, and defaults to HEAD.
217The keys for each item will be:
218
219 mode
220 type
221 object
222 file
223
224=cut
225
226 method list_tree (Str $sha1?) {
227 $sha1 ||= $self->head_hash;
228
229 my $output = $self->run_cmd(qw/ls-tree -z/, $sha1);
230 return unless defined $output;
231
232 my @ret;
233 for my $line (split /\0/, $output) {
234 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
235 push @ret, Object->new( mode => oct $mode,
236 type => $type,
237 sha1 => $object,
238 file => $file,
50394a3e 239 project => $self,
a8a8f8f9 240 );
241 }
242 return @ret;
243 }
244
8bb7649b 245 method get_object (NonEmptySimpleStr $sha1) {
894bff59 246 unless ( $self->_is_valid_rev($sha1) ) {
8bb7649b 247 $sha1 = $self->head_hash($sha1);
248 }
77edf882 249 return Object->new(
54368e9d 250 project => $self,
251 sha1 => $sha1,
252 );
253 }
8bb7649b 254
894bff59 255 method _is_valid_rev (Str $rev) {
256 return ($rev =~ /^($SHA1RE)$/);
257 }
258
54368e9d 259 # Should be in ::Object
260 method get_object_mode_string (Gitalist::Git::Object $object) {
894bff59 261 return $object->modestr;
54368e9d 262 }
263
894bff59 264 method get_object_type (NonEmptySimpleStr $sha1) {
265 return $self->get_object($sha1)->type;
54368e9d 266 }
267
894bff59 268 method cat_file (NonEmptySimpleStr $sha1) {
269 return $self->get_object($sha1)->contents;
54368e9d 270 }
271
272 method hash_by_path ($base, $path?, $type?) {
273 $path ||= '';
274 $path =~ s{/+$}();
275
276 my $output = $self->run_cmd('ls-tree', $base, '--', $path)
277 or return;
278 my($line) = $output ? split(/\n/, $output) : ();
279
280 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
281 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
282 return defined $type && $type ne $2
283 ? ()
284 : $3;
285 }
286
4111e151 287 method list_revs ( NonEmptySimpleStr :$sha1!,
288 Int :$count?,
289 Int :$skip?,
290 HashRef :$search?,
291 NonEmptySimpleStr :$file?
292 ) {
293 $sha1 = $self->head_hash($sha1)
294 if !$sha1 || $sha1 !~ $SHA1RE;
295
296 my @search_opts;
297 if($search) {
298 $search->{type} = 'grep'
299 if $search->{type} eq 'commit';
300 @search_opts = (
301 # This seems a little fragile ...
302 qq[--$search->{type}=$search->{text}],
303 '--regexp-ignore-case',
304 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
305 );
306 }
307
308 my $output = $self->run_cmd(
309 'rev-list',
310 '--header',
311 (defined $count ? "--max-count=$count" : ()),
312 (defined $skip ? "--skip=$skip" : ()),
313 @search_opts,
314 $sha1,
315 '--',
316 ($file ? $file : ()),
317 );
318 return unless $output;
319
320 my @revs = $self->parse_rev_list($output);
321
322 return @revs;
323 }
324
325 method parse_rev_list ($output) {
326 return
327 map $self->get_gpp_object($_),
894bff59 328 grep $self->_is_valid_rev($_),
4111e151 329 map split(/\n/, $_, 6), split /\0/, $output;
330 }
54368e9d 331
77edf882 332 # XXX Ideally this would return a wee object instead of ad hoc structures.
333 method diff ( Gitalist::Git::Object :$commit,
334 Bool :$patch?,
fc948aee 335 Maybe[NonEmptySimpleStr] :$parent?,
77edf882 336 NonEmptySimpleStr :$file? ) {
337 # Use parent if specifed, else take the parent from the commit
338 # if there is only one, otherwise it was a merge commit.
339 $parent = $parent
340 ? $parent
341 : $commit->parents <= 1
342 ? $commit->parent_sha1
343 : '-c';
344 my @etc = (
345 ( $file ? ('--', $file) : () ),
346 );
347
348 my @out = $self->raw_diff(
ba65bc52 349 ( $patch ? '--patch-with-raw' : () ),
66a82e01 350 ( $parent ? $parent : () ),
351 $commit->sha1, @etc,
77edf882 352 );
353
354 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
355 my @difftree = $self->parse_diff_tree(\@out);
356
357 return \@difftree
358 unless $patch;
359
360 # The blank line between the tree and the patch.
361 shift @out;
362
363 # XXX And no I'm not happy about having diff return tree + patch.
364 return \@difftree, [$self->parse_diff(@out)];
365 }
366
367 method parse_diff (@diff) {
368 my @ret;
369 for (@diff) {
370 # This regex is a little pathological.
371 if(m{^diff --git (a/(.*?)) (b/\2)}) {
372 push @ret, {
373 head => $_,
374 a => $1,
375 b => $3,
376 file => $2,
377 diff => '',
378 };
379 next;
380 }
381
382 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
383 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
384 next
385 }
386
387 # XXX Somewhat hacky. Ahem.
388 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
389 }
390
391 return @ret;
392 }
393
394 # gitweb uses the following sort of command for diffing merges:
395# /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index --cc 316cf158df3f6207afbae7270bcc5ba0 --
396# and for regular diffs
397# /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index 2e3454ca0749641b42f063730b0090e1 316cf158df3f6207afbae7270bcc5ba0 --
398
399 method raw_diff (@args) {
400 my $cmdout = $self->run_cmd(
401 qw(diff-tree -r -M --no-commit-id --full-index),
402 @args
403 );
404 return $cmdout ? split(/\n/, $cmdout) : ();
405 }
406
407 method parse_diff_tree ($diff) {
408 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
409 my @ret;
410 while (@$diff and $diff->[0] =~ /^:\d+/) {
411 my $line = shift @$diff;
412 # see. man git-diff-tree for more info
413 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
414 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
415 my %line = zip @keys, @vals;
416 # Some convenience keys
417 $line{file} = $line{src};
418 $line{sha1} = $line{sha1dst};
419 $line{is_new} = $line{sha1src} =~ /^0+$/
420 if $line{sha1src};
421 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
422 if $line{status} =~ /^R/;
423 push @ret, \%line;
424 }
425
426 return @ret;
427 }
54368e9d 428
d8abdf1c 429 method reflog (@logargs) {
430 my @entries
431 = $self->run_cmd(qw(log -g), @logargs)
432 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
433
b719ff6a 434# commit 02526fc15beddf2c64798a947fecdd8d11bf993d
435# Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
436# Reflog message: push
437# Author: Foo Barsby <fbarsby@example.com>
438# Date: Thu Sep 17 12:26:05 2009 +0100
439#
440# Merge branch 'abc123'
d8abdf1c 441
442 return map {
443 # XXX Stuff like this makes me want to switch to Git::PurePerl
444 my($sha1, $type, $author, $date)
445 = m{
446 ^ commit \s+ ($SHA1RE)$
447 .*?
448 Reflog[ ]message: \s+ (.+?)$ \s+
449 Author: \s+ ([^<]+) <.*?$ \s+
450 Date: \s+ (.+?)$
451 }xms;
452
453 pos($_) = index($_, $date) + length $date;
454
455 # Yeah, I just did that.
456 my($msg) = /\G\s+(\S.*)/sg;
457 {
458 hash => $sha1,
459 type => $type,
460 author => $author,
461
462 # XXX Add DateTime goodness.
463 date => $date,
464 message => $msg,
465 }
466 ;
467 } @entries;
468 }
469
56b6dbe6 470 # Compatibility
471
caba5c95 472=head2 info
56b6dbe6 473
474Returns a hash containing properties of this project. The keys will
475be:
476
477 name
478 description (empty if .git/description is empty/unnamed)
479 owner
480 last_change
481
482=cut
483
caba5c95 484 method info {
56b6dbe6 485 return {
486 name => $self->name,
487 description => $self->description,
488 owner => $self->owner,
489 last_change => $self->last_change,
490 };
491 };
29debefd 492
b5b638f7 493=head1 SEE ALSO
494
495L<Gitalist::Git::Util> L<Gitalist::Git::Object>
496
497=head1 AUTHORS AND COPYRIGHT
498
499 Catalyst application:
500 (C) 2009 Venda Ltd and Dan Brook <dbrook@venda.com>
501
502 Original gitweb.cgi from which this was derived:
503 (C) 2005-2006, Kay Sievers <kay.sievers@vrfy.org>
504 (C) 2005, Christian Gierke
505
506=head1 LICENSE
507
508FIXME - Is this going to be GPLv2 as per gitweb? If so this is broken..
509
510This library is free software. You can redistribute it and/or modify
511it under the same terms as Perl itself.
512
513=cut
514
56b6dbe6 515} # end class