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 # If we don't have a project param it probably means we're at /
49 unless $c->req->param('p');
51 $self->project( $c->req->param('p') );
53 (my $pd = $self->project_dir( $self->project )) =~ s{/\.git$}();
54 $self->gpp( Git::PurePerl->new(directory => $pd) );
65 $self->git; # Cause lazy value build.
70 my $git = File::Which::which('git');
74 Could not find a git executable.
75 Please specify the which git executable to use in gitweb.yml
83 return Gitalist->config->{repo_dir};
88 A wrapper for the equivalent L<Git::PurePerl> method.
93 my($self, $sha1) = @_;
95 # We either want an object or undef, *not* an empty list.
96 return $self->gpp->get_object($sha1) || undef;
101 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
107 my ($self, $dir) = @_;
109 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
114 Call out to the C<git> binary and return a string consisting of the output.
119 my ($self, @args) = @_;
121 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
123 open my $fh, '-|', $self->git, @args
124 or die "failed to run git command";
125 binmode $fh, ':encoding(UTF-8)';
127 my $output = do { local $/ = undef; <$fh> };
135 The directory under which the given project will reside i.e C<.git/..>
140 my($self, $project) = @_;
142 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
143 ? $project->stringify
144 : $self->dir_from_project_name($project);
147 if -f dir($dir)->file('.git/HEAD');
154 Run a C<git> command in a given project and return the output as a string.
159 my ($self, $project, @args) = @_;
161 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
166 Run a C<git> command for the project specified in the C<p> parameter and
167 return the output as a list of strings corresponding to the lines of output.
172 my($self, @args) = @_;
174 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
176 return $output ? split(/\n/, $output) : ();
181 Returns a hash corresponding to a given project's properties. The keys will
185 description (empty if .git/description is empty/unnamed)
192 my ($self, $project) = @_;
196 $self->get_project_properties(
197 $self->dir_from_project_name($project),
202 =head2 get_project_properties
204 Called by C<project_info> to get a project's properties.
208 sub get_project_properties {
209 my ($self, $dir) = @_;
213 $props{description} = $dir->file('description')->slurp;
214 chomp $props{description};
217 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
218 delete $props{description};
221 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
223 my $output = $self->run_cmd_in($dir, qw{
224 for-each-ref --format=%(committer)
225 --sort=-committerdate --count=1 refs/heads
228 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
229 my $dt = DateTime->from_epoch(epoch => $epoch);
230 $dt->set_time_zone($tz);
231 $props{last_change} = $dt;
239 For the C<repo_dir> specified in the config return an array of projects where
240 each item will contain the contents of L</project_info>.
245 my ($self, $dir) = @_;
247 my $base = dir($dir || $self->repo_dir);
250 my $dh = $base->open;
251 while (my $file = $dh->read) {
252 next if $file =~ /^.{1,2}$/;
254 my $obj = $base->subdir($file);
256 next unless $self->is_git_repo($obj);
258 # XXX Leaky abstraction alert!
259 my $is_bare = !-d $obj->subdir('.git');
261 my $name = (File::Spec->splitdir($obj))[-1];
263 name => ($name . ( $is_bare ? '' : '/.git' )),
264 $self->get_project_properties(
265 $is_bare ? $obj : $obj->subdir('.git')
270 return [sort { $a->{name} cmp $b->{name} } @ret];
273 =head2 dir_from_project_name
275 Get the corresponding directory of a given project.
279 sub dir_from_project_name {
280 my ($self, $project) = @_;
282 return dir($self->repo_dir)->subdir($project);
287 Find the hash of a given head (defaults to HEAD) of given (or current) project.
292 my ($self, $head) = @_;
294 my($output) = $self->command(qw/rev-parse --verify/, $head || 'HEAD' );
295 return unless $output;
297 my($sha1) = $output =~ /^($SHA1RE)$/;
303 For a given tree sha1 return an array describing the tree's contents. Where
304 the keys for each item will be:
314 my ($self, $sha1) = @_;
316 $sha1 = $self->head_hash($sha1)
317 if !$sha1 or $sha1 !~ $SHA1RE;
319 my($output) = $self->command(qw/ls-tree -z/, $sha1);
324 for my $line (split /\0/, $output) {
325 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
329 # XXX I wonder why directories always turn up as 040000 ...
330 modestr => $self->get_object_mode_string({mode=>oct $mode}),
340 =head2 get_object_mode_string
342 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
346 sub get_object_mode_string {
347 my ($self, $object) = @_;
349 return unless $object && $object->{mode};
350 return mode_to_string($object->{mode});
353 =head2 get_object_type
357 sub get_object_type {
358 my ($self, $object) = @_;
360 my($output) = $self->command(qw/cat-file -t/, $object)
368 Return the contents of a given file.
373 my ($self, $object) = @_;
375 my $type = $self->get_object_type($object);
376 die "object `$object' is not a file\n"
377 if (!defined $type || $type ne 'blob');
379 my($output) = $self->command(qw/cat-file -p/, $object)
387 For a given sha1 and path find the corresponding hash. Useful for find blobs.
392 my($self, $base, $path, $type) = @_;
396 my($line) = $self->command('ls-tree', $base, '--', $path)
399 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
400 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
401 return defined $type && $type ne $2
408 Check whether a given rev is valid i.e looks like a sha1.
413 my ($self, $rev) = @_;
416 return ($rev =~ /^($SHA1RE)$/);
421 Provides the raw output of a diff.
425 # gitweb uses the following sort of command for diffing merges:
426 # /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 --
427 # and for regular diffs
428 # /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 --
431 my ($self, @args) = @_;
433 return $self->command(
434 qw(diff-tree -r -M --no-commit-id --full-index),
440 diff --git a/TODO b/TODO
441 index 6a05e77..2071fd0 100644
445 * An action to find what branches have been merged, either as a list or through a search mechanism.
446 * An action to find which branches a given commit is on.
447 * Fix any not text/html bits e.g the patch action.
448 -* Simplify the creation of links.
449 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
450 index 706d024..7fac165 100644
451 --- a/lib/Gitalist/Controller/Root.pm
452 +++ b/lib/Gitalist/Controller/Root.pm
453 @@ -157,23 +157,6 @@ sub shortlog : Local {
459 -The tree of a given commit.
464 Returns a list of diff chunks corresponding to the files contained in the diff
465 and some associated metadata.
469 # XXX Ideally this would return a wee object instead of ad hoc structures.
471 my($self, %args) = @_;
473 # So either a parent is specifed, or we use the commit's parent if there's
474 # only one, otherwise it was a merge commit.
475 my $parent = $args{parent}
477 : @{$args{commit}->parents} <= 1
478 ? $args{commit}->parent_sha1
481 ( $args{file} ? ('--', $args{file}) : () ),
484 my @out = $self->raw_diff(
485 ( $args{patch} ? '--patch-with-raw' : () ),
486 $parent, $args{commit}->sha1, @etc
489 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
490 my @difftree = $self->parse_diff_tree(\@out);
495 # The blank line between the tree and the patch.
498 # XXX And no I'm not happy about having diff return tree + patch.
499 return \@difftree, [$self->parse_diff(@out)];
503 my($self, @diff) = @_;
507 # This regex is a little pathological.
508 if(m{^diff --git (a/(.*?)) (b/\2)}) {
519 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
520 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
524 # XXX Somewhat hacky. Ahem.
525 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
531 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
532 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
534 =head2 parse_diff_tree
536 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
537 to the C<diff-tree> output.
541 sub parse_diff_tree {
542 my($self, $diff) = @_;
544 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
546 while(@$diff and $diff->[0] =~ /^:\d+/) {
547 my $line = shift @$diff;
548 # see. man git-diff-tree for more info
549 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
550 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
551 my %line = zip @keys, @vals;
552 # Some convenience keys
553 $line{file} = $line{src};
554 $line{sha1} = $line{sha1dst};
555 $line{is_new} = $line{sha1src} =~ /^0+$/
557 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
558 if $line{status} =~ /^R/;
565 =head2 parse_rev_list
567 Given the output of the C<rev-list> command return a list of hashes.
572 my ($self, $output) = @_;
575 map $self->get_object($_),
576 grep $self->valid_rev($_),
577 map split(/\n/, $_, 6), split /\0/, $output;
582 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
588 my ($self, %args) = @_;
590 $args{sha1} = $self->head_hash($args{sha1})
591 if !$args{sha1} || $args{sha1} !~ $SHA1RE;
595 my $sargs = $args{search};
596 $sargs->{type} = 'grep'
597 if $sargs->{type} eq 'commit';
599 # This seems a little fragile ...
600 qq[--$sargs->{type}=$sargs->{text}],
601 '--regexp-ignore-case',
602 $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
606 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
608 (defined $args{ count } ? "--max-count=$args{count}" : ()),
609 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
613 ($args{file} ? $args{file} : ()),
615 return unless $output;
617 my @revs = $self->parse_rev_list($output);
624 Get a single piece of revision information for a given sha1.
629 my($self, $rev, $project) = @_;
631 return unless $self->valid_rev($rev);
633 return $self->list_revs(
634 rev => $rev, count => 1,
635 ( $project ? (project => $project) : () )
641 Calls the C<reflog> command and returns a list of hashes.
646 my ($self, @logargs) = @_;
649 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
650 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
653 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
654 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
656 Author: Foo Barsby <fbarsby@example.com>
657 Date: Thu Sep 17 12:26:05 2009 +0100
659 Merge branch 'abc123'
664 # XXX Stuff like this makes me want to switch to Git::PurePerl
665 my($sha1, $type, $author, $date)
667 ^ commit \s+ ($SHA1RE)$
669 Reflog[ ]message: \s+ (.+?)$ \s+
670 Author: \s+ ([^<]+) <.*?$ \s+
674 pos($_) = index($_, $date) + length $date;
676 # Yeah, I just did that.
678 my($msg) = /\G\s+(\S.*)/sg;
685 # XXX Add DateTime goodness.
694 Returns an array of hashes representing the heads (aka branches) for the
695 given, or current, project.
700 my ($self, $project) = @_;
702 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
705 for my $line (@output) {
706 my ($rev, $head, $commiter) = split /\0/, $line, 3;
707 $head =~ s!^refs/heads/!!;
709 push @ret, { sha1 => $rev, name => $head };
711 #FIXME: That isn't the time I'm looking for..
712 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
713 my $dt = DateTime->from_epoch(epoch => $epoch);
714 $dt->set_time_zone($tz);
715 $ret[-1]->{last_change} = $dt;
724 For a given sha1 check which branches currently point at it.
729 my($self, $sha1) = @_;
731 my $refs = $self->references->{$sha1};
733 return $refs ? @$refs : ();
738 A wrapper for C<git show-ref --dereference>. Based on gitweb's
739 C<git_get_references>.
746 return $self->{references}
747 if $self->{references};
749 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
750 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
751 my @reflist = $self->command(qw(show-ref --dereference))
756 push @{$refs{$1}}, $2
757 if m!^($SHA1RE)\srefs/(.*)$!;
760 return $self->{references} = \%refs;
765 __PACKAGE__->meta->make_immutable;