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