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