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