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