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