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