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