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