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