Introduce Gitalist::Git::Head.
[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             my ($sha1, $name, $commitinfo) = split /\0/, $line, 3;
242             $name =~ s!^refs/heads/!!;
243
244             my ($committer, $epoch, $tz) =
245                 $commitinfo =~ /(.*)\s(\d+)\s+([+-]\d+)$/;
246             my $dt = DateTime->from_epoch(
247                 epoch => $epoch,
248                 time_zone => $tz,
249             );
250             my $head = Gitalist::Git::Head->new(
251                 sha1 => $sha1,
252                 name => $name,
253                 committer => $committer,
254                 last_change => $dt,
255             );
256             push @ret, $head;
257         }
258
259         return \@ret;
260     }
261
262     method _build_tags {
263         my @revlines = $self->run_cmd_list('for-each-ref',
264           '--sort=-creatordate',
265           '--format=%(objectname) %(objecttype) %(refname) %(*objectname) %(*objecttype) %(subject)%00%(creator)',
266           'refs/tags'
267         );
268         my @ret;
269         for my $line (@revlines) {
270             my($refinfo, $creatorinfo) = split /\0/, $line;
271             my($rev, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
272             my($creator, $epoch, $tz) = ($creatorinfo =~ /^(.*) ([0-9]+) (.*)$/);
273             $name =~ s!^refs/tags/!!;
274
275             push @ret, { sha1 => $rev, name => $name };
276
277             #FIXME: That isn't the time I'm looking for..
278             if($epoch and $tz) {
279                 my $dt = DateTime->from_epoch(epoch => $epoch);
280                 $dt->set_time_zone($tz);
281                 $ret[-1]->{last_change} = $dt;
282             }
283         }
284
285         return \@ret;
286     }
287
288     method _build_references {
289         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
290         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
291         my @reflist = $self->run_cmd_list(qw(show-ref --dereference))
292             or return;
293         my %refs;
294         for (@reflist) {
295             push @{$refs{$1}}, $2
296                 if m!^($SHA1RE)\srefs/(.*)$!;
297         }
298
299         return \%refs;
300     }
301
302     ## Private methods
303     method _parse_rev_list ($output) {
304         return
305             map  $self->get_gpp_object($_),
306                 grep is_SHA1($_),
307                     map  split(/\n/, $_, 6), split /\0/, $output;
308     }
309
310 } # end class
311
312 __END__
313
314 =head1 NAME
315
316 Gitalist::Git::Repository - Model of a git repository
317
318 =head1 SYNOPSIS
319
320     my $gitrepo = dir('/repo/base/Gitalist');
321     my $repository = Gitalist::Git::Repository->new($gitrepo);
322      $repository->name;        # 'Gitalist'
323      $repository->path;        # '/repo/base/Gitalist/.git'
324      $repository->description; # 'Unnamed repository.'
325
326 =head1 DESCRIPTION
327
328 This class models a git repository, referred to in Gitalist
329 as a "Repository".
330
331
332 =head1 ATTRIBUTES
333
334 =head2 name
335
336 The name of the Repository.  If unspecified, this will be derived from the path to the git repository.
337
338 =head2 path
339
340 L<Path::Class:Dir> for the filesystem path to the git repository.
341
342 =head2 description
343
344 The contents of .git/description.
345
346 =head2 owner
347
348 Owner of the files on the filesystem.
349
350 =head2 last_change
351
352 The L<DateTime> of the last modification of the repository.  This will be C<undef> if the repository has never been used.
353
354 =head2 is_bare
355
356 True if this is a bare git repository.
357
358 =head2 heads
359
360 =head2 tags
361
362 An array of the name and sha1 of all heads/tags in the repository.
363
364 =head2 references
365
366 Hashref of ArrayRefs for each reference.
367
368
369 =head1 METHODS
370
371 =head2 head_hash ($head?)
372
373 Return the sha1 for HEAD, or any specified head.
374
375 =head2 get_object ($sha1)
376
377 Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
378
379 =head2 list_revs ($sha1, $count?, $skip?, \%search?, $file?)
380
381 Returns a list of revs for the given head ($sha1).
382
383 =head2 snapshot ($sha1, $format)
384
385 Generate an archived snapshot of the repository.
386 $sha1 should be a commit or tree.
387 Returns a filehandle to read from.
388
389 =head2 diff ($commit, $patch?, $parent?, $file?)
390
391 Generate a diff from a given L<Gitalist::Git::Object>.
392
393 =head2 reflog (@lorgargs)
394
395 Return a list of hashes representing each reflog entry.
396
397 FIXME Should this return objects?
398
399
400 =head1 SEE ALSO
401
402 L<Gitalist::Git::Util> L<Gitalist::Git::Object>
403
404
405 =head1 AUTHORS
406
407 See L<Gitalist> for authors.
408
409 =head1 LICENSE
410
411 See L<Gitalist> for the license.
412
413 =cut