Merge
[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, $project) = @_;
303
304   my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
305   return unless defined $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, $rev, $project) = @_;
325
326   $project ||= $self->project;
327   $rev ||= $self->head_hash($project);
328
329   my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
330   return unless defined $output;
331
332   my @ret;
333   for my $line (split /\0/, $output) {
334     my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
335
336     push @ret, {
337       mode    => oct $mode,
338           # XXX I wonder why directories always turn up as 040000 ...
339       modestr => $self->get_object_mode_string({mode=>oct $mode}),
340       type    => $type,
341       object  => $object,
342       file    => $file,
343     };
344   }
345
346   return @ret;
347 }
348
349 =head2 get_object_mode_string
350
351 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
352
353 =cut
354
355 sub get_object_mode_string {
356   my ($self, $object) = @_;
357
358   return unless $object && $object->{mode};
359   return mode_to_string($object->{mode});
360 }
361
362 =head2 get_object_type
363
364 =cut
365
366 sub get_object_type {
367   my ($self, $object, $project) = @_;
368
369   chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
370   return unless $output;
371
372   return $output;
373 }
374
375 =head2 cat_file
376
377 Return the contents of a given file.
378
379 =cut
380
381 sub cat_file {
382   my ($self, $object, $project) = @_;
383
384   my $type = $self->get_object_type($object, $self->project);
385   die "object `$object' is not a file\n"
386     if (!defined $type || $type ne 'blob');
387
388   my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
389   return unless $output;
390
391   return $output;
392 }
393
394 =head2 hash_by_path
395
396 For a given sha1 and path find the corresponding hash. Useful for find blobs.
397
398 =cut
399
400 sub hash_by_path {
401   my($self, $base, $path, $type) = @_;
402
403   $path =~ s{/+$}();
404
405   my($line) = $self->command('ls-tree', $base, '--', $path)
406     or return;
407
408   #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
409   $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
410   return defined $type && $type ne $2
411     ? ()
412     : $3;
413 }
414
415 =head2 valid_rev
416
417 Check whether a given rev is valid i.e looks like a sha1.
418
419 =cut
420
421 sub valid_rev {
422   my ($self, $rev) = @_;
423
424   return unless $rev;
425   return ($rev =~ /^($SHA1RE)$/);
426 }
427
428 =head2 raw_diff
429
430 Provides the raw output of a diff.
431
432 =cut
433
434 # gitweb uses the following sort of command for diffing merges:
435 # /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 --
436 # and for regular diffs
437 # /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 --
438
439 sub raw_diff {
440   my ($self, @args) = @_;
441
442   return $self->command(
443           qw(diff-tree -r -M --no-commit-id --full-index),
444           @args
445   );
446 }
447
448 =pod
449 diff --git a/TODO b/TODO
450 index 6a05e77..2071fd0 100644
451 --- a/TODO
452 +++ b/TODO
453 @@ -2,4 +2,3 @@
454  * An action to find what branches have been merged, either as a list or through a search mechanism.
455  * An action to find which branches a given commit is on.
456  * Fix any not text/html bits e.g the patch action.
457 -* Simplify the creation of links.
458 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
459 index 706d024..7fac165 100644
460 --- a/lib/Gitalist/Controller/Root.pm
461 +++ b/lib/Gitalist/Controller/Root.pm
462 @@ -157,23 +157,6 @@ sub shortlog : Local {
463    );
464  }
465  
466 -=head2 tree
467 -
468 -The tree of a given commit.
469 =cut
470
471 =head2 diff
472
473 Returns a list of diff chunks corresponding to the files contained in the diff
474 and some associated metadata.
475
476 =cut
477
478 # XXX Ideally this would return a wee object instead of ad hoc structures.
479 sub diff {
480   my($self, %args) = @_;
481
482   # So either a parent is specifed, or we use the commit's parent if there's
483   # only one, otherwise it was a merge commit.
484   my $parent = $args{parent}
485              ? $args{parent}
486              : $args{commit}->parents <= 1
487                ? $args{commit}->parent_sha1
488                : '-c';
489   my @etc = (
490     ( $args{file}  ? ('--', $args{file}) : () ),
491   );
492
493   my @out = $self->raw_diff(
494         ( $args{patch} ? '--patch-with-raw' : () ),
495           $parent, $args{commit}->sha1, @etc
496   );
497
498   # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
499   my @difftree = $self->parse_diff_tree(\@out);
500
501   return \@difftree
502         unless $args{patch};
503
504   # The blank line between the tree and the patch.
505   shift @out;
506
507   # XXX And no I'm not happy about having diff return tree + patch.
508   return \@difftree, [$self->parse_diff(@out)];
509 }
510
511 sub parse_diff {
512   my($self, @diff) = @_;
513
514   my @ret;
515   for (@diff) {
516     # This regex is a little pathological.
517     if(m{^diff --git (a/(.*?)) (b/\2)}) {
518       push @ret, {
519         head => $_,
520         a    => $1,
521         b    => $3,
522         file => $2,
523         diff => '',
524       };
525       next;
526     }
527   
528     if(/^index (\w+)\.\.(\w+) (\d+)$/) {
529       @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
530       next
531     }
532   
533     # XXX Somewhat hacky. Ahem.
534     $ret[@ret ? -1 : 0]{diff} .= "$_\n";
535   }
536
537   return @ret;
538 }
539
540 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
541 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M      templates/blob.tt2
542
543 =head2 parse_diff_tree
544
545 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
546 to the C<diff-tree> output.
547
548 =cut
549
550 sub parse_diff_tree {
551   my($self, $diff) = @_;
552
553   my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
554   my @ret;
555   while(@$diff and $diff->[0] =~ /^:\d+/) {
556         my $line = shift @$diff;
557     # see. man git-diff-tree for more info
558     # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
559     my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
560     my %line = zip @keys, @vals;
561     # Some convenience keys
562     $line{file}   = $line{src};
563     $line{sha1}   = $line{sha1dst};
564     $line{is_new} = $line{sha1src} =~ /^0+$/
565                 if $line{sha1src};
566         @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
567       if $line{status} =~ /^R/;
568     push @ret, \%line;
569   }
570
571   return @ret;
572 }
573
574 =head2 parse_rev_list
575
576 Given the output of the C<rev-list> command return a list of hashes.
577
578 =cut
579
580 sub parse_rev_list {
581   my ($self, $output) = @_;
582
583   return
584     map  $self->get_object($_),
585     grep $self->valid_rev($_),
586     map  split(/\n/, $_, 6), split /\0/, $output;
587 }
588
589 =head2 list_revs
590
591 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
592 array of hashes.
593
594 =cut
595
596 sub list_revs {
597   my ($self, %args) = @_;
598
599   $args{sha1} = $self->head_hash($args{sha1})
600     if !$args{sha1} || $args{sha1} !~ $SHA1RE;
601
602         my @search_opts;
603   if($args{search}) {
604     my $sargs = $args{search};
605     $sargs->{type} = 'grep'
606       if $sargs->{type} eq 'commit';
607     @search_opts = (
608        # This seems a little fragile ...
609        qq[--$sargs->{type}=$sargs->{text}],
610        '--regexp-ignore-case',
611        $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
612     );
613   }
614
615   my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
616     '--header',
617     (defined $args{ count  } ? "--max-count=$args{count}" : ()),
618     (defined $args{ skip   } ? "--skip=$args{skip}"       : ()),
619     @search_opts,
620     $args{sha1},
621     '--',
622     ($args{file} ? $args{file} : ()),
623   );
624   return unless $output;
625
626   my @revs = $self->parse_rev_list($output);
627
628   return @revs;
629 }
630
631 =head2 rev_info
632
633 Get a single piece of revision information for a given sha1.
634
635 =cut
636
637 sub rev_info {
638   my($self, $rev, $project) = @_;
639
640   return unless $self->valid_rev($rev);
641
642   return $self->list_revs(
643           rev => $rev, count => 1,
644           ( $project ? (project => $project) : () )
645   );
646 }
647
648 =head2 reflog
649
650 Calls the C<reflog> command and returns a list of hashes.
651
652 =cut
653
654 sub reflog {
655   my ($self, @logargs) = @_;
656
657   my @entries
658     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
659     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
660
661 =pod
662   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
663   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
664   Reflog message: push
665   Author: Foo Barsby <fbarsby@example.com>
666   Date:   Thu Sep 17 12:26:05 2009 +0100
667
668       Merge branch 'abc123'
669 =cut
670
671   return map {
672
673     # XXX Stuff like this makes me want to switch to Git::PurePerl
674     my($sha1, $type, $author, $date)
675       = m{
676           ^ commit \s+ ($SHA1RE)$
677           .*?
678           Reflog[ ]message: \s+ (.+?)$ \s+
679           Author: \s+ ([^<]+) <.*?$ \s+
680           Date: \s+ (.+?)$
681         }xms;
682
683     pos($_) = index($_, $date) + length $date;
684
685     # Yeah, I just did that.
686
687     my($msg) = /\G\s+(\S.*)/sg;
688
689     {
690       hash    => $sha1,
691       type    => $type,
692       author  => $author,
693
694       # XXX Add DateTime goodness.
695       date    => $date,
696       message => $msg,
697     };
698   } @entries;
699 }
700
701 =head2 heads
702
703 Returns an array of hashes representing the heads (aka branches) for the
704 given, or current, project.
705
706 =cut
707
708 sub heads {
709   my ($self, $project) = @_;
710
711   my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
712
713   my @ret;
714   for my $line (@output) {
715     my ($rev, $head, $commiter) = split /\0/, $line, 3;
716     $head =~ s!^refs/heads/!!;
717
718     push @ret, { sha1 => $rev, name => $head };
719
720     #FIXME: That isn't the time I'm looking for..
721     if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
722       my $dt = DateTime->from_epoch(epoch => $epoch);
723       $dt->set_time_zone($tz);
724       $ret[-1]->{last_change} = $dt;
725     }
726   }
727
728   return @ret;
729 }
730
731 =head2 refs_for
732
733 For a given sha1 check which branches currently point at it.
734
735 =cut
736
737 sub refs_for {
738         my($self, $sha1) = @_;
739
740         my $refs = $self->references->{$sha1};
741
742         return $refs ? @$refs : ();
743 }
744
745 =head2 references
746
747 A wrapper for C<git show-ref --dereference>. Based on gitweb's
748 C<git_get_references>.
749
750 =cut
751
752 sub references {
753         my($self) = @_;
754
755         return $self->{references}
756                 if $self->{references};
757
758         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
759         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
760         my @reflist = $self->command(qw(show-ref --dereference))
761                 or return;
762
763         my %refs;
764         for(@reflist) {
765                 push @{$refs{$1}}, $2
766                         if m!^($SHA1RE)\srefs/(.*)$!;
767         }
768
769         return $self->{references} = \%refs;
770 }
771
772 1;
773
774 __PACKAGE__->meta->make_immutable;