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