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