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