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