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