1 package Gitalist::Model::Git;
4 use namespace::autoclean;
6 BEGIN { extends 'Catalyst::Model' }
13 use DateTime::Format::Mail;
14 use File::Stat::ModeString;
15 use List::MoreUtils qw/any/;
16 use Scalar::Util qw/blessed/;
17 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
21 Gitalist::Model::Git - the model for git interactions
25 [enter your description here]
31 # Should these live in a separate module? Or perhaps extended Regexp::Common?
32 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
34 has project => ( isa => NonEmptySimpleStr, is => 'rw');
35 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 ); # Fixme - path::class
36 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
44 $self->git; # Cause lazy value build.
51 #isa => 'Git::PurePerl'
57 (my $pd = $self->project_dir( $self->project )) =~ s{/\.git$}();
58 return Git::PurePerl->new(
65 my $git = File::Which::which('git');
69 Could not find a git executable.
70 Please specify the which git executable to use in gitweb.yml
78 return Gitalist->config->{repo_dir};
83 A wrapper for the equivalent L<Git::PurePerl> method.
88 $_[0]->gpp->get_object($_[1]);
93 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
99 my ($self, $dir) = @_;
101 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
106 Call out to the C<git> binary and return a string consisting of the output.
111 my ($self, @args) = @_;
113 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
115 open my $fh, '-|', $self->git, @args
116 or die "failed to run git command";
117 binmode $fh, ':encoding(UTF-8)';
119 my $output = do { local $/ = undef; <$fh> };
127 The directory under which the given project will reside i.e C<.git/..>
132 my($self, $project) = @_;
134 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
135 ? $project->stringify
136 : $self->dir_from_project_name($project);
139 if -f dir($dir)->file('.git/HEAD');
146 Run a C<git> command in a given project and return the output as a string.
151 my ($self, $project, @args) = @_;
153 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
158 Run a C<git> command for the project specified in the C<p> parameter and
159 return the output as a list of strings corresponding to the lines of output.
164 my($self, @args) = @_;
166 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
168 return $output ? split(/\n/, $output) : ();
173 Returns a hash corresponding to a given project's properties. The keys will
177 description (empty if .git/description is empty/unnamed)
184 my ($self, $project) = @_;
188 $self->get_project_properties(
189 $self->dir_from_project_name($project),
194 =head2 get_project_properties
196 Called by C<project_info> to get a project's properties.
200 sub get_project_properties {
201 my ($self, $dir) = @_;
205 $props{description} = $dir->file('description')->slurp;
206 chomp $props{description};
209 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
210 delete $props{description};
213 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
215 my $output = $self->run_cmd_in($dir, qw{
216 for-each-ref --format=%(committer)
217 --sort=-committerdate --count=1 refs/heads
220 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
221 my $dt = DateTime->from_epoch(epoch => $epoch);
222 $dt->set_time_zone($tz);
223 $props{last_change} = $dt;
231 For the C<repo_dir> specified in the config return an array of projects where
232 each item will contain the contents of L</project_info>.
237 my ($self, $dir) = @_;
239 my $base = dir($dir || $self->repo_dir);
242 my $dh = $base->open;
243 while (my $file = $dh->read) {
244 next if $file =~ /^.{1,2}$/;
246 my $obj = $base->subdir($file);
248 next unless $self->is_git_repo($obj);
250 # XXX Leaky abstraction alert!
251 my $is_bare = !-d $obj->subdir('.git');
253 my $name = (File::Spec->splitdir($obj))[-1];
255 name => ($name . ( $is_bare ? '' : '/.git' )),
256 $self->get_project_properties(
257 $is_bare ? $obj : $obj->subdir('.git')
262 return [sort { $a->{name} cmp $b->{name} } @ret];
265 =head2 dir_from_project_name
267 Get the corresponding directory of a given project.
271 sub dir_from_project_name {
272 my ($self, $project) = @_;
274 return dir($self->repo_dir)->subdir($project);
279 Find the C<HEAD> of given (or current) project.
284 my ($self, $project) = @_;
286 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify HEAD/ );
287 return unless defined $output;
289 my ($head) = $output =~ /^($SHA1RE)$/;
295 For a given tree sha1 return an array describing the tree's contents. Where
296 the keys for each item will be:
306 my ($self, $rev, $project) = @_;
308 $project ||= $self->project;
309 $rev ||= $self->head_hash($project);
311 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
312 return unless defined $output;
315 for my $line (split /\0/, $output) {
316 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
320 modestr => $self->get_object_mode_string({mode=>oct $mode}),
330 =head2 get_object_mode_string
332 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
336 sub get_object_mode_string {
337 my ($self, $object) = @_;
339 return unless $object && $object->{mode};
340 return mode_to_string($object->{mode});
343 =head2 get_object_type
347 sub get_object_type {
348 my ($self, $object, $project) = @_;
350 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
351 return unless $output;
358 Return the contents of a given file.
363 my ($self, $object, $project) = @_;
365 my $type = $self->get_object_type($object);
366 die "object `$object' is not a file\n"
367 if (!defined $type || $type ne 'blob');
369 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
370 return unless $output;
377 For a given sha1 and path find the corresponding hash. Useful for find blobs.
382 my($self, $base, $path, $type) = @_;
386 my($line) = $self->command('ls-tree', $base, '--', $path)
389 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
390 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
391 return defined $type && $type ne $2
398 Check whether a given rev is valid i.e looks like a sha1.
403 my ($self, $rev) = @_;
406 return ($rev =~ /^($SHA1RE)$/);
416 my ($self, @revs) = @_;
418 croak("Gitalist::Model::Git::diff needs either one or two revisions, got: @revs")
421 || any { !$self->valid_rev($_) } @revs;
423 my $output = $self->run_cmd_in($self->project, 'diff', @revs);
424 return unless $output;
429 =head2 parse_rev_list
431 Given the output of the C<rev-list> command return a list of hashes.
436 my ($self, $output) = @_;
439 my @revs = split /\0/, $output;
441 for my $rev (split /\0/, $output) {
442 for my $line (split /\n/, $rev, 6) {
446 if ($self->valid_rev($line)) {
447 push @ret, $self->get_object($line);
457 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
463 my ($self, %args) = @_;
465 $args{rev} ||= $self->head_hash($args{project});
467 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
469 (defined $args{ count } ? "--max-count=$args{count}" : ()),
470 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
473 ($args{file} ? $args{file} : ()),
475 return unless $output;
477 my @revs = $self->parse_rev_list($output);
484 Get a single piece of revision information for a given sha1.
489 my($self, $rev, $project) = @_;
491 return unless $self->valid_rev($rev);
493 return $self->list_revs(
494 rev => $rev, count => 1,
495 ( $project ? (project => $project) : () )
501 Calls the C<reflog> command and returns a list of hashes.
506 my ($self, @logargs) = @_;
509 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
510 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
514 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
515 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
517 Author: Foo Barsby <fbarsby@example.com>
518 Date: Thu Sep 17 12:26:05 2009 +0100
520 Merge branch 'abc123'
525 # XXX Stuff like this makes me want to switch to Git::PurePerl
526 my($sha1, $type, $author, $date)
528 ^ commit \s+ ($SHA1RE)$
530 Reflog[ ]message: \s+ (.+?)$ \s+
531 Author: \s+ ([^<]+) <.*?$ \s+
535 pos($_) = index($_, $date) + length $date;
537 # Yeah, I just did that.
539 my($msg) = /\G\s+(\S.*)/sg;
546 # XXX Add DateTime goodness.
555 Returns an array of hashes representing the heads (aka branches) for the
556 given, or current, project.
561 my ($self, $project) = @_;
563 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
566 for my $line (@output) {
567 my ($rev, $head, $commiter) = split /\0/, $line, 3;
568 $head =~ s!^refs/heads/!!;
570 push @ret, { sha1 => $rev, name => $head };
572 #FIXME: That isn't the time I'm looking for..
573 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
574 my $dt = DateTime->from_epoch(epoch => $epoch);
575 $dt->set_time_zone($tz);
576 $ret[-1]->{last_change} = $dt;
585 For a given sha1 check which branches currently point at it.
590 my($self, $sha1) = @_;
592 my $refs = $self->references->{$sha1};
594 return $refs ? @$refs : ();
599 A wrapper for C<git show-ref --dereference>. Based on gitweb's
600 C<git_get_references>.
607 return $self->{references}
608 if $self->{references};
610 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
611 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
612 my @reflist = $self->command(qw(show-ref --dereference))
617 push @{$refs{$1}}, $2
618 if m!^($SHA1RE)\srefs/(.*)$!;
621 return $self->{references} = \%refs;
626 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
627 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M TODO
628 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M lib/Gitalist/Controller/Root.pm
629 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M lib/Gitalist/View/Default.pm
630 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A lib/Gitalist/View/SyntaxHighlight.pm
631 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A root/static/css/syntax-dark.css
632 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
636 use List::MoreUtils qw(zip);
637 # XXX Hrm, getting called twice, not sure why.
640 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
641 to the C<diff-tree> output.
646 my($self, $commit) = @_;
648 my @dtout = $self->command(
649 # XXX should really deal with multple parents ...
650 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
653 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
655 # see. man git-diff-tree for more info
656 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
657 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
658 my %line = zip @keys, @vals;
659 # Some convenience keys
660 $line{file} = $line{src};
661 $line{sha1} = $line{sha1dst};
662 $line{is_new} = $line{sha1src} =~ /^0+$/;
671 __PACKAGE__->meta->make_immutable;