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 )->resolve =~ 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) = @_;
304 my($output) = $self->command(qw/rev-parse --verify/, $head || 'HEAD' );
305 return unless $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, $sha1) = @_;
326 $sha1 = $self->head_hash($sha1)
327 if !$sha1 or $sha1 !~ $SHA1RE;
329 my($output) = $self->command(qw/ls-tree -z/, $sha1);
334 for my $line (split /\0/, $output) {
335 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
339 # XXX I wonder why directories always turn up as 040000 ...
340 modestr => $self->get_object_mode_string({mode=>oct $mode}),
350 =head2 get_object_mode_string
352 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
356 sub get_object_mode_string {
357 my ($self, $object) = @_;
359 return unless $object && $object->{mode};
360 return mode_to_string($object->{mode});
363 =head2 get_object_type
367 sub get_object_type {
368 my ($self, $object) = @_;
370 my($output) = $self->command(qw/cat-file -t/, $object)
378 Return the contents of a given file.
383 my ($self, $object) = @_;
385 my $type = $self->get_object_type($object, $self->project);
386 die "object `$object' is not a file\n"
387 if (!defined $type || $type ne 'blob');
389 my($output) = $self->command(qw/cat-file -p/, $object)
397 For a given sha1 and path find the corresponding hash. Useful for find blobs.
402 my($self, $base, $path, $type) = @_;
406 my($line) = $self->command('ls-tree', $base, '--', $path)
409 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
410 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
411 return defined $type && $type ne $2
418 Check whether a given rev is valid i.e looks like a sha1.
423 my ($self, $rev) = @_;
426 return ($rev =~ /^($SHA1RE)$/);
431 Provides the raw output of a diff.
435 # gitweb uses the following sort of command for diffing merges:
436 # /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 --
437 # and for regular diffs
438 # /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 --
441 my ($self, @args) = @_;
443 return $self->command(
444 qw(diff-tree -r -M --no-commit-id --full-index),
450 diff --git a/TODO b/TODO
451 index 6a05e77..2071fd0 100644
455 * An action to find what branches have been merged, either as a list or through a search mechanism.
456 * An action to find which branches a given commit is on.
457 * Fix any not text/html bits e.g the patch action.
458 -* Simplify the creation of links.
459 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
460 index 706d024..7fac165 100644
461 --- a/lib/Gitalist/Controller/Root.pm
462 +++ b/lib/Gitalist/Controller/Root.pm
463 @@ -157,23 +157,6 @@ sub shortlog : Local {
469 -The tree of a given commit.
474 Returns a list of diff chunks corresponding to the files contained in the diff
475 and some associated metadata.
479 # XXX Ideally this would return a wee object instead of ad hoc structures.
481 my($self, %args) = @_;
483 # So either a parent is specifed, or we use the commit's parent if there's
484 # only one, otherwise it was a merge commit.
485 my $parent = $args{parent}
487 : $args{commit}->parents <= 1
488 ? $args{commit}->parent_sha1
491 ( $args{file} ? ('--', $args{file}) : () ),
494 my @out = $self->raw_diff(
495 ( $args{patch} ? '--patch-with-raw' : () ),
496 $parent, $args{commit}->sha1, @etc
499 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
500 my @difftree = $self->parse_diff_tree(\@out);
505 # The blank line between the tree and the patch.
508 # XXX And no I'm not happy about having diff return tree + patch.
509 return \@difftree, [$self->parse_diff(@out)];
513 my($self, @diff) = @_;
517 # This regex is a little pathological.
518 if(m{^diff --git (a/(.*?)) (b/\2)}) {
529 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
530 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
534 # XXX Somewhat hacky. Ahem.
535 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
541 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
542 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
544 =head2 parse_diff_tree
546 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
547 to the C<diff-tree> output.
551 sub parse_diff_tree {
552 my($self, $diff) = @_;
554 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
556 while(@$diff and $diff->[0] =~ /^:\d+/) {
557 my $line = shift @$diff;
558 # see. man git-diff-tree for more info
559 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
560 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
561 my %line = zip @keys, @vals;
562 # Some convenience keys
563 $line{file} = $line{src};
564 $line{sha1} = $line{sha1dst};
565 $line{is_new} = $line{sha1src} =~ /^0+$/
567 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
568 if $line{status} =~ /^R/;
575 =head2 parse_rev_list
577 Given the output of the C<rev-list> command return a list of hashes.
582 my ($self, $output) = @_;
585 map $self->get_object($_),
586 grep $self->valid_rev($_),
587 map split(/\n/, $_, 6), split /\0/, $output;
592 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
598 my ($self, %args) = @_;
600 $args{sha1} = $self->head_hash($args{sha1})
601 if !$args{sha1} || $args{sha1} !~ $SHA1RE;
605 my $sargs = $args{search};
606 $sargs->{type} = 'grep'
607 if $sargs->{type} eq 'commit';
609 # This seems a little fragile ...
610 qq[--$sargs->{type}=$sargs->{text}],
611 '--regexp-ignore-case',
612 $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
616 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
618 (defined $args{ count } ? "--max-count=$args{count}" : ()),
619 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
623 ($args{file} ? $args{file} : ()),
625 return unless $output;
627 my @revs = $self->parse_rev_list($output);
634 Get a single piece of revision information for a given sha1.
639 my($self, $rev, $project) = @_;
641 return unless $self->valid_rev($rev);
643 return $self->list_revs(
644 rev => $rev, count => 1,
645 ( $project ? (project => $project) : () )
651 Calls the C<reflog> command and returns a list of hashes.
656 my ($self, @logargs) = @_;
659 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
660 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
663 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
664 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
666 Author: Foo Barsby <fbarsby@example.com>
667 Date: Thu Sep 17 12:26:05 2009 +0100
669 Merge branch 'abc123'
674 # XXX Stuff like this makes me want to switch to Git::PurePerl
675 my($sha1, $type, $author, $date)
677 ^ commit \s+ ($SHA1RE)$
679 Reflog[ ]message: \s+ (.+?)$ \s+
680 Author: \s+ ([^<]+) <.*?$ \s+
684 pos($_) = index($_, $date) + length $date;
686 # Yeah, I just did that.
688 my($msg) = /\G\s+(\S.*)/sg;
695 # XXX Add DateTime goodness.
704 Returns an array of hashes representing the heads (aka branches) for the
705 given, or current, project.
710 my ($self, $project) = @_;
712 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
715 for my $line (@output) {
716 my ($rev, $head, $commiter) = split /\0/, $line, 3;
717 $head =~ s!^refs/heads/!!;
719 push @ret, { sha1 => $rev, name => $head };
721 #FIXME: That isn't the time I'm looking for..
722 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
723 my $dt = DateTime->from_epoch(epoch => $epoch);
724 $dt->set_time_zone($tz);
725 $ret[-1]->{last_change} = $dt;
734 For a given sha1 check which branches currently point at it.
739 my($self, $sha1) = @_;
741 my $refs = $self->references->{$sha1};
743 return $refs ? @$refs : ();
748 A wrapper for C<git show-ref --dereference>. Based on gitweb's
749 C<git_get_references>.
756 return $self->{references}
757 if $self->{references};
759 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
760 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
761 my @reflist = $self->command(qw(show-ref --dereference))
766 push @{$refs{$1}}, $2
767 if m!^($SHA1RE)\srefs/(.*)$!;
770 return $self->{references} = \%refs;
775 __PACKAGE__->meta->make_immutable;