Fix bugs with commitdiff
[catagits/Gitalist.git] / lib / Gitalist / Model / Git.pm
1 package Gitalist::Model::Git;
2
3 use Moose;
4 use namespace::autoclean;
5 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
6 use Moose::Autobox;
7
8 extends 'Catalyst::Model';
9 with 'Catalyst::Component::InstancePerContext';
10
11 has repo_dir => ( is => 'ro', required => 1, isa => NonEmptySimpleStr );
12
13 =head1 NAME
14
15 Gitalist::Model::Git - the model for git interactions
16
17 =head1 DESCRIPTION
18
19 [enter your description here]
20
21 =head1 METHODS
22
23 =cut
24
25 use Git::PurePerl;
26 use Path::Class qw/dir/;
27 sub build_per_context_instance {
28   my ( $self, $c ) = @_;
29
30   my $app = blessed($c) || $c;
31   my $model = Git::Repos->new(
32     project => ([$c->req->parameters->{p} || '/']->flatten)[0],
33     repo_dir => $self->repo_dir,
34   );
35
36   # This is fugly as fuck. Move Git::PurePerl construction into attribute builders..
37   my ($pd, $gd) = $model->project_dir( $model->project )->resolve =~ m{((.+?)(:?/\/\.git)?$)};
38   $gd .= '/.git' if ($gd !~ /\.git$/ and -d "$gd/.git");
39   $model->gpp( Git::PurePerl->new(gitdir => $gd, directory => $pd) );
40
41   return $model;
42 }
43
44 __PACKAGE__->meta->make_immutable;
45
46 package Git::Repos; # Better name? Split out into own file once we have a sane name.
47 use Moose;
48 use namespace::autoclean;
49 use DateTime;
50 use Path::Class;
51 use File::Which;
52 use Carp qw/croak/;
53 use File::Find::Rule;
54 use DateTime::Format::Mail;
55 use File::Stat::ModeString;
56 use List::MoreUtils qw/any zip/;
57 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
58
59 use Git::PurePerl;
60
61 # Should these live in a separate module? Or perhaps extended Regexp::Common?
62 # No, should be a MooseX::Types module!!
63 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
64
65 # These are static and only need to be setup on app start.
66 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
67 has git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
68 # These are dynamic and can be different from one request to the next.
69 has project  => ( isa => NonEmptySimpleStr, is => 'rw');
70 has gpp      => ( isa => 'Git::PurePerl',   is => 'rw', lazy_build => 1 );
71
72
73
74 =head2 BUILD
75
76 =cut
77
78 sub BUILD {
79     my ($self) = @_;
80     $self->git; # Cause lazy value build.
81     $self->repo_dir;
82 }
83
84 sub _build_git {
85     my $git = File::Which::which('git');
86
87     if (!$git) {
88         die <<EOR;
89 Could not find a git executable.
90 Please specify the which git executable to use in gitweb.yml
91 EOR
92     }
93
94     return $git;
95 }
96
97 =head2 get_object
98
99 A wrapper for the equivalent L<Git::PurePerl> method.
100
101 =cut
102
103 sub get_object {
104   my($self, $sha1) = @_;
105
106   # We either want an object or undef, *not* an empty list.
107   return $self->gpp->get_object($sha1) || undef;
108 }
109
110 =head2 is_git_repo
111
112 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
113 C<git> repo.
114
115 =cut
116
117 sub is_git_repo {
118   my ($self, $dir) = @_;
119
120   return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
121 }
122
123 =head2 run_cmd
124
125 Call out to the C<git> binary and return a string consisting of the output.
126
127 =cut
128
129 sub run_cmd {
130   my ($self, @args) = @_;
131
132   print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
133
134   open my $fh, '-|', $self->git, @args
135     or die "failed to run git command";
136   binmode $fh, ':encoding(UTF-8)';
137
138   my $output = do { local $/ = undef; <$fh> };
139   close $fh;
140
141   return $output;
142 }
143
144 =head2 project_dir
145
146 The directory under which the given project will reside i.e C<.git/..>
147
148 =cut
149
150 sub project_dir {
151   my($self, $project) = @_;
152
153   my $dir = blessed($project) && $project->isa('Path::Class::Dir')
154        ? $project->stringify
155        : $self->dir_from_project_name($project);
156
157   $dir .= '/.git'
158       if -f dir($dir)->file('.git/HEAD');
159
160   return $dir;
161 }
162
163 =head2 run_cmd_in
164
165 Run a C<git> command in a given project and return the output as a string.
166
167 =cut
168
169 sub run_cmd_in {
170   my ($self, $project, @args) = @_;
171
172   return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
173 }
174
175 =head2 command
176
177 Run a C<git> command for the project specified in the C<p> parameter and
178 return the output as a list of strings corresponding to the lines of output.
179
180 =cut
181
182 sub command {
183   my($self, @args) = @_;
184
185   my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
186
187   return $output ? split(/\n/, $output) : ();
188 }
189
190 =head2 project_info
191
192 Returns a hash corresponding to a given project's properties. The keys will
193 be:
194
195     name
196     description (empty if .git/description is empty/unnamed)
197     owner
198     last_change
199
200 =cut
201
202 sub project_info {
203   my ($self, $project) = @_;
204
205   return {
206     name => $project,
207     $self->get_project_properties(
208       $self->dir_from_project_name($project),
209     ),
210   };
211 }
212
213 =head2 get_project_properties
214
215 Called by C<project_info> to get a project's properties.
216
217 =cut
218
219 sub get_project_properties {
220   my ($self, $dir) = @_;
221   my %props;
222
223   eval {
224     $props{description} = $dir->file('description')->slurp;
225     chomp $props{description};
226     };
227
228   if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
229     delete $props{description};
230   }
231
232   ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
233
234   my $output = $self->run_cmd_in($dir, qw{
235       for-each-ref --format=%(committer)
236       --sort=-committerdate --count=1 refs/heads
237       });
238
239   if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
240     my $dt = DateTime->from_epoch(epoch => $epoch);
241     $dt->set_time_zone($tz);
242     $props{last_change} = $dt;
243   }
244
245   return %props;
246 }
247
248 =head2 list_projects
249
250 For the C<repo_dir> specified in the config return an array of projects where
251 each item will contain the contents of L</project_info>.
252
253 =cut
254
255 sub list_projects {
256     my ($self, $dir) = @_;
257
258     my $base = dir($dir || $self->repo_dir);
259
260     my @ret;
261     my $dh = $base->open or die("Cannot open dir $base");
262     while (my $file = $dh->read) {
263         next if $file =~ /^.{1,2}$/;
264
265         my $obj = $base->subdir($file);
266         next unless -d $obj;
267         next unless $self->is_git_repo($obj);
268                 # XXX Leaky abstraction alert!
269                 my $is_bare = !-d $obj->subdir('.git');
270
271                 my $name = (File::Spec->splitdir($obj))[-1];
272         push @ret, {
273             name => ($name . ( $is_bare ? '' : '/.git' )),
274             $self->get_project_properties(
275                                 $is_bare ? $obj : $obj->subdir('.git')
276                         ),
277         };
278   }
279
280   return [sort { $a->{name} cmp $b->{name} } @ret];
281 }
282
283 =head2 dir_from_project_name
284
285 Get the corresponding directory of a given project.
286
287 =cut
288
289 sub dir_from_project_name {
290   my ($self, $project) = @_;
291
292   return dir($self->repo_dir)->subdir($project);
293 }
294
295 =head2 head_hash
296
297 Find the hash of a given head (defaults to HEAD) of given (or current) project.
298
299 =cut
300
301 sub head_hash {
302   my ($self, $head) = @_;
303
304   my($output) = $self->command(qw/rev-parse --verify/, $head || 'HEAD' );
305   return unless $output;
306
307   my($sha1) = $output =~ /^($SHA1RE)$/;
308   return $sha1;
309 }
310
311 =head2 list_tree
312
313 For a given tree sha1 return an array describing the tree's contents. Where
314 the keys for each item will be:
315
316     mode
317     type
318     object
319     file
320
321 =cut
322
323 sub list_tree {
324   my ($self, $sha1) = @_;
325
326   $sha1 = $self->head_hash($sha1)
327         if !$sha1 or $sha1 !~ $SHA1RE;
328
329   my($output) = $self->command(qw/ls-tree -z/, $sha1);
330   return
331         unless $output;
332
333   my @ret;
334   for my $line (split /\0/, $output) {
335     my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
336
337     push @ret, {
338       mode    => oct $mode,
339       # XXX I wonder why directories always turn up as 040000 ...
340       modestr => $self->get_object_mode_string({mode=>oct $mode}),
341       type    => $type,
342       object  => $object,
343       file    => $file,
344     };
345   }
346
347   return @ret;
348 }
349
350 =head2 get_object_mode_string
351
352 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
353
354 =cut
355
356 sub get_object_mode_string {
357   my ($self, $object) = @_;
358
359   return unless $object && $object->{mode};
360   return mode_to_string($object->{mode});
361 }
362
363 =head2 get_object_type
364
365 =cut
366
367 sub get_object_type {
368   my ($self, $object) = @_;
369
370   my($output) = $self->command(qw/cat-file -t/, $object)
371     or return;
372
373   return $output;
374 }
375
376 =head2 cat_file
377
378 Return the contents of a given file.
379
380 =cut
381
382 sub cat_file {
383   my ($self, $object) = @_;
384
385   my $type = $self->get_object_type($object, $self->project);
386   die "object `$object' is not a file\n"
387     if (!defined $type || $type ne 'blob');
388
389   my($output) = $self->command(qw/cat-file -p/, $object)
390     or return;
391
392   return $output;
393 }
394
395 =head2 hash_by_path
396
397 For a given sha1 and path find the corresponding hash. Useful for find blobs.
398
399 =cut
400
401 sub hash_by_path {
402   my($self, $base, $path, $type) = @_;
403
404   $path =~ s{/+$}();
405
406   my($line) = $self->command('ls-tree', $base, '--', $path)
407     or return;
408
409   #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa    panic.c'
410   $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
411   return defined $type && $type ne $2
412     ? ()
413     : $3;
414 }
415
416 =head2 valid_rev
417
418 Check whether a given rev is valid i.e looks like a sha1.
419
420 =cut
421
422 sub valid_rev {
423   my ($self, $rev) = @_;
424
425   return unless $rev;
426   return ($rev =~ /^($SHA1RE)$/);
427 }
428
429 =head2 raw_diff
430
431 Provides the raw output of a diff.
432
433 =cut
434
435 # gitweb uses the following sort of command for diffing merges:
436 # /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 --
437 # and for regular diffs
438 # /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 --
439
440 sub raw_diff {
441   my ($self, @args) = @_;
442
443   return $self->command(
444       qw(diff-tree -r -M --no-commit-id --full-index),
445       @args
446   );
447 }
448
449 =pod
450 diff --git a/TODO b/TODO
451 index 6a05e77..2071fd0 100644
452 --- a/TODO
453 +++ b/TODO
454 @@ -2,4 +2,3 @@
455  * An action to find what branches have been merged, either as a list or through a search mechanism.
456  * An action to find which branches a given commit is on.
457  * Fix any not text/html bits e.g the patch action.
458 -* Simplify the creation of links.
459 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
460 index 706d024..7fac165 100644
461 --- a/lib/Gitalist/Controller/Root.pm
462 +++ b/lib/Gitalist/Controller/Root.pm
463 @@ -157,23 +157,6 @@ sub shortlog : Local {
464    );
465  }
466  
467 -=head2 tree
468 -
469 -The tree of a given commit.
470 =cut
471
472 =head2 diff
473
474 Returns a list of diff chunks corresponding to the files contained in the diff
475 and some associated metadata.
476
477 =cut
478
479 # XXX Ideally this would return a wee object instead of ad hoc structures.
480 sub diff {
481   my($self, %args) = @_;
482
483   # So either a parent is specifed, or we use the commit's parent if there's
484   # only one, otherwise it was a merge commit.
485   my $parent = $args{parent}
486              ? $args{parent}
487              : $args{commit}->parents <= 1
488                ? $args{commit}->parent_sha1
489                : '-c';
490   my @etc = (
491     ( $args{file}  ? ('--', $args{file}) : () ),
492   );
493
494   my @out = $self->raw_diff(
495     ( $args{patch} ? '--patch-with-raw' : () ),
496       $parent, $args{commit}->sha1, @etc
497   );
498
499   # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
500   my @difftree = $self->parse_diff_tree(\@out);
501
502   return \@difftree
503     unless $args{patch};
504
505   # The blank line between the tree and the patch.
506   shift @out;
507
508   # XXX And no I'm not happy about having diff return tree + patch.
509   return \@difftree, [$self->parse_diff(@out)];
510 }
511
512 sub parse_diff {
513   my($self, @diff) = @_;
514
515   my @ret;
516   for (@diff) {
517     # This regex is a little pathological.
518     if(m{^diff --git (a/(.*?)) (b/\2)}) {
519       push @ret, {
520         head => $_,
521         a    => $1,
522         b    => $3,
523         file => $2,
524         diff => '',
525       };
526       next;
527     }
528   
529     if(/^index (\w+)\.\.(\w+) (\d+)$/) {
530       @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
531       next
532     }
533   
534     # XXX Somewhat hacky. Ahem.
535     $ret[@ret ? -1 : 0]{diff} .= "$_\n";
536   }
537
538   return @ret;
539 }
540
541 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
542 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M      templates/blob.tt2
543
544 =head2 parse_diff_tree
545
546 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
547 to the C<diff-tree> output.
548
549 =cut
550
551 sub parse_diff_tree {
552   my($self, $diff) = @_;
553
554   my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
555   my @ret;
556   while(@$diff and $diff->[0] =~ /^:\d+/) {
557     my $line = shift @$diff;
558     # see. man git-diff-tree for more info
559     # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
560     my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
561     my %line = zip @keys, @vals;
562     # Some convenience keys
563     $line{file}   = $line{src};
564     $line{sha1}   = $line{sha1dst};
565     $line{is_new} = $line{sha1src} =~ /^0+$/
566         if $line{sha1src};
567     @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
568       if $line{status} =~ /^R/;
569     push @ret, \%line;
570   }
571
572   return @ret;
573 }
574
575 =head2 parse_rev_list
576
577 Given the output of the C<rev-list> command return a list of hashes.
578
579 =cut
580
581 sub parse_rev_list {
582   my ($self, $output) = @_;
583
584   return
585     map  $self->get_object($_),
586     grep $self->valid_rev($_),
587     map  split(/\n/, $_, 6), split /\0/, $output;
588 }
589
590 =head2 list_revs
591
592 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
593 array of hashes.
594
595 =cut
596
597 sub list_revs {
598   my ($self, %args) = @_;
599
600   $args{sha1} = $self->head_hash($args{sha1})
601     if !$args{sha1} || $args{sha1} !~ $SHA1RE;
602
603         my @search_opts;
604   if($args{search}) {
605     my $sargs = $args{search};
606     $sargs->{type} = 'grep'
607       if $sargs->{type} eq 'commit';
608     @search_opts = (
609        # This seems a little fragile ...
610        qq[--$sargs->{type}=$sargs->{text}],
611        '--regexp-ignore-case',
612        $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
613     );
614   }
615
616   my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
617     '--header',
618     (defined $args{ count  } ? "--max-count=$args{count}" : ()),
619     (defined $args{ skip   } ? "--skip=$args{skip}"       : ()),
620     @search_opts,
621     $args{sha1},
622     '--',
623     ($args{file} ? $args{file} : ()),
624   );
625   return unless $output;
626
627   my @revs = $self->parse_rev_list($output);
628
629   return @revs;
630 }
631
632 =head2 rev_info
633
634 Get a single piece of revision information for a given sha1.
635
636 =cut
637
638 sub rev_info {
639   my($self, $rev, $project) = @_;
640
641   return unless $self->valid_rev($rev);
642
643   return $self->list_revs(
644       rev => $rev, count => 1,
645       ( $project ? (project => $project) : () )
646   );
647 }
648
649 =head2 reflog
650
651 Calls the C<reflog> command and returns a list of hashes.
652
653 =cut
654
655 sub reflog {
656   my ($self, @logargs) = @_;
657
658   my @entries
659     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
660     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
661
662 =pod
663   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
664   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
665   Reflog message: push
666   Author: Foo Barsby <fbarsby@example.com>
667   Date:   Thu Sep 17 12:26:05 2009 +0100
668
669       Merge branch 'abc123'
670 =cut
671
672   return map {
673
674     # XXX Stuff like this makes me want to switch to Git::PurePerl
675     my($sha1, $type, $author, $date)
676       = m{
677           ^ commit \s+ ($SHA1RE)$
678           .*?
679           Reflog[ ]message: \s+ (.+?)$ \s+
680           Author: \s+ ([^<]+) <.*?$ \s+
681           Date: \s+ (.+?)$
682         }xms;
683
684     pos($_) = index($_, $date) + length $date;
685
686     # Yeah, I just did that.
687
688     my($msg) = /\G\s+(\S.*)/sg;
689
690     {
691       hash    => $sha1,
692       type    => $type,
693       author  => $author,
694
695       # XXX Add DateTime goodness.
696       date    => $date,
697       message => $msg,
698     };
699   } @entries;
700 }
701
702 =head2 heads
703
704 Returns an array of hashes representing the heads (aka branches) for the
705 given, or current, project.
706
707 =cut
708
709 sub heads {
710   my ($self, $project) = @_;
711
712   my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
713
714   my @ret;
715   for my $line (@output) {
716     my ($rev, $head, $commiter) = split /\0/, $line, 3;
717     $head =~ s!^refs/heads/!!;
718
719     push @ret, { sha1 => $rev, name => $head };
720
721     #FIXME: That isn't the time I'm looking for..
722     if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
723       my $dt = DateTime->from_epoch(epoch => $epoch);
724       $dt->set_time_zone($tz);
725       $ret[-1]->{last_change} = $dt;
726     }
727   }
728
729   return @ret;
730 }
731
732 =head2 refs_for
733
734 For a given sha1 check which branches currently point at it.
735
736 =cut
737
738 sub refs_for {
739     my($self, $sha1) = @_;
740
741     my $refs = $self->references->{$sha1};
742
743     return $refs ? @$refs : ();
744 }
745
746 =head2 references
747
748 A wrapper for C<git show-ref --dereference>. Based on gitweb's
749 C<git_get_references>.
750
751 =cut
752
753 sub references {
754     my($self) = @_;
755
756     return $self->{references}
757         if $self->{references};
758
759     # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
760     # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
761     my @reflist = $self->command(qw(show-ref --dereference))
762         or return;
763
764     my %refs;
765     for(@reflist) {
766         push @{$refs{$1}}, $2
767             if m!^($SHA1RE)\srefs/(.*)$!;
768     }
769
770     return $self->{references} = \%refs;
771 }
772
773 1;
774
775 __PACKAGE__->meta->make_immutable;