1 package Gitalist::Model::Git;
4 use namespace::autoclean;
6 extends 'Catalyst::Model';
7 with 'Catalyst::Component::InstancePerContext';
14 use DateTime::Format::Mail;
15 use File::Stat::ModeString;
16 use List::MoreUtils qw/any zip/;
17 use Scalar::Util qw/blessed/;
18 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
24 Gitalist::Model::Git - the model for git interactions
28 [enter your description here]
34 # Should these live in a separate module? Or perhaps extended Regexp::Common?
35 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
37 # These are static and only need to be setup on app start.
38 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 ); # Fixme - path::class
39 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
40 # These are dynamic and can be different from one request to the next.
41 has project => ( isa => NonEmptySimpleStr, is => 'rw');
42 has gpp => ( isa => 'Git::PurePerl', is => 'rw', lazy_build => 1 );
44 sub build_per_context_instance {
45 my ( $self, $c ) = @_;
47 $self->project( $c->req->param('p') );
49 (my $pd = $self->project_dir( $self->project )) =~ s{/\.git$}();
50 $self->gpp( Git::PurePerl->new(directory => $pd) );
61 $self->git; # Cause lazy value build.
66 my $git = File::Which::which('git');
70 Could not find a git executable.
71 Please specify the which git executable to use in gitweb.yml
79 return Gitalist->config->{repo_dir};
84 A wrapper for the equivalent L<Git::PurePerl> method.
89 my($self, $sha1) = @_;
91 # We either want an object or undef, *not* an empty list.
92 return $self->gpp->get_object($sha1) || undef;
97 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
103 my ($self, $dir) = @_;
105 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
110 Call out to the C<git> binary and return a string consisting of the output.
115 my ($self, @args) = @_;
117 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
119 open my $fh, '-|', $self->git, @args
120 or die "failed to run git command";
121 binmode $fh, ':encoding(UTF-8)';
123 my $output = do { local $/ = undef; <$fh> };
131 The directory under which the given project will reside i.e C<.git/..>
136 my($self, $project) = @_;
138 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
139 ? $project->stringify
140 : $self->dir_from_project_name($project);
143 if -f dir($dir)->file('.git/HEAD');
150 Run a C<git> command in a given project and return the output as a string.
155 my ($self, $project, @args) = @_;
157 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
162 Run a C<git> command for the project specified in the C<p> parameter and
163 return the output as a list of strings corresponding to the lines of output.
168 my($self, @args) = @_;
170 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
172 return $output ? split(/\n/, $output) : ();
177 Returns a hash corresponding to a given project's properties. The keys will
181 description (empty if .git/description is empty/unnamed)
188 my ($self, $project) = @_;
192 $self->get_project_properties(
193 $self->dir_from_project_name($project),
198 =head2 get_project_properties
200 Called by C<project_info> to get a project's properties.
204 sub get_project_properties {
205 my ($self, $dir) = @_;
209 $props{description} = $dir->file('description')->slurp;
210 chomp $props{description};
213 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
214 delete $props{description};
217 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
219 my $output = $self->run_cmd_in($dir, qw{
220 for-each-ref --format=%(committer)
221 --sort=-committerdate --count=1 refs/heads
224 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
225 my $dt = DateTime->from_epoch(epoch => $epoch);
226 $dt->set_time_zone($tz);
227 $props{last_change} = $dt;
235 For the C<repo_dir> specified in the config return an array of projects where
236 each item will contain the contents of L</project_info>.
241 my ($self, $dir) = @_;
243 my $base = dir($dir || $self->repo_dir);
246 my $dh = $base->open;
247 while (my $file = $dh->read) {
248 next if $file =~ /^.{1,2}$/;
250 my $obj = $base->subdir($file);
252 next unless $self->is_git_repo($obj);
254 # XXX Leaky abstraction alert!
255 my $is_bare = !-d $obj->subdir('.git');
257 my $name = (File::Spec->splitdir($obj))[-1];
259 name => ($name . ( $is_bare ? '' : '/.git' )),
260 $self->get_project_properties(
261 $is_bare ? $obj : $obj->subdir('.git')
266 return [sort { $a->{name} cmp $b->{name} } @ret];
269 =head2 dir_from_project_name
271 Get the corresponding directory of a given project.
275 sub dir_from_project_name {
276 my ($self, $project) = @_;
278 return dir($self->repo_dir)->subdir($project);
283 Find the hash of a given head (defaults to HEAD) of given (or current) project.
288 my ($self, $head, $project) = @_;
290 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
291 return unless defined $output;
293 my($sha1) = $output =~ /^($SHA1RE)$/;
299 For a given tree sha1 return an array describing the tree's contents. Where
300 the keys for each item will be:
310 my ($self, $rev, $project) = @_;
312 $project ||= $self->project;
313 $rev ||= $self->head_hash($project);
315 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
316 return unless defined $output;
319 for my $line (split /\0/, $output) {
320 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
324 # XXX I wonder why directories always turn up as 040000 ...
325 modestr => $self->get_object_mode_string({mode=>oct $mode}),
335 =head2 get_object_mode_string
337 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
341 sub get_object_mode_string {
342 my ($self, $object) = @_;
344 return unless $object && $object->{mode};
345 return mode_to_string($object->{mode});
348 =head2 get_object_type
352 sub get_object_type {
353 my ($self, $object, $project) = @_;
355 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
356 return unless $output;
363 Return the contents of a given file.
368 my ($self, $object, $project) = @_;
370 my $type = $self->get_object_type($object);
371 die "object `$object' is not a file\n"
372 if (!defined $type || $type ne 'blob');
374 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
375 return unless $output;
382 For a given sha1 and path find the corresponding hash. Useful for find blobs.
387 my($self, $base, $path, $type) = @_;
391 my($line) = $self->command('ls-tree', $base, '--', $path)
394 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
395 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
396 return defined $type && $type ne $2
403 Check whether a given rev is valid i.e looks like a sha1.
408 my ($self, $rev) = @_;
411 return ($rev =~ /^($SHA1RE)$/);
416 Provides the raw output of a diff.
420 # gitweb uses the following sort of command for diffing merges:
421 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index --cc 316cf158df3f6207afbae7270bcc5ba0 --
422 # and for regular diffs
423 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index 2e3454ca0749641b42f063730b0090e1 316cf158df3f6207afbae7270bcc5ba0 --
426 my ($self, @args) = @_;
428 return $self->command(
429 qw(diff-tree -r -M --no-commit-id --full-index),
435 diff --git a/TODO b/TODO
436 index 6a05e77..2071fd0 100644
440 * An action to find what branches have been merged, either as a list or through a search mechanism.
441 * An action to find which branches a given commit is on.
442 * Fix any not text/html bits e.g the patch action.
443 -* Simplify the creation of links.
444 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
445 index 706d024..7fac165 100644
446 --- a/lib/Gitalist/Controller/Root.pm
447 +++ b/lib/Gitalist/Controller/Root.pm
448 @@ -157,23 +157,6 @@ sub shortlog : Local {
454 -The tree of a given commit.
459 Returns a list of diff chunks corresponding to the files contained in the diff
460 and some associated metadata.
464 # XXX Ideally this would return a wee object instead of ad hoc structures.
466 my($self, %args) = @_;
468 # So either a parent is specifed, or we use the commit's parent if there's
469 # only one, otherwise it was a merge commit.
470 my $parent = $args{parent}
472 : @{$args{commit}->parents} <= 1
473 ? $args{commit}->parent_sha1
476 ( $args{file} ? ('--', $args{file}) : () ),
479 my @out = $self->raw_diff(
480 ( $args{patch} ? '--patch-with-raw' : () ),
481 $parent, $args{commit}->sha1, @etc
484 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
485 my @difftree = $self->parse_diff_tree(\@out);
490 # The blank line between the tree and the patch.
493 # XXX And no I'm not happy about having diff return tree + patch.
494 return \@difftree, [$self->parse_diff(@out)];
498 my($self, @diff) = @_;
502 # This regex is a little pathological.
503 if(m{^diff --git (a/(.*?)) (b/\2)}) {
514 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
515 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
519 # XXX Somewhat hacky. Ahem.
520 $ret[-1]{diff} .= "$_\n";
526 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
527 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
529 =head2 parse_diff_tree
531 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
532 to the C<diff-tree> output.
536 sub parse_diff_tree {
537 my($self, $diff) = @_;
539 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
541 while($diff->[0] =~ /^:\d+/) {
542 local $_ = shift @$diff;
543 # see. man git-diff-tree for more info
544 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
545 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
546 my %line = zip @keys, @vals;
547 # Some convenience keys
548 $line{file} = $line{src};
549 $line{sha1} = $line{sha1dst};
550 $line{is_new} = $line{sha1src} =~ /^0+$/;
557 =head2 parse_rev_list
559 Given the output of the C<rev-list> command return a list of hashes.
564 my ($self, $output) = @_;
567 my @revs = split /\0/, $output;
569 for my $rev (split /\0/, $output) {
570 for my $line (split /\n/, $rev, 6) {
574 if ($self->valid_rev($line)) {
575 push @ret, $self->get_object($line);
585 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
591 my ($self, %args) = @_;
593 $args{sha1} ||= $self->head_hash($args{project});
595 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
597 (defined $args{ count } ? "--max-count=$args{count}" : ()),
598 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
601 ($args{file} ? $args{file} : ()),
603 return unless $output;
605 my @revs = $self->parse_rev_list($output);
612 Get a single piece of revision information for a given sha1.
617 my($self, $rev, $project) = @_;
619 return unless $self->valid_rev($rev);
621 return $self->list_revs(
622 rev => $rev, count => 1,
623 ( $project ? (project => $project) : () )
629 Calls the C<reflog> command and returns a list of hashes.
634 my ($self, @logargs) = @_;
637 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
638 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
641 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
642 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
644 Author: Foo Barsby <fbarsby@example.com>
645 Date: Thu Sep 17 12:26:05 2009 +0100
647 Merge branch 'abc123'
652 # XXX Stuff like this makes me want to switch to Git::PurePerl
653 my($sha1, $type, $author, $date)
655 ^ commit \s+ ($SHA1RE)$
657 Reflog[ ]message: \s+ (.+?)$ \s+
658 Author: \s+ ([^<]+) <.*?$ \s+
662 pos($_) = index($_, $date) + length $date;
664 # Yeah, I just did that.
666 my($msg) = /\G\s+(\S.*)/sg;
673 # XXX Add DateTime goodness.
682 Returns an array of hashes representing the heads (aka branches) for the
683 given, or current, project.
688 my ($self, $project) = @_;
690 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
693 for my $line (@output) {
694 my ($rev, $head, $commiter) = split /\0/, $line, 3;
695 $head =~ s!^refs/heads/!!;
697 push @ret, { sha1 => $rev, name => $head };
699 #FIXME: That isn't the time I'm looking for..
700 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
701 my $dt = DateTime->from_epoch(epoch => $epoch);
702 $dt->set_time_zone($tz);
703 $ret[-1]->{last_change} = $dt;
712 For a given sha1 check which branches currently point at it.
717 my($self, $sha1) = @_;
719 my $refs = $self->references->{$sha1};
721 return $refs ? @$refs : ();
726 A wrapper for C<git show-ref --dereference>. Based on gitweb's
727 C<git_get_references>.
734 return $self->{references}
735 if $self->{references};
737 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
738 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
739 my @reflist = $self->command(qw(show-ref --dereference))
744 push @{$refs{$1}}, $2
745 if m!^($SHA1RE)\srefs/(.*)$!;
748 return $self->{references} = \%refs;
753 __PACKAGE__->meta->make_immutable;