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