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