54d0fd728db21ee2644be47ade62ee381b3db82d
[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/;
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 sub raw_diff {
421   my ($self, @args) = @_;
422
423   return $self->command(diff => '--full-index', @args);
424 }
425
426 =begin
427 diff --git a/TODO b/TODO
428 index 6a05e77..2071fd0 100644
429 --- a/TODO
430 +++ b/TODO
431 @@ -2,4 +2,3 @@
432  * An action to find what branches have been merged, either as a list or through a search mechanism.
433  * An action to find which branches a given commit is on.
434  * Fix any not text/html bits e.g the patch action.
435 -* Simplify the creation of links.
436 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
437 index 706d024..7fac165 100644
438 --- a/lib/Gitalist/Controller/Root.pm
439 +++ b/lib/Gitalist/Controller/Root.pm
440 @@ -157,23 +157,6 @@ sub shortlog : Local {
441    );
442  }
443  
444 -=head2 tree
445 -
446 -The tree of a given commit.
447 =cut
448
449 =head2 diff
450
451 Returns a list of diff chunks corresponding to the files contained in the diff
452 and some associated metadata.
453
454 =cut
455
456 sub diff {
457   my($self, @revs) = @_;
458
459   return $self->parse_diff($self->raw_diff(@revs));
460 }
461
462 sub parse_diff {
463   my($self, @diff) = @_;
464
465   my @ret;
466   for (@diff) {
467         # This regex is a little pathological.
468         if(m{^diff --git (a/(.*?)) (b/\2)}) {
469       push @ret, {
470         head => $_,
471         a    => $1,
472         b    => $3,
473                 file => $2,
474                 diff => '',
475       };
476           next;
477         }
478
479         if(/^index (\w+)\.\.(\w+) (\d+)$/) {
480           @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
481           next
482     }
483
484         # XXX Somewhat hacky. Ahem.
485         $ret[-1]{diff} .= "$_\n";
486   }
487
488   return @ret;
489 }
490
491 =head2 parse_rev_list
492
493 Given the output of the C<rev-list> command return a list of hashes.
494
495 =cut
496
497 sub parse_rev_list {
498   my ($self, $output) = @_;
499   my @ret;
500
501   my @revs = split /\0/, $output;
502
503   for my $rev (split /\0/, $output) {
504     for my $line (split /\n/, $rev, 6) {
505       chomp $line;
506       next unless $line;
507
508       if ($self->valid_rev($line)) {
509         push @ret, $self->get_object($line);
510       }
511         }
512   }
513
514   return @ret;
515 }
516
517 =head2 list_revs
518
519 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
520 array of hashes.
521
522 =cut
523
524 sub list_revs {
525   my ($self, %args) = @_;
526
527   $args{sha1} ||= $self->head_hash($args{project});
528
529   my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
530     '--header',
531     (defined $args{ count } ? "--max-count=$args{count}" : ()),
532     (defined $args{ skip  } ? "--skip=$args{skip}"       : ()),
533     $args{sha1},
534     '--',
535     ($args{file} ? $args{file} : ()),
536   );
537   return unless $output;
538
539   my @revs = $self->parse_rev_list($output);
540
541   return @revs;
542 }
543
544 =head2 rev_info
545
546 Get a single piece of revision information for a given sha1.
547
548 =cut
549
550 sub rev_info {
551   my($self, $rev, $project) = @_;
552
553   return unless $self->valid_rev($rev);
554
555   return $self->list_revs(
556           rev => $rev, count => 1,
557           ( $project ? (project => $project) : () )
558   );
559 }
560
561 =head2 reflog
562
563 Calls the C<reflog> command and returns a list of hashes.
564
565 =cut
566
567 sub reflog {
568   my ($self, @logargs) = @_;
569
570   my @entries
571     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
572     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
573
574 =begin
575
576   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
577   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
578   Reflog message: push
579   Author: Foo Barsby <fbarsby@example.com>
580   Date:   Thu Sep 17 12:26:05 2009 +0100
581
582       Merge branch 'abc123'
583 =cut
584
585   return map {
586
587     # XXX Stuff like this makes me want to switch to Git::PurePerl
588     my($sha1, $type, $author, $date)
589       = m{
590           ^ commit \s+ ($SHA1RE)$
591           .*?
592           Reflog[ ]message: \s+ (.+?)$ \s+
593           Author: \s+ ([^<]+) <.*?$ \s+
594           Date: \s+ (.+?)$
595         }xms;
596
597     pos($_) = index($_, $date) + length $date;
598
599     # Yeah, I just did that.
600
601     my($msg) = /\G\s+(\S.*)/sg;
602
603     {
604       hash    => $sha1,
605       type    => $type,
606       author  => $author,
607
608       # XXX Add DateTime goodness.
609       date    => $date,
610       message => $msg,
611     };
612   } @entries;
613 }
614
615 =head2 heads
616
617 Returns an array of hashes representing the heads (aka branches) for the
618 given, or current, project.
619
620 =cut
621
622 sub heads {
623   my ($self, $project) = @_;
624
625   my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
626
627   my @ret;
628   for my $line (@output) {
629     my ($rev, $head, $commiter) = split /\0/, $line, 3;
630     $head =~ s!^refs/heads/!!;
631
632     push @ret, { sha1 => $rev, name => $head };
633
634     #FIXME: That isn't the time I'm looking for..
635     if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
636       my $dt = DateTime->from_epoch(epoch => $epoch);
637       $dt->set_time_zone($tz);
638       $ret[-1]->{last_change} = $dt;
639     }
640   }
641
642   return @ret;
643 }
644
645 =head2 refs_for
646
647 For a given sha1 check which branches currently point at it.
648
649 =cut
650
651 sub refs_for {
652         my($self, $sha1) = @_;
653
654         my $refs = $self->references->{$sha1};
655
656         return $refs ? @$refs : ();
657 }
658
659 =head2 references
660
661 A wrapper for C<git show-ref --dereference>. Based on gitweb's
662 C<git_get_references>.
663
664 =cut
665
666 sub references {
667         my($self) = @_;
668
669         return $self->{references}
670                 if $self->{references};
671
672         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
673         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
674         my @reflist = $self->command(qw(show-ref --dereference))
675                 or return;
676
677         my %refs;
678         for(@reflist) {
679                 push @{$refs{$1}}, $2
680                         if m!^($SHA1RE)\srefs/(.*)$!;
681         }
682
683         return $self->{references} = \%refs;
684 }
685
686 =begin
687
688 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
689 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M      TODO
690 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M      lib/Gitalist/Controller/Root.pm
691 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M      lib/Gitalist/View/Default.pm
692 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A      lib/Gitalist/View/SyntaxHighlight.pm
693 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A      root/static/css/syntax-dark.css
694 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M      templates/blob.tt2
695
696 =cut
697
698 use List::MoreUtils qw(zip);
699 # XXX Hrm, getting called twice, not sure why.
700 =head2 diff_tree
701
702 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
703 to the C<diff-tree> output.
704
705 =cut
706
707 sub diff_tree {
708         my($self, $commit) = @_;
709
710         my @dtout = $self->command(
711                 # XXX should really deal with multple parents ...
712                 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
713         );
714
715         my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
716         my @difftree = map {
717                 # see. man git-diff-tree for more info
718                 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
719                 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
720                 my %line = zip @keys, @vals;
721                 # Some convenience keys
722                 $line{file}   = $line{src};
723                 $line{sha1}   = $line{sha1dst};
724                 $line{is_new} = $line{sha1src} =~ /^0+$/;
725                 \%line;
726         } @dtout;
727
728         return @difftree;
729 }
730
731 1;
732
733 __PACKAGE__->meta->make_immutable;