1 package Gitalist::Model::Git;
4 use namespace::autoclean;
5 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
8 extends 'Catalyst::Model';
9 with 'Catalyst::Component::InstancePerContext';
11 has repo_dir => ( is => 'ro', required => 1, isa => NonEmptySimpleStr );
15 Gitalist::Model::Git - the model for git interactions
19 [enter your description here]
26 use Path::Class qw/dir/;
27 sub build_per_context_instance {
28 my ( $self, $c ) = @_;
30 my $app = blessed($c) || $c;
31 my $model = Git::Repos->new(
32 project => ([$c->req->parameters->{p} || '/']->flatten)[0],
33 repo_dir => $self->repo_dir,
36 # This is fugly as fuck. Move Git::PurePerl construction into attribute builders..
37 my ($pd, $gd) = $model->project_dir( $model->project ) =~ m{((.+?)(:?/\/\.git)?$)};
38 $gd .= '/.git' if ($gd !~ /\.git$/ and -d "$gd/.git");
39 $model->gpp( Git::PurePerl->new(gitdir => $gd, directory => $pd) );
44 __PACKAGE__->meta->make_immutable;
46 package Git::Repos; # Better name? Split out into own file once we have a sane name.
48 use namespace::autoclean;
54 use DateTime::Format::Mail;
55 use File::Stat::ModeString;
56 use List::MoreUtils qw/any zip/;
57 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
61 # Should these live in a separate module? Or perhaps extended Regexp::Common?
62 # No, should be a MooseX::Types module!!
63 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
65 # These are static and only need to be setup on app start.
66 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
67 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
68 # These are dynamic and can be different from one request to the next.
69 has project => ( isa => NonEmptySimpleStr, is => 'rw');
70 has gpp => ( isa => 'Git::PurePerl', is => 'rw', lazy_build => 1 );
80 $self->git; # Cause lazy value build.
85 my $git = File::Which::which('git');
89 Could not find a git executable.
90 Please specify the which git executable to use in gitweb.yml
99 A wrapper for the equivalent L<Git::PurePerl> method.
104 my($self, $sha1) = @_;
106 # We either want an object or undef, *not* an empty list.
107 return $self->gpp->get_object($sha1) || undef;
112 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
118 my ($self, $dir) = @_;
120 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
125 Call out to the C<git> binary and return a string consisting of the output.
130 my ($self, @args) = @_;
132 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
134 open my $fh, '-|', $self->git, @args
135 or die "failed to run git command";
136 binmode $fh, ':encoding(UTF-8)';
138 my $output = do { local $/ = undef; <$fh> };
146 The directory under which the given project will reside i.e C<.git/..>
151 my($self, $project) = @_;
153 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
154 ? $project->stringify
155 : $self->dir_from_project_name($project);
158 if -f dir($dir)->file('.git/HEAD');
165 Run a C<git> command in a given project and return the output as a string.
170 my ($self, $project, @args) = @_;
172 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
177 Run a C<git> command for the project specified in the C<p> parameter and
178 return the output as a list of strings corresponding to the lines of output.
183 my($self, @args) = @_;
185 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
187 return $output ? split(/\n/, $output) : ();
192 Returns a hash corresponding to a given project's properties. The keys will
196 description (empty if .git/description is empty/unnamed)
203 my ($self, $project) = @_;
207 $self->get_project_properties(
208 $self->dir_from_project_name($project),
213 =head2 get_project_properties
215 Called by C<project_info> to get a project's properties.
219 sub get_project_properties {
220 my ($self, $dir) = @_;
224 $props{description} = $dir->file('description')->slurp;
225 chomp $props{description};
228 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
229 delete $props{description};
232 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
234 my $output = $self->run_cmd_in($dir, qw{
235 for-each-ref --format=%(committer)
236 --sort=-committerdate --count=1 refs/heads
239 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
240 my $dt = DateTime->from_epoch(epoch => $epoch);
241 $dt->set_time_zone($tz);
242 $props{last_change} = $dt;
250 For the C<repo_dir> specified in the config return an array of projects where
251 each item will contain the contents of L</project_info>.
256 my ($self, $dir) = @_;
258 my $base = dir($dir || $self->repo_dir);
261 my $dh = $base->open or die("Cannot open dir $base");
262 while (my $file = $dh->read) {
263 next if $file =~ /^.{1,2}$/;
265 my $obj = $base->subdir($file);
267 next unless $self->is_git_repo($obj);
268 # XXX Leaky abstraction alert!
269 my $is_bare = !-d $obj->subdir('.git');
271 my $name = (File::Spec->splitdir($obj))[-1];
273 name => ($name . ( $is_bare ? '' : '/.git' )),
274 $self->get_project_properties(
275 $is_bare ? $obj : $obj->subdir('.git')
280 return [sort { $a->{name} cmp $b->{name} } @ret];
283 =head2 dir_from_project_name
285 Get the corresponding directory of a given project.
289 sub dir_from_project_name {
290 my ($self, $project) = @_;
292 return dir($self->repo_dir)->subdir($project);
297 Find the hash of a given head (defaults to HEAD) of given (or current) project.
302 my ($self, $head, $project) = @_;
304 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
305 return unless defined $output;
307 my($sha1) = $output =~ /^($SHA1RE)$/;
313 For a given tree sha1 return an array describing the tree's contents. Where
314 the keys for each item will be:
324 my ($self, $rev, $project) = @_;
326 $project ||= $self->project;
327 $rev ||= $self->head_hash($project);
329 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
330 return unless defined $output;
333 for my $line (split /\0/, $output) {
334 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
338 # XXX I wonder why directories always turn up as 040000 ...
339 modestr => $self->get_object_mode_string({mode=>oct $mode}),
349 =head2 get_object_mode_string
351 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
355 sub get_object_mode_string {
356 my ($self, $object) = @_;
358 return unless $object && $object->{mode};
359 return mode_to_string($object->{mode});
362 =head2 get_object_type
366 sub get_object_type {
367 my ($self, $object, $project) = @_;
369 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
370 return unless $output;
377 Return the contents of a given file.
382 my ($self, $object, $project) = @_;
384 my $type = $self->get_object_type($object, $project || $self->project);
385 die "object `$object' is not a file\n"
386 if (!defined $type || $type ne 'blob');
388 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
389 return unless $output;
396 For a given sha1 and path find the corresponding hash. Useful for find blobs.
401 my($self, $base, $path, $type) = @_;
405 my($line) = $self->command('ls-tree', $base, '--', $path)
408 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
409 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
410 return defined $type && $type ne $2
417 Check whether a given rev is valid i.e looks like a sha1.
422 my ($self, $rev) = @_;
425 return ($rev =~ /^($SHA1RE)$/);
430 Provides the raw output of a diff.
434 # gitweb uses the following sort of command for diffing merges:
435 # /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 --
436 # and for regular diffs
437 # /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 --
440 my ($self, @args) = @_;
442 return $self->command(
443 qw(diff-tree -r -M --no-commit-id --full-index),
449 diff --git a/TODO b/TODO
450 index 6a05e77..2071fd0 100644
454 * An action to find what branches have been merged, either as a list or through a search mechanism.
455 * An action to find which branches a given commit is on.
456 * Fix any not text/html bits e.g the patch action.
457 -* Simplify the creation of links.
458 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
459 index 706d024..7fac165 100644
460 --- a/lib/Gitalist/Controller/Root.pm
461 +++ b/lib/Gitalist/Controller/Root.pm
462 @@ -157,23 +157,6 @@ sub shortlog : Local {
468 -The tree of a given commit.
473 Returns a list of diff chunks corresponding to the files contained in the diff
474 and some associated metadata.
478 # XXX Ideally this would return a wee object instead of ad hoc structures.
480 my($self, %args) = @_;
482 # So either a parent is specifed, or we use the commit's parent if there's
483 # only one, otherwise it was a merge commit.
484 my $parent = $args{parent}
486 : $args{commit}->parents <= 1
487 ? $args{commit}->parent_sha1
490 ( $args{file} ? ('--', $args{file}) : () ),
493 my @out = $self->raw_diff(
494 ( $args{patch} ? '--patch-with-raw' : () ),
495 $parent, $args{commit}->sha1, @etc
498 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
499 my @difftree = $self->parse_diff_tree(\@out);
504 # The blank line between the tree and the patch.
507 # XXX And no I'm not happy about having diff return tree + patch.
508 return \@difftree, [$self->parse_diff(@out)];
512 my($self, @diff) = @_;
516 # This regex is a little pathological.
517 if(m{^diff --git (a/(.*?)) (b/\2)}) {
528 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
529 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
533 # XXX Somewhat hacky. Ahem.
534 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
540 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
541 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
543 =head2 parse_diff_tree
545 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
546 to the C<diff-tree> output.
550 sub parse_diff_tree {
551 my($self, $diff) = @_;
553 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
555 while(@$diff and $diff->[0] =~ /^:\d+/) {
556 my $line = shift @$diff;
557 # see. man git-diff-tree for more info
558 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
559 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
560 my %line = zip @keys, @vals;
561 # Some convenience keys
562 $line{file} = $line{src};
563 $line{sha1} = $line{sha1dst};
564 $line{is_new} = $line{sha1src} =~ /^0+$/
566 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
567 if $line{status} =~ /^R/;
574 =head2 parse_rev_list
576 Given the output of the C<rev-list> command return a list of hashes.
581 my ($self, $output) = @_;
584 map $self->get_object($_),
585 grep $self->valid_rev($_),
586 map split(/\n/, $_, 6), split /\0/, $output;
591 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
597 my ($self, %args) = @_;
599 $args{sha1} = $self->head_hash($args{sha1})
600 if !$args{sha1} || $args{sha1} !~ $SHA1RE;
604 my $sargs = $args{search};
605 $sargs->{type} = 'grep'
606 if $sargs->{type} eq 'commit';
608 # This seems a little fragile ...
609 qq[--$sargs->{type}=$sargs->{text}],
610 '--regexp-ignore-case',
611 $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
615 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
617 (defined $args{ count } ? "--max-count=$args{count}" : ()),
618 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
622 ($args{file} ? $args{file} : ()),
624 return unless $output;
626 my @revs = $self->parse_rev_list($output);
633 Get a single piece of revision information for a given sha1.
638 my($self, $rev, $project) = @_;
640 return unless $self->valid_rev($rev);
642 return $self->list_revs(
643 rev => $rev, count => 1,
644 ( $project ? (project => $project) : () )
650 Calls the C<reflog> command and returns a list of hashes.
655 my ($self, @logargs) = @_;
658 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
659 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
662 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
663 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
665 Author: Foo Barsby <fbarsby@example.com>
666 Date: Thu Sep 17 12:26:05 2009 +0100
668 Merge branch 'abc123'
673 # XXX Stuff like this makes me want to switch to Git::PurePerl
674 my($sha1, $type, $author, $date)
676 ^ commit \s+ ($SHA1RE)$
678 Reflog[ ]message: \s+ (.+?)$ \s+
679 Author: \s+ ([^<]+) <.*?$ \s+
683 pos($_) = index($_, $date) + length $date;
685 # Yeah, I just did that.
687 my($msg) = /\G\s+(\S.*)/sg;
694 # XXX Add DateTime goodness.
703 Returns an array of hashes representing the heads (aka branches) for the
704 given, or current, project.
709 my ($self, $project) = @_;
711 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
714 for my $line (@output) {
715 my ($rev, $head, $commiter) = split /\0/, $line, 3;
716 $head =~ s!^refs/heads/!!;
718 push @ret, { sha1 => $rev, name => $head };
720 #FIXME: That isn't the time I'm looking for..
721 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
722 my $dt = DateTime->from_epoch(epoch => $epoch);
723 $dt->set_time_zone($tz);
724 $ret[-1]->{last_change} = $dt;
733 For a given sha1 check which branches currently point at it.
738 my($self, $sha1) = @_;
740 my $refs = $self->references->{$sha1};
742 return $refs ? @$refs : ();
747 A wrapper for C<git show-ref --dereference>. Based on gitweb's
748 C<git_get_references>.
755 return $self->{references}
756 if $self->{references};
758 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
759 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
760 my @reflist = $self->command(qw(show-ref --dereference))
765 push @{$refs{$1}}, $2
766 if m!^($SHA1RE)\srefs/(.*)$!;
769 return $self->{references} = \%refs;
774 __PACKAGE__->meta->make_immutable;