Tidied up the /blob action and the commit-nav.tt2 links.
[catagits/Gitalist.git] / lib / Gitalist / Model / Git.pm
1 package Gitalist::Model::Git;
2
3 use Moose;
4 use namespace::autoclean;
5
6 BEGIN { extends 'Catalyst::Model' }
7
8 use DateTime;
9 use Path::Class;
10 use File::Which;
11 use Carp qw/croak/;
12 use File::Find::Rule;
13 use DateTime::Format::Mail;
14 use File::Stat::ModeString;
15 use List::MoreUtils qw/any/;
16 use Scalar::Util qw/blessed/;
17 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
18
19 # Should these live in a separate module? Or perhaps extended Regexp::Common?
20 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
21
22 has project  => ( isa => NonEmptySimpleStr, is => 'rw');
23 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 ); # Fixme - path::class
24 has git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
25  
26 sub BUILD {
27     my ($self) = @_;
28     $self->git; # Cause lazy value build.
29     $self->repo_dir;
30 }
31
32 use Git::PurePerl;
33
34 has gpp => (
35  #isa => 'Git::PurePerl'
36   is       => 'ro',
37   required => 1,
38   lazy     => 1,
39   default  => sub {
40     my($self) = @_;
41     return Git::PurePerl->new(
42       directory => $self->project_dir( $self->project )
43     );
44   },
45 );
46
47 sub _build_git {
48     my $git = File::Which::which('git');
49
50     if (!$git) {
51         die <<EOR;
52 Could not find a git executable.
53 Please specify the which git executable to use in gitweb.yml
54 EOR
55     }
56
57     return $git;
58 }
59  
60 sub _build_repo_dir {
61   return Gitalist->config->{repo_dir};
62 }
63
64 sub get_object {
65   $_[0]->gpp->get_object($_[1]);
66 }
67
68 sub is_git_repo {
69   my ($self, $dir) = @_;
70
71   return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
72 }
73
74 sub run_cmd {
75   my ($self, @args) = @_;
76
77   print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
78
79   open my $fh, '-|', $self->git, @args
80     or die "failed to run git command";
81   binmode $fh, ':encoding(UTF-8)';
82
83   my $output = do { local $/ = undef; <$fh> };
84   close $fh;
85
86   return $output;
87 }
88
89 sub project_dir {
90   my($self, $project) = @_;
91
92   my $dir = blessed($project) && $project->isa('Path::Class::Dir')
93        ? $project->stringify
94        : $self->git_dir_from_project_name($project);
95
96   $dir =~ s/\.git$//;
97
98   return $dir;
99 }
100
101 sub run_cmd_in {
102   my ($self, $project, @args) = @_;
103
104   return $self->run_cmd('--git-dir' => $self->project_dir($project)."/.git", @args);
105 }
106
107 sub command {
108   my($self, @args) = @_;
109
110   my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project)."/.git", @args);
111
112   return $output ? split(/\n/, $output) : ();
113 }
114
115 sub project_info {
116   my ($self, $project) = @_;
117
118   return {
119     name => $project,
120     $self->get_project_properties(
121       $self->git_dir_from_project_name($project),
122       ),
123     };
124 }
125
126 sub get_project_properties {
127   my ($self, $dir) = @_;
128   my %props;
129
130   eval {
131     $props{description} = $dir->file('description')->slurp;
132     chomp $props{description};
133     };
134
135   if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
136     delete $props{description};
137   }
138
139   ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
140
141   my $output = $self->run_cmd_in($dir, qw{
142       for-each-ref --format=%(committer)
143       --sort=-committerdate --count=1 refs/heads
144       });
145
146   if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
147     my $dt = DateTime->from_epoch(epoch => $epoch);
148     $dt->set_time_zone($tz);
149     $props{last_change} = $dt;
150   }
151
152   return %props;
153 }
154
155 sub list_projects {
156   my ($self) = @_;
157
158   my $base = dir($self->repo_dir);
159
160   my @ret;
161   my $dh = $base->open;
162   while (my $file = $dh->read) {
163     next if $file =~ /^.{1,2}$/;
164
165     my $obj = $base->subdir($file);
166     next unless -d $obj;
167     next unless $self->is_git_repo($obj);
168
169     # XXX Leaky abstraction alert!
170     my $is_bare = !-d $obj->subdir('.git');
171
172     my $name = (File::Spec->splitdir($obj))[-1];
173     push @ret, {
174       name => ($name . ( $is_bare ? '.git' : '/.git' )),
175       $self->get_project_properties(
176         $is_bare ? $obj : $obj->subdir('.git')
177         ),
178       };
179   }
180
181   return [sort { $a->{name} cmp $b->{name} } @ret];
182 }
183
184 sub git_dir_from_project_name {
185   my ($self, $project) = @_;
186
187   return dir($self->repo_dir)->subdir($project);
188 }
189
190 sub head_hash {
191   my ($self, $project) = @_;
192
193   my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify HEAD/ );
194   return unless defined $output;
195
196   my ($head) = $output =~ /^($SHA1RE)$/;
197   return $head;
198 }
199
200 sub list_tree {
201   my ($self, $project, $rev) = @_;
202
203   $rev ||= $self->head_hash($project);
204
205   my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
206   return unless defined $output;
207
208   my @ret;
209   for my $line (split /\0/, $output) {
210     my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
211
212     push @ret, {
213       mode   => oct $mode,
214       type   => $type,
215       object => $object,
216       file   => $file,
217       };
218   }
219
220   return @ret;
221 }
222
223 sub get_object_mode_string {
224   my ($self, $object) = @_;
225
226   return unless $object && $object->{mode};
227   return mode_to_string($object->{mode});
228 }
229
230 sub get_object_type {
231   my ($self, $project, $object) = @_;
232
233   my $output = $self->run_cmd_in($project, qw/cat-file -t/, $object);
234   return unless $output;
235
236   chomp $output;
237   return $output;
238 }
239
240 sub hash_by_path {
241   my($self, $base, $path, $type) = @_;
242
243   $path =~ s{/+$}();
244
245   my($line) = $self->command('ls-tree', $base, '--', $path)
246     or return;
247
248   #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
249   $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
250   return defined $type && $type ne $2
251     ? ()
252     : $3;
253 }
254
255 sub cat_file {
256   my ($self, $object) = @_;
257
258   my $type = $self->get_object_type($self->project, $object);
259   die "object `$object' is not a file\n"
260     if (!defined $type || $type ne 'blob');
261
262   my $output = $self->run_cmd_in($self->project, qw/cat-file -p/, $object);
263   return unless $output;
264
265   return $output;
266 }
267
268 sub valid_rev {
269   my ($self, $rev) = @_;
270
271   return unless $rev;
272   return ($rev =~ /^($SHA1RE)$/);
273 }
274
275 sub diff {
276   my ($self, $project, @revs) = @_;
277
278   croak("Gitalist::Model::Git::diff needs a project and either one or two revisions")
279     if scalar @revs < 1
280       || scalar @revs > 2
281       || any { !$self->valid_rev($_) } @revs;
282
283   my $output = $self->run_cmd_in($project, 'diff', @revs);
284   return unless $output;
285
286   return $output;
287 }
288
289 {
290   my $formatter = DateTime::Format::Mail->new;
291
292   sub parse_rev_list {
293     my ($self, $output) = @_;
294     my @ret;
295
296     my @revs = split /\0/, $output;
297
298     for my $rev (split /\0/, $output) {
299       for my $line (split /\n/, $rev, 6) {
300         chomp $line;
301         next unless $line;
302
303         if ($self->valid_rev($line)) {
304           push @ret, {rev => $line};
305           next;
306         }
307
308         if (my ($key, $value) = $line =~ /^(tree|parent)\s+(.*)$/) {
309           $ret[-1]->{$key} = $value;
310           next;
311         }
312
313         if (my ($key, $value, $epoch, $tz) = $line =~ /^(author|committer)\s+(.*)\s+(\d+)\s+([+-]\d+)$/) {
314           $ret[-1]->{$key} = $value;
315           eval {
316             $ret[-1]->{ $key . "_datetime" } = DateTime->from_epoch(epoch => $epoch);
317             $ret[-1]->{ $key . "_datetime" }->set_time_zone($tz);
318             $ret[-1]->{ $key . "_datetime" }->set_formatter($formatter);
319             };
320
321           if ($@) {
322             $ret[-1]->{ $key . "_datetime" } = "$epoch $tz";
323           }
324
325           if (my ($name, $email) = $value =~ /^([^<]+)\s+<([^>]+)>$/) {
326             $ret[-1]->{ $key . "_name"  } = $name;
327             $ret[-1]->{ $key . "_email" } = $email;
328           }
329         }
330
331         $line =~ s/^\n?\s{4}//;
332         $ret[-1]->{longmessage} = $line;
333         $ret[-1]->{message} = (split /\n/, $line, 2)[0];
334       }
335     }
336
337     return @ret;
338   }
339 }
340
341 sub list_revs {
342   my ($self, $project, %args) = @_;
343
344   $args{rev} ||= $self->head_hash($project);
345
346   my $output = $self->run_cmd_in($project, 'rev-list',
347     '--header',
348     (defined $args{ count } ? "--max-count=$args{count}" : ()),
349     (defined $args{ skip  } ? "--skip=$args{skip}"     : ()),
350     $args{rev},
351     '--',
352     ($args{file} || ()),
353     );
354   return unless $output;
355
356   my @revs = $self->parse_rev_list($output);
357
358   return \@revs;
359 }
360
361 sub rev_info {
362   my ($self, $project, $rev) = @_;
363
364   return unless $self->valid_rev($rev);
365
366   return $self->list_revs($project, rev => $rev, count => 1);
367 }
368
369 sub reflog {
370   my ($self, @logargs) = @_;
371
372   my @entries
373     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
374     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
375
376 =begin
377
378   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
379   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
380   Reflog message: push
381   Author: Foo Barsby <fbarsby@example.com>
382   Date:   Thu Sep 17 12:26:05 2009 +0100
383
384       Merge branch 'abc123'
385 =cut
386
387   return map {
388
389     # XXX Stuff like this makes me want to switch to Git::PurePerl
390     my($sha1, $type, $author, $date)
391       = m{
392           ^ commit \s+ ($SHA1RE)$
393           .*?
394           Reflog[ ]message: \s+ (.+?)$ \s+
395           Author: \s+ ([^<]+) <.*?$ \s+
396           Date: \s+ (.+?)$
397 }xms;
398
399     pos($_) = index($_, $date) + length $date;
400
401     # Yeah, I just did that.
402
403     my($msg) = /\G\s+(\S.*)/sg;
404
405     {
406       hash    => $sha1,
407       type    => $type,
408       author  => $author,
409
410       # XXX Add DateTime goodness.
411       date    => $date,
412       message => $msg,
413     };
414   } @entries;
415 }
416
417 sub get_heads {
418   my ($self, $project) = @_;
419
420   my $output = $self->run_cmd_in($project, qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
421   return unless $output;
422
423   my @ret;
424   for my $line (split /\n/, $output) {
425     my ($rev, $head, $commiter) = split /\0/, $line, 3;
426     $head =~ s!^refs/heads/!!;
427
428     push @ret, { rev => $rev, name => $head };
429
430     #FIXME: That isn't the time I'm looking for..
431     if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
432       my $dt = DateTime->from_epoch(epoch => $epoch);
433       $dt->set_time_zone($tz);
434       $ret[-1]->{last_change} = $dt;
435     }
436   }
437
438   return \@ret;
439 }
440
441 =head2 refs_for
442
443 Return a list of refs (e.g branches) for a given sha1.
444
445 =cut
446
447 sub refs_for {
448         my($self, $sha1) = @_;
449
450         my $refs = $self->references->{$sha1};
451
452         return $refs ? @$refs : ();
453 }
454
455 =head2
456
457 A wrapper for C<git show-ref --dereference>. Based on gitweb's
458 C<git_get_references>.
459
460 =cut
461
462 sub references {
463         my($self) = @_;
464
465         return $self->{references}
466                 if $self->{references};
467
468         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
469         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
470         my @reflist = $self->command(qw(show-ref --dereference))
471                 or return;
472
473         my %refs;
474         for(@reflist) {
475                 push @{$refs{$1}}, $2
476                         if m!^($SHA1RE)\srefs/(.*)$!;
477         }
478
479         return $self->{references} = \%refs;
480 }
481
482 =begin
483
484 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
485 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M      TODO
486 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M      lib/Gitalist/Controller/Root.pm
487 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M      lib/Gitalist/View/Default.pm
488 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A      lib/Gitalist/View/SyntaxHighlight.pm
489 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A      root/static/css/syntax-dark.css
490 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M      templates/blob.tt2
491
492 =cut
493
494 use List::MoreUtils qw(zip);
495 # XXX Hrm, getting called twice, not sure why.
496 sub diff_tree {
497         my($self, $commit) = @_;
498
499         my @dtout = $self->command(
500                 # XXX should really deal with multple parents ...
501                 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
502         );
503
504         my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
505         my @difftree = map {
506                 # see. man git-diff-tree for more info
507                 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
508                 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
509                 my %line = zip @keys, @vals;
510                 # Some convenience keys
511                 $line{file}   = $line{src};
512                 $line{sha1}   = $line{sha1dst};
513                 $line{is_new} = $line{sha1src} =~ /^0+$/;
514                 \%line;
515         } @dtout;
516
517         return @difftree;
518 }
519
520 sub archive {
521   my ($self, $project, $rev) = @_;
522
523   #FIXME: huge memory consuption
524   #TODO: compression
525   return $self->run_cmd_in($project, qw/archive --format=tar/, "--prefix=${project}/", $rev);
526 }
527
528 1;
529
530 __PACKAGE__->meta->make_immutable;