Merge branch 'win32' into tmp
[catagits/Gitalist.git] / lib / Gitalist / Git / Repository.pm
1 use MooseX::Declare;
2
3 class Gitalist::Git::Repository with Gitalist::Git::HasUtils {
4     # FIXME, use Types::Path::Class and coerce
5     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
6     use MooseX::Types::Path::Class qw/Dir/;
7     use MooseX::Types::Moose qw/Str Maybe Bool HashRef ArrayRef/;
8     use Gitalist::Git::Types qw/SHA1/;
9     use MooseX::MultiMethods;
10     use Moose::Autobox;
11     use List::MoreUtils qw/any zip/;
12     use DateTime;
13     use Encode qw/decode/;
14
15     use if $^O ne 'MSWin32', 'I18N::Langinfo', => qw/langinfo CODESET/;
16     BEGIN {
17         no strict 'subs';
18         *__owner = defined &langinfo
19             ? sub { map { decode(langinfo(CODESET), $_) } (getpwuid $_[0]->path->stat->uid)[6,0] }
20             : sub { return qw/OwnEr GroUp/ }
21         ;
22     }
23
24     use Gitalist::Git::Object::Blob;
25     use Gitalist::Git::Object::Tree;
26     use Gitalist::Git::Object::Commit;
27     use Gitalist::Git::Object::Tag;
28
29     our $SHA1RE = qr/[0-9a-fA-F]{40}/;
30
31     around BUILDARGS (ClassName $class: Dir $dir) {
32         # Allows us to be called as Repository->new($dir)
33         # Last path component becomes $self->name
34         # Full path to git objects becomes $self->path
35         my $name = $dir->dir_list(-1);
36         $dir = $dir->subdir('.git') if (-f $dir->file('.git', 'HEAD'));
37         confess("Can't find a git repository at " . $dir)
38             unless ( -f $dir->file('HEAD') );
39         return $class->$orig(name => $name,
40                              path => $dir);
41     }
42
43     has name => ( isa => NonEmptySimpleStr,
44                   is => 'ro', required => 1 );
45
46     has path => ( isa => Dir,
47                   is => 'ro', required => 1);
48
49     has description => ( isa => Str,
50                          is => 'ro',
51                          lazy_build => 1,
52                      );
53
54     has owner => ( isa => NonEmptySimpleStr,
55                    is => 'ro',
56                    lazy_build => 1,
57                );
58
59     has last_change => ( isa => Maybe['DateTime'],
60                          is => 'ro',
61                          lazy_build => 1,
62                      );
63
64     has is_bare => ( isa => Bool,
65                      is => 'ro',
66                      lazy => 1,
67                      default => sub {
68                          -d $_[0]->path->parent->subdir->($_[0]->name)
69                              ? 1 : 0
70                          },
71                      );
72     has heads => ( isa => ArrayRef[HashRef],
73                    is => 'ro',
74                    lazy_build => 1);
75     has tags => ( isa => ArrayRef[HashRef],
76                    is => 'ro',
77                    lazy_build => 1);
78     has references => ( isa => HashRef[ArrayRef[Str]],
79                         is => 'ro',
80                         lazy_build => 1 );
81
82     method BUILD {
83         $self->$_() for qw/last_change owner description/; # Ensure to build early.
84     }
85
86     ## Public methods
87
88     multi method get_object_or_head (SHA1 $sha1) {
89         $self->get_object($sha1);
90     }
91     multi method get_object_or_head (NonEmptySimpleStr $ref) {
92         my $sha1 = $self->head_hash($ref);
93         $self->get_object($sha1);
94     }    
95     
96     method head_hash (Str $head?) {
97         my $output = $self->run_cmd(qw/rev-parse --verify/, $head || 'HEAD' );
98         confess("No such head: " . $head) unless defined $output;
99
100         my($sha1) = $output =~ /^($SHA1RE)$/;
101         return $sha1;
102     }
103
104     method list_tree (SHA1 $sha1?) {
105         $sha1 ||= $self->head_hash;
106         my $object = $self->get_object($sha1);
107         return @{$object->tree};
108     }
109
110     method get_object (NonEmptySimpleStr $sha1) {
111         unless (is_SHA1($sha1)) {
112             $sha1 = $self->head_hash($sha1);
113         }
114         my $type = $self->run_cmd('cat-file', '-t', $sha1);
115         chomp($type);
116         my $class = 'Gitalist::Git::Object::' . ucfirst($type);
117         $class->new(
118             repository => $self,
119             sha1 => $sha1,
120             type => $type,
121         );
122     }
123
124     method hash_by_path ($base, $path = '', $type?) {
125         $path =~ s{/+$}();
126         # FIXME should this really just take the first result?
127         my @paths = $self->run_cmd('ls-tree', $base, '--', $path)
128             or return;
129         my $line = $paths[0];
130
131         #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa  panic.c'
132         $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
133         return defined $type && $type ne $2
134             ? ()
135                 : $3;
136     }
137
138     method list_revs ( NonEmptySimpleStr :$sha1!,
139                        Int :$count?,
140                        Int :$skip?,
141                        HashRef :$search?,
142                        NonEmptySimpleStr :$file? ) {
143         $sha1 = $self->head_hash($sha1)
144             if !$sha1 || $sha1 !~ $SHA1RE;
145
146         my @search_opts;
147         if ($search) {
148             $search->{type} = 'grep'
149                 if $search->{type} eq 'commit';
150             @search_opts = (
151                 # This seems a little fragile ...
152                 qq[--$search->{type}=$search->{text}],
153                 '--regexp-ignore-case',
154                 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
155             );
156         }
157
158         my $output = $self->run_cmd(
159             'rev-list',
160             '--header',
161             (defined $count ? "--max-count=$count" : ()),
162             (defined $skip ? "--skip=$skip"       : ()),
163             @search_opts,
164             $sha1,
165             '--',
166             ($file ? $file : ()),
167         );
168         return unless $output;
169
170         my @revs = $self->_parse_rev_list($output);
171
172         return @revs;
173     }
174
175     method snapshot (NonEmptySimpleStr :$sha1,
176                  NonEmptySimpleStr :$format
177                ) {
178         # TODO - only valid formats are 'tar' and 'zip'
179         my $formats = { tgz => 'tar', zip => 'zip' };
180         unless ($formats->exists($format)) {
181             die("No such format: $format");
182         }
183         $format = $formats->{$format};
184         my $name = $self->name;
185         $name =~ s,([^/])/*\.git$,$1,;
186         my $filename = $name;
187         $filename .= "-$sha1.$format";
188         $name =~ s/\047/\047\\\047\047/g;
189
190         my @cmd = ('archive', "--format=$format", "--prefix=$name/", $sha1);
191         return ($filename, $self->run_cmd_fh(@cmd));
192         # TODO - support compressed archives
193     }
194
195     method diff ( Gitalist::Git::Object :$commit!,
196                   Bool :$patch?,
197                   Maybe[NonEmptySimpleStr] :$parent?,
198                   NonEmptySimpleStr :$filename?
199               ) {
200               return $commit->diff( patch => $patch,
201                                     parent => $parent,
202                                     filename => $filename);
203     }
204
205     method reflog (@logargs) {
206         my @entries
207             =  $self->run_cmd(qw(log -g), @logargs)
208                 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
209
210         #  commit 02526fc15beddf2c64798a947fecdd8d11bf993d
211         #  Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
212         #  Reflog message: push
213         #  Author: Foo Barsby <fbarsby@example.com>
214         #  Date:   Thu Sep 17 12:26:05 2009 +0100
215         #
216         #      Merge branch 'abc123'
217
218         return map {
219             # XXX Stuff like this makes me want to switch to Git::PurePerl
220             my($sha1, $type, $author, $date)
221                 = m{
222                        ^ commit \s+ ($SHA1RE)$
223                        .*?
224                        Reflog[ ]message: \s+ (.+?)$ \s+
225                      Author: \s+ ([^<]+) <.*?$ \s+
226                    Date: \s+ (.+?)$
227                }xms;
228
229             pos($_) = index($_, $date) + length $date;
230
231             # Yeah, I just did that.
232             my($msg) = /\G\s+(\S.*)/sg;
233             {
234                 hash    => $sha1,
235                 type    => $type,
236                 author  => $author,
237
238                 # XXX Add DateTime goodness.
239                 date    => $date,
240                 message => $msg,
241             }
242             ;
243         } @entries;
244     }
245
246     ## BUILDERS
247     method _build_util {
248         Gitalist::Git::Util->new(
249             repository => $self,
250         );
251     }
252
253     method _build_description {
254         my $description = "";
255         eval {
256             $description = $self->path->file('description')->slurp;
257             chomp $description;
258         };
259         $description = "Unnamed repository, edit the .git/description file to set a description"
260             if $description eq "Unnamed repository; edit this file 'description' to name the repository.";
261         return $description;
262     }
263
264     method _build_owner {
265         my ($gecos, $name) = $self->__owner;
266         $gecos =~ s/,+$//;
267         return length($gecos) ? $gecos : $name;
268     }
269
270     method _build_last_change {
271         my $last_change;
272         my $output = $self->run_cmd(
273             qw{ for-each-ref --format=%(committer)
274                 --sort=-committerdate --count=1 refs/heads
275           });
276         if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
277             my $dt = DateTime->from_epoch(epoch => $epoch);
278             $dt->set_time_zone($tz);
279             $last_change = $dt;
280         }
281         return $last_change;
282     }
283
284     method _build_heads {
285         my @revlines = $self->run_cmd_list(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
286         my @ret;
287         for my $line (@revlines) {
288             my ($rev, $head, $commiter) = split /\0/, $line, 3;
289             $head =~ s!^refs/heads/!!;
290
291             push @ret, { sha1 => $rev, name => $head };
292
293             #FIXME: That isn't the time I'm looking for..
294             if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
295                 my $dt = DateTime->from_epoch(epoch => $epoch);
296                 $dt->set_time_zone($tz);
297                 $ret[-1]->{last_change} = $dt;
298             }
299         }
300
301         return \@ret;
302     }
303
304     method _build_tags {
305         my @revlines = $self->run_cmd_list('for-each-ref',
306           '--sort=-creatordate',
307           '--format=%(objectname) %(objecttype) %(refname) %(*objectname) %(*objecttype) %(subject)%00%(creator)',
308           'refs/tags'
309         );
310         my @ret;
311         for my $line (@revlines) {
312             my($refinfo, $creatorinfo) = split /\0/, $line;
313             my($rev, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
314             my($creator, $epoch, $tz) = ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
315             $name =~ s!^refs/tags/!!;
316
317             push @ret, { sha1 => $rev, name => $name };
318
319             #FIXME: That isn't the time I'm looking for..
320             if($epoch and $tz) {
321                 my $dt = DateTime->from_epoch(epoch => $epoch);
322                 $dt->set_time_zone($tz);
323                 $ret[-1]->{last_change} = $dt;
324             }
325         }
326
327         return \@ret;
328     }
329
330     method _build_references {
331         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
332         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
333         my @reflist = $self->run_cmd_list(qw(show-ref --dereference))
334             or return;
335         my %refs;
336         for (@reflist) {
337             push @{$refs{$1}}, $2
338                 if m!^($SHA1RE)\srefs/(.*)$!;
339         }
340
341         return \%refs;
342     }
343
344     ## Private methods
345     method _parse_rev_list ($output) {
346         return
347             map  $self->get_gpp_object($_),
348                 grep is_SHA1($_),
349                     map  split(/\n/, $_, 6), split /\0/, $output;
350     }
351
352 } # end class
353
354 __END__
355
356 =head1 NAME
357
358 Gitalist::Git::Repository - Model of a git repository
359
360 =head1 SYNOPSIS
361
362     my $gitrepo = dir('/repo/base/Gitalist');
363     my $repository = Gitalist::Git::Repository->new($gitrepo);
364      $repository->name;        # 'Gitalist'
365      $repository->path;        # '/repo/base/Gitalist/.git'
366      $repository->description; # 'Unnamed repository.'
367
368 =head1 DESCRIPTION
369
370 This class models a git repository, referred to in Gitalist
371 as a "Repository".
372
373
374 =head1 ATTRIBUTES
375
376 =head2 name
377
378 The name of the Repository.  If unspecified, this will be derived from the path to the git repository.
379
380 =head2 path
381
382 L<Path::Class:Dir> for the filesystem path to the git repository.
383
384 =head2 description
385
386 The contents of .git/description.
387
388 =head2 owner
389
390 Owner of the files on the filesystem.
391
392 =head2 last_change
393
394 The L<DateTime> of the last modification of the repository.  This will be C<undef> if the repository has never been used.
395
396 =head2 is_bare
397
398 True if this is a bare git repository.
399
400 =head2 heads
401
402 =head2 tags
403
404 An array of the name and sha1 of all heads/tags in the repository.
405
406 =head2 references
407
408 Hashref of ArrayRefs for each reference.
409
410
411 =head1 METHODS
412
413 =head2 head_hash ($head?)
414
415 Return the sha1 for HEAD, or any specified head.
416
417 =head2 list_tree ($sha1?)
418
419 Return an array of contents for a given tree.
420 The tree is specified by sha1, and defaults to HEAD.
421 Each item is a L<Gitalist::Git::Object>.
422
423 =head2 get_object ($sha1)
424
425 Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
426
427 =head2 hash_by_path ($sha1, $path, $type?)
428
429 Returns the sha1 for a given path, optionally limited by type.
430
431 =head2 list_revs ($sha1, $count?, $skip?, \%search?, $file?)
432
433 Returns a list of revs for the given head ($sha1).
434
435 =head2 snapshot ($sha1, $format)
436
437 Generate an archived snapshot of the repository.
438 $sha1 should be a commit or tree.
439 Returns a filehandle to read from.
440
441 =head2 diff ($commit, $patch?, $parent?, $file?)
442
443 Generate a diff from a given L<Gitalist::Git::Object>.
444
445 =head2 reflog (@lorgargs)
446
447 Return a list of hashes representing each reflog entry.
448
449 FIXME Should this return objects?
450
451
452 =head1 SEE ALSO
453
454 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
455
456
457 =head1 AUTHORS
458
459 See L<Gitalist> for authors.
460
461 =head1 LICENSE
462
463 See L<Gitalist> for the license.
464
465 =cut