Move Repository->hash_by_path to Commit->sha_by_path.
[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/;
3a6dd969 6 use MooseX::Types::Path::Class qw/Dir/;
829d41ed 7 use MooseX::Types::Moose qw/Str Maybe Bool HashRef ArrayRef/;
3a6dd969 8 use Gitalist::Git::Types qw/SHA1/;
2e79039a 9 use Moose::Autobox;
77edf882 10 use List::MoreUtils qw/any zip/;
3a6dd969 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;
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,
3a6dd969 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
3a6dd969 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 {
2c130350 58 -d $_[0]->path->parent->subdir($_[0]->name)
b5b638f7 59 ? 1 : 0
60 },
61 );
cc88eca5 62 has heads => ( isa => ArrayRef[HashRef],
63 is => 'ro',
3a6dd969 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 {
4dacb4b2 73 $self->$_() for qw/last_change owner description /; # Ensure to build early.
01ced85b 74 }
75
bba40bd5 76 ## Public methods
dcb1b927 77
bc50b7ec 78 method get_object_or_head (NonEmptySimpleStr $ref) {
79 my $sha1 = is_SHA1($ref) ? $ref : $self->head_hash($ref);
dcb1b927 80 $self->get_object($sha1);
81 }
bc50b7ec 82
32a371cc 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;
29debefd 86
32a371cc 87 my($sha1) = $output =~ /^($SHA1RE)$/;
88 return $sha1;
56b6dbe6 89 }
90
ceef0cf1 91 method list_tree (SHA1 $sha1?) {
a8a8f8f9 92 $sha1 ||= $self->head_hash;
b36b7e0b 93 my $object = $self->get_object($sha1);
94 return @{$object->tree};
a8a8f8f9 95 }
96
8bb7649b 97 method get_object (NonEmptySimpleStr $sha1) {
ceef0cf1 98 unless (is_SHA1($sha1)) {
8bb7649b 99 $sha1 = $self->head_hash($sha1);
100 }
e1307124 101 my $type = $self->run_cmd('cat-file', '-t', $sha1);
102 chomp($type);
467fa7d9 103 my $class = 'Gitalist::Git::Object::' . ucfirst($type);
104 $class->new(
82bc0f05 105 repository => $self,
54368e9d 106 sha1 => $sha1,
f3083570 107 type => $type,
54368e9d 108 );
109 }
8bb7649b 110
4111e151 111 method list_revs ( NonEmptySimpleStr :$sha1!,
112 Int :$count?,
113 Int :$skip?,
114 HashRef :$search?,
05e8b4d0 115 NonEmptySimpleStr :$file? ) {
4111e151 116 $sha1 = $self->head_hash($sha1)
117 if !$sha1 || $sha1 !~ $SHA1RE;
118
c1a9cd73 119 my @search_opts;
53a9d6de 120 if ($search and exists $search->{text}) {
4111e151 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
cc88eca5 143 my @revs = $self->_parse_rev_list($output);
4111e151 144
145 return @revs;
146 }
147
bba40bd5 148 method snapshot (NonEmptySimpleStr :$sha1,
30db8f5b 149 NonEmptySimpleStr :$format
150 ) {
bba40bd5 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
2e79039a 166 }
54368e9d 167
d8abdf1c 168 method reflog (@logargs) {
169 my @entries
170 = $self->run_cmd(qw(log -g), @logargs)
171 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
172
05e8b4d0 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'
d8abdf1c 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
cc88eca5 209 ## BUILDERS
50d45f00 210 method _build_util {
32a371cc 211 Gitalist::Git::Util->new(
82bc0f05 212 repository => $self,
32a371cc 213 );
214 }
215
216 method _build_description {
76c97bf6 217 my $description = "";
5d8568c6 218 eval {
76c97bf6 219 $description = $self->path->file('description')->slurp;
220 chomp $description;
5d8568c6 221 };
3c12ecb7 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.";
76c97bf6 224 return $description;
32a371cc 225 }
226
227 method _build_owner {
e66671b8 228 my ($gecos, $name) = map { decode(langinfo(CODESET), $_) } (getpwuid $self->path->stat->uid)[6,0];
32a371cc 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+)$/) {
3a6dd969 240 my $dt = DateTime->from_epoch(epoch => $epoch);
32a371cc 241 $dt->set_time_zone($tz);
242 $last_change = $dt;
243 }
244 return $last_change;
245 }
246
cc88eca5 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+)$/) {
3a6dd969 258 my $dt = DateTime->from_epoch(epoch => $epoch);
cc88eca5 259 $dt->set_time_zone($tz);
260 $ret[-1]->{last_change} = $dt;
261 }
262 }
263
264 return \@ret;
265 }
266
ea19a20c 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)',
c1a9cd73 271 'refs/tags'
ea19a20c 272 );
273 my @ret;
274 for my $line (@revlines) {
275 my($refinfo, $creatorinfo) = split /\0/, $line;
c1a9cd73 276 my($rev, $type, $name, $refid, $reftype, $title) = split(' ', $refinfo, 6);
ea19a20c 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) {
3a6dd969 284 my $dt = DateTime->from_epoch(epoch => $epoch);
ea19a20c 285 $dt->set_time_zone($tz);
286 $ret[-1]->{last_change} = $dt;
287 }
288 }
289
290 return \@ret;
291 }
292
cc88eca5 293 method _build_references {
c1a9cd73 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))
05e8b4d0 297 or return;
cc88eca5 298 my %refs;
05e8b4d0 299 for (@reflist) {
300 push @{$refs{$1}}, $2
301 if m!^($SHA1RE)\srefs/(.*)$!;
302 }
cc88eca5 303
05e8b4d0 304 return \%refs;
cc88eca5 305 }
306
307 ## Private methods
cc88eca5 308 method _parse_rev_list ($output) {
309 return
310 map $self->get_gpp_object($_),
ceef0cf1 311 grep is_SHA1($_),
cc88eca5 312 map split(/\n/, $_, 6), split /\0/, $output;
313 }
314
775e96e0 315} # end class
316
317__END__
318
bba40bd5 319=head1 NAME
320
44a9ed75 321Gitalist::Git::Repository - Model of a git repository
bba40bd5 322
323=head1 SYNOPSIS
324
325 my $gitrepo = dir('/repo/base/Gitalist');
82bc0f05 326 my $repository = Gitalist::Git::Repository->new($gitrepo);
327 $repository->name; # 'Gitalist'
328 $repository->path; # '/repo/base/Gitalist/.git'
329 $repository->description; # 'Unnamed repository.'
bba40bd5 330
331=head1 DESCRIPTION
332
333This class models a git repository, referred to in Gitalist
87581f05 334as a "Repository".
bba40bd5 335
8ba87261 336
bba40bd5 337=head1 ATTRIBUTES
338
339=head2 name
340
87581f05 341The name of the Repository. If unspecified, this will be derived from the path to the git repository.
bba40bd5 342
bba40bd5 343=head2 path
344
8ba87261 345L<Path::Class:Dir> for the filesystem path to the git repository.
bba40bd5 346
bba40bd5 347=head2 description
348
8ba87261 349The contents of .git/description.
bba40bd5 350
bba40bd5 351=head2 owner
352
8ba87261 353Owner of the files on the filesystem.
bba40bd5 354
bba40bd5 355=head2 last_change
356
8ba87261 357The L<DateTime> of the last modification of the repository. This will be C<undef> if the repository has never been used.
bba40bd5 358
bba40bd5 359=head2 is_bare
360
8ba87261 361True if this is a bare git repository.
bba40bd5 362
bba40bd5 363=head2 heads
364
bba40bd5 365=head2 tags
366
8ba87261 367An array of the name and sha1 of all heads/tags in the repository.
bba40bd5 368
369=head2 references
370
371Hashref of ArrayRefs for each reference.
372
8ba87261 373
bba40bd5 374=head1 METHODS
375
376=head2 head_hash ($head?)
377
378Return the sha1 for HEAD, or any specified head.
379
bba40bd5 380=head2 list_tree ($sha1?)
381
382Return an array of contents for a given tree.
383The tree is specified by sha1, and defaults to HEAD.
384Each item is a L<Gitalist::Git::Object>.
385
bba40bd5 386=head2 get_object ($sha1)
387
388Return an appropriate subclass of L<Gitalist::Git::Object> for the given sha1.
389
8ba87261 390=head2 list_revs ($sha1, $count?, $skip?, \%search?, $file?)
bba40bd5 391
392Returns a list of revs for the given head ($sha1).
393
8ba87261 394=head2 snapshot ($sha1, $format)
bba40bd5 395
396Generate an archived snapshot of the repository.
397$sha1 should be a commit or tree.
398Returns a filehandle to read from.
399
8ba87261 400=head2 diff ($commit, $patch?, $parent?, $file?)
bba40bd5 401
402Generate a diff from a given L<Gitalist::Git::Object>.
403
8ba87261 404=head2 reflog (@lorgargs)
bba40bd5 405
406Return a list of hashes representing each reflog entry.
407
408FIXME Should this return objects?
409
bba40bd5 410
b5b638f7 411=head1 SEE ALSO
412
413L<Gitalist::Git::Util> L<Gitalist::Git::Object>
414
8ba87261 415
775e96e0 416=head1 AUTHORS
b5b638f7 417
775e96e0 418See L<Gitalist> for authors.
b5b638f7 419
420=head1 LICENSE
421
775e96e0 422See L<Gitalist> for the license.
b5b638f7 423
424=cut