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