Further win32 related hacks.
[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             no warnings; # where's this warning coming from?
151             @search_opts = (
152                 # This seems a little fragile ...
153                 qq[--$search->{type}=$search->{text}],
154                 '--regexp-ignore-case',
155                 $search->{regexp} ? '--extended-regexp' : '--fixed-strings'
156             );
157         }
158
159         my $output = $self->run_cmd(
160             'rev-list',
161             '--header',
162             (defined $count ? "--max-count=$count" : ()),
163             (defined $skip ? "--skip=$skip"       : ()),
164             @search_opts,
165             $sha1,
166             '--',
167             ($file ? $file : ()),
168         );
169         return unless $output;
170
171         my @revs = $self->_parse_rev_list($output);
172
173         return @revs;
174     }
175
176     method snapshot (NonEmptySimpleStr :$sha1,
177                  NonEmptySimpleStr :$format
178                ) {
179         # TODO - only valid formats are 'tar' and 'zip'
180         my $formats = { tgz => 'tar', zip => 'zip' };
181         unless ($formats->exists($format)) {
182             die("No such format: $format");
183         }
184         $format = $formats->{$format};
185         my $name = $self->name;
186         $name =~ s,([^/])/*\.git$,$1,;
187         my $filename = $name;
188         $filename .= "-$sha1.$format";
189         $name =~ s/\047/\047\\\047\047/g;
190
191         my @cmd = ('archive', "--format=$format", "--prefix=$name/", $sha1);
192         return ($filename, $self->run_cmd_fh(@cmd));
193         # TODO - support compressed archives
194     }
195
196     method diff ( Gitalist::Git::Object :$commit!,
197                   Bool :$patch?,
198                   Maybe[NonEmptySimpleStr] :$parent?,
199                   NonEmptySimpleStr :$filename?
200               ) {
201               return $commit->diff( patch => $patch,
202                                     parent => $parent,
203                                     filename => $filename);
204     }
205
206     method reflog (@logargs) {
207         my @entries
208             =  $self->run_cmd(qw(log -g), @logargs)
209                 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
210
211         #  commit 02526fc15beddf2c64798a947fecdd8d11bf993d
212         #  Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
213         #  Reflog message: push
214         #  Author: Foo Barsby <fbarsby@example.com>
215         #  Date:   Thu Sep 17 12:26:05 2009 +0100
216         #
217         #      Merge branch 'abc123'
218
219         return map {
220             # XXX Stuff like this makes me want to switch to Git::PurePerl
221             my($sha1, $type, $author, $date)
222                 = m{
223                        ^ commit \s+ ($SHA1RE)$
224                        .*?
225                        Reflog[ ]message: \s+ (.+?)$ \s+
226                      Author: \s+ ([^<]+) <.*?$ \s+
227                    Date: \s+ (.+?)$
228                }xms;
229
230             pos($_) = index($_, $date) + length $date;
231
232             # Yeah, I just did that.
233             my($msg) = /\G\s+(\S.*)/sg;
234             {
235                 hash    => $sha1,
236                 type    => $type,
237                 author  => $author,
238
239                 # XXX Add DateTime goodness.
240                 date    => $date,
241                 message => $msg,
242             }
243             ;
244         } @entries;
245     }
246
247     ## BUILDERS
248     method _build_util {
249         Gitalist::Git::Util->new(
250             repository => $self,
251         );
252     }
253
254     method _build_description {
255         my $description = "";
256         eval {
257             $description = $self->path->file('description')->slurp;
258             chomp $description;
259         };
260         $description = "Unnamed repository, edit the .git/description file to set a description"
261             if $description eq "Unnamed repository; edit this file 'description' to name the repository.";
262         return $description;
263     }
264
265     method _build_owner {
266         my ($gecos, $name) = $self->__owner;
267         $gecos =~ s/,+$//;
268         return length($gecos) ? $gecos : $name;
269     }
270
271     method _build_last_change {
272         my $last_change;
273         my $output = $self->run_cmd(
274             qw{ for-each-ref --format=%(committer)
275                 --sort=-committerdate --count=1 refs/heads
276           });
277         if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
278             my $dt = DateTime->from_epoch(epoch => $epoch);
279             $dt->set_time_zone($tz);
280             $last_change = $dt;
281         }
282         return $last_change;
283     }
284
285     method _build_heads {
286         my @revlines = $self->run_cmd_list(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
287         my @ret;
288         for my $line (@revlines) {
289             my ($rev, $head, $commiter) = split /\0/, $line, 3;
290             $head =~ s!^refs/heads/!!;
291
292             push @ret, { sha1 => $rev, name => $head };
293
294             #FIXME: That isn't the time I'm looking for..
295             if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
296                 my $dt = DateTime->from_epoch(epoch => $epoch);
297                 $dt->set_time_zone($tz);
298                 $ret[-1]->{last_change} = $dt;
299             }
300         }
301
302         return \@ret;
303     }
304
305     method _build_tags {
306         my @revlines = $self->run_cmd_list('for-each-ref',
307           '--sort=-creatordate',
308           '--format=%(objectname) %(objecttype) %(refname) %(*objectname) %(*objecttype) %(subject)%00%(creator)',
309           'refs/tags'
310         );
311         my @ret;
312         for my $line (@revlines) {
313             my($refinfo, $creatorinfo) = split /\0/, $line;
314             my($rev, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
315             my($creator, $epoch, $tz) = ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
316             $name =~ s!^refs/tags/!!;
317
318             push @ret, { sha1 => $rev, name => $name };
319
320             #FIXME: That isn't the time I'm looking for..
321             if($epoch and $tz) {
322                 my $dt = DateTime->from_epoch(epoch => $epoch);
323                 $dt->set_time_zone($tz);
324                 $ret[-1]->{last_change} = $dt;
325             }
326         }
327
328         return \@ret;
329     }
330
331     method _build_references {
332         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
333         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
334         my @reflist = $self->run_cmd_list(qw(show-ref --dereference))
335             or return;
336         my %refs;
337         for (@reflist) {
338             push @{$refs{$1}}, $2
339                 if m!^($SHA1RE)\srefs/(.*)$!;
340         }
341
342         return \%refs;
343     }
344
345     ## Private methods
346     method _parse_rev_list ($output) {
347         return
348             map  $self->get_gpp_object($_),
349                 grep is_SHA1($_),
350                     map  split(/\n/, $_, 6), split /\0/, $output;
351     }
352
353 } # end class
354
355 __END__
356
357 =head1 NAME
358
359 Gitalist::Git::Repository - Model of a git repository
360
361 =head1 SYNOPSIS
362
363     my $gitrepo = dir('/repo/base/Gitalist');
364     my $repository = Gitalist::Git::Repository->new($gitrepo);
365      $repository->name;        # 'Gitalist'
366      $repository->path;        # '/repo/base/Gitalist/.git'
367      $repository->description; # 'Unnamed repository.'
368
369 =head1 DESCRIPTION
370
371 This class models a git repository, referred to in Gitalist
372 as a "Repository".
373
374
375 =head1 ATTRIBUTES
376
377 =head2 name
378
379 The name of the Repository.  If unspecified, this will be derived from the path to the git repository.
380
381 =head2 path
382
383 L<Path::Class:Dir> for the filesystem path to the git repository.
384
385 =head2 description
386
387 The contents of .git/description.
388
389 =head2 owner
390
391 Owner of the files on the filesystem.
392
393 =head2 last_change
394
395 The L<DateTime> of the last modification of the repository.  This will be C<undef> if the repository has never been used.
396
397 =head2 is_bare
398
399 True if this is a bare git repository.
400
401 =head2 heads
402
403 =head2 tags
404
405 An array of the name and sha1 of all heads/tags in the repository.
406
407 =head2 references
408
409 Hashref of ArrayRefs for each reference.
410
411
412 =head1 METHODS
413
414 =head2 head_hash ($head?)
415
416 Return the sha1 for HEAD, or any specified head.
417
418 =head2 list_tree ($sha1?)
419
420 Return an array of contents for a given tree.
421 The tree is specified by sha1, and defaults to HEAD.
422 Each item is a L<Gitalist::Git::Object>.
423
424 =head2 get_object ($sha1)
425
426 Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
427
428 =head2 hash_by_path ($sha1, $path, $type?)
429
430 Returns the sha1 for a given path, optionally limited by type.
431
432 =head2 list_revs ($sha1, $count?, $skip?, \%search?, $file?)
433
434 Returns a list of revs for the given head ($sha1).
435
436 =head2 snapshot ($sha1, $format)
437
438 Generate an archived snapshot of the repository.
439 $sha1 should be a commit or tree.
440 Returns a filehandle to read from.
441
442 =head2 diff ($commit, $patch?, $parent?, $file?)
443
444 Generate a diff from a given L<Gitalist::Git::Object>.
445
446 =head2 reflog (@lorgargs)
447
448 Return a list of hashes representing each reflog entry.
449
450 FIXME Should this return objects?
451
452
453 =head1 SEE ALSO
454
455 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
456
457
458 =head1 AUTHORS
459
460 See L<Gitalist> for authors.
461
462 =head1 LICENSE
463
464 See L<Gitalist> for the license.
465
466 =cut