Intermediate commit on the way to switching to Git::PurePerl.
[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 Git::PurePerl;
9
10 use DateTime;
11 use Path::Class;
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
19 {
20   my $git;
21   sub git_bin {
22     return $git
23       if $git;
24
25     if (my $config_git = Gitalist->config->{git}) {
26       $git = $config_git if -x $config_git;
27     }
28     else {
29       require File::Which;
30       $git = File::Which::which('git');
31     }
32
33     if (!$git) {
34       die <<EOR
35 Could not find a git executable.
36 Please specify the which git executable to use in gitweb.yml
37 EOR
38     }
39
40     return $git;
41   }
42 }
43
44 has project => (is => 'rw', isa => 'Str');
45
46 sub is_git_repo {
47   my ($self, $dir) = @_;
48
49   return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
50 }
51
52 sub project_info {
53   my ($self, $project) = @_;
54
55   return {
56     name => $project,
57     $self->get_project_properties(
58       $self->git_dir_from_project_name($project),
59       ),
60     };
61 }
62
63 sub get_project_properties {
64   my ($self, $dir) = @_;
65   my %props;
66
67   eval {
68     $props{description} = $dir->file('description')->slurp;
69     chomp $props{description};
70     };
71
72   if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
73     delete $props{description};
74   }
75
76   ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
77
78   my $output = $self->run_cmd_in($dir, qw{
79       for-each-ref --format=%(committer)
80       --sort=-committerdate --count=1 refs/heads
81       });
82
83   if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
84     my $dt = DateTime->from_epoch(epoch => $epoch);
85     $dt->set_time_zone($tz);
86     $props{last_change} = $dt;
87   }
88
89   return %props;
90 }
91
92 sub list_projects {
93   my ($self) = @_;
94
95   my $base = dir(Gitalist->config->{repo_dir});
96
97   my @ret;
98   my $dh = $base->open;
99   while (my $file = $dh->read) {
100     next if $file =~ /^.{1,2}$/;
101
102     my $obj = $base->subdir($file);
103     next unless -d $obj;
104     next unless $self->is_git_repo($obj);
105
106     # XXX Leaky abstraction alert!
107     my $is_bare = !-d $obj->subdir('.git');
108
109     my $name = (File::Spec->splitdir($obj))[-1];
110     push @ret, {
111       name => ($name . ( $is_bare ? '.git' : '/.git' )),
112       $self->get_project_properties(
113         $is_bare ? $obj : $obj->subdir('.git')
114         ),
115       };
116   }
117
118   return [sort { $a->{name} cmp $b->{name} } @ret];
119 }
120
121 sub run_cmd {
122   my ($self, @args) = @_;
123
124   open my $fh, '-|', __PACKAGE__->git_bin, @args
125     or die "failed to run git command";
126   binmode $fh, ':encoding(UTF-8)';
127
128   print STDERR "RAN - git @_[1..$#_]\n";
129
130   my $output = do { local $/ = undef; <$fh> };
131   close $fh;
132
133   return $output;
134 }
135
136 sub project_dir {
137   my($self, $project) = @_;
138
139   my $dir = blessed($project) && $project->isa('Path::Class::Dir')
140        ? $project->stringify
141        : $self->git_dir_from_project_name($project);
142
143   $dir =~ s/\.git$//;
144
145   return $dir;
146 }
147
148 sub run_cmd_in {
149   my ($self, $project, @args) = @_;
150
151   return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
152 }
153
154 sub git_dir_from_project_name {
155   my ($self, $project) = @_;
156
157   return dir(Gitalist->config->{repo_dir})->subdir($project);
158 }
159
160 sub get_head_hash {
161   my ($self, $project) = @_;
162
163   my $output = $self->run_cmd_in($self->project, qw/rev-parse --verify HEAD/ );
164   return unless defined $output;
165
166   my ($head) = $output =~ /^([0-9a-fA-F]{40})$/;
167   return $head;
168 }
169
170 sub list_tree {
171   my ($self, $project, $rev) = @_;
172
173   $rev ||= $self->get_head_hash($project);
174
175   my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
176   return unless defined $output;
177
178   my @ret;
179   for my $line (split /\0/, $output) {
180     my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
181
182     push @ret, {
183       mode   => oct $mode,
184       type   => $type,
185       object => $object,
186       file   => $file,
187       };
188   }
189
190   return @ret;
191 }
192
193 sub get_object_mode_string {
194   my ($self, $object) = @_;
195
196   return unless $object && $object->{mode};
197   return mode_to_string($object->{mode});
198 }
199
200 sub get_object_type {
201   my ($self, $project, $object) = @_;
202
203   my $output = $self->run_cmd_in($project, qw/cat-file -t/, $object);
204   return unless $output;
205
206   chomp $output;
207   return $output;
208 }
209
210 sub get_hash_by_path {
211   my($self, $base, $path, $type) = @_;
212
213   $path =~ s{/+$}();
214
215   my $line = $self->run_cmd_in($self->project, 'ls-tree', $base, '--', $path)
216     or return;
217
218   #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
219   $line =~ m/^([0-9]+) (.+) ([0-9a-fA-F]{40})\t/;
220   return defined $type && $type ne $2
221     ? ()
222     : return $3;
223 }
224
225 sub cat_file {
226   my ($self, $object) = @_;
227
228   my $type = $self->get_object_type($self->project, $object);
229   die "object `$object' is not a file\n"
230     if (!defined $type || $type ne 'blob');
231
232   my $output = $self->run_cmd_in($self->project, qw/cat-file -p/, $object);
233   return unless $output;
234
235   return $output;
236 }
237
238 sub valid_rev {
239   my ($self, $rev) = @_;
240
241   return unless $rev;
242   return ($rev =~ /^([0-9a-fA-F]{40})$/);
243 }
244
245 sub diff {
246   my ($self, $project, @revs) = @_;
247
248   croak("Gitalist::Model::Git::diff needs a project and either one or two revisions")
249     if scalar @revs < 1
250       || scalar @revs > 2
251       || any { !$self->valid_rev($_) } @revs;
252
253   my $output = $self->run_cmd_in($project, 'diff', @revs);
254   return unless $output;
255
256   return $output;
257 }
258
259 {
260   my $formatter = DateTime::Format::Mail->new;
261
262   sub parse_rev_list {
263     my ($self, $output) = @_;
264     my @ret;
265
266     my @revs = split /\0/, $output;
267
268     for my $rev (split /\0/, $output) {
269       for my $line (split /\n/, $rev, 6) {
270         chomp $line;
271         next unless $line;
272
273         if ($self->valid_rev($line)) {
274           push @ret, {rev => $line};
275           next;
276         }
277
278         if (my ($key, $value) = $line =~ /^(tree|parent)\s+(.*)$/) {
279           $ret[-1]->{$key} = $value;
280           next;
281         }
282
283         if (my ($key, $value, $epoch, $tz) = $line =~ /^(author|committer)\s+(.*)\s+(\d+)\s+([+-]\d+)$/) {
284           $ret[-1]->{$key} = $value;
285           eval {
286             $ret[-1]->{ $key . "_datetime" } = DateTime->from_epoch(epoch => $epoch);
287             $ret[-1]->{ $key . "_datetime" }->set_time_zone($tz);
288             $ret[-1]->{ $key . "_datetime" }->set_formatter($formatter);
289             };
290
291           if ($@) {
292             $ret[-1]->{ $key . "_datetime" } = "$epoch $tz";
293           }
294
295           if (my ($name, $email) = $value =~ /^([^<]+)\s+<([^>]+)>$/) {
296             $ret[-1]->{ $key . "_name"  } = $name;
297             $ret[-1]->{ $key . "_email" } = $email;
298           }
299         }
300
301         $line =~ s/^\n?\s{4}//;
302         $ret[-1]->{longmessage} = $line;
303         $ret[-1]->{message} = (split /\n/, $line, 2)[0];
304       }
305     }
306
307     return @ret;
308   }
309 }
310
311 sub list_revs {
312   my ($self, $project, %args) = @_;
313
314   $args{rev} ||= $self->get_head_hash($project);
315
316   my $output = $self->run_cmd_in($project, 'rev-list',
317     '--header',
318     (defined $args{ count } ? "--max-count=$args{count}" : ()),
319     (defined $args{ skip  } ? "--skip=$args{skip}"     : ()),
320     $args{rev},
321     '--',
322     ($args{file} || ()),
323     );
324   return unless $output;
325
326   my @revs = $self->parse_rev_list($output);
327
328   return \@revs;
329 }
330
331 sub rev_info {
332   my ($self, $project, $rev) = @_;
333
334   return unless $self->valid_rev($rev);
335
336   return $self->list_revs($project, rev => $rev, count => 1);
337 }
338
339 sub reflog {
340   my ($self, @logargs) = @_;
341
342   my @entries
343     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
344     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
345
346 =begin
347
348   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
349   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
350   Reflog message: push
351   Author: Iain Loasby <iloasby@rowlf.of-2.uk.venda.com>
352   Date:   Thu Sep 17 12:26:05 2009 +0100
353
354       Merge branch 'rt125181
355 =cut
356
357   return map {
358
359     # XXX Stuff like this makes me want to switch to Git::PurePerl
360     my($sha1, $type, $author, $date)
361       = m{
362           ^ commit \s+ ([0-9a-f]+)$
363           .*?
364           Reflog[ ]message: \s+ (.+?)$ \s+
365           Author: \s+ ([^<]+) <.*?$ \s+
366           Date: \s+ (.+?)$
367 }xms;
368
369     pos($_) = index($_, $date) + length $date;
370
371     # Yeah, I just did that.
372
373     my($msg) = /\G\s+(\S.*)/sg;
374
375     {
376       hash    => $sha1,
377       type    => $type,
378       author  => $author,
379
380       # XXX Add DateTime goodness.
381       date    => $date,
382       message => $msg,
383     };
384     } @entries;
385 }
386
387 sub get_heads {
388   my ($self, $project) = @_;
389
390   my $output = $self->run_cmd_in($project, qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
391   return unless $output;
392
393   my @ret;
394   for my $line (split /\n/, $output) {
395     my ($rev, $head, $commiter) = split /\0/, $line, 3;
396     $head =~ s!^refs/heads/!!;
397
398     push @ret, { rev => $rev, name => $head };
399
400     #FIXME: That isn't the time I'm looking for..
401     if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
402       my $dt = DateTime->from_epoch(epoch => $epoch);
403       $dt->set_time_zone($tz);
404       $ret[-1]->{last_change} = $dt;
405     }
406   }
407
408   return \@ret;
409 }
410
411 sub archive {
412   my ($self, $project, $rev) = @_;
413
414   #FIXME: huge memory consuption
415   #TODO: compression
416   return $self->run_cmd_in($project, qw/archive --format=tar/, "--prefix=${project}/", $rev);
417 }
418
419 1;
420
421 __PACKAGE__->meta->make_immutable;