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 Git::Repos; # Better name? Split out into own file once we have a sane name.
46 use namespace::autoclean;
52 use DateTime::Format::Mail;
53 use File::Stat::ModeString;
54 use List::MoreUtils qw/any zip/;
55 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
59 # Should these live in a separate module? Or perhaps extended Regexp::Common?
60 # No, should be a MooseX::Types module!!
61 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
63 # These are static and only need to be setup on app start.
64 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
65 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
66 # These are dynamic and can be different from one request to the next.
67 has project => ( isa => NonEmptySimpleStr, is => 'rw');
68 has gpp => ( isa => 'Git::PurePerl', is => 'rw', lazy_build => 1 );
78 $self->git; # Cause lazy value build.
83 my $git = File::Which::which('git');
87 Could not find a git executable.
88 Please specify the which git executable to use in gitweb.yml
97 A wrapper for the equivalent L<Git::PurePerl> method.
102 my($self, $sha1) = @_;
104 # We either want an object or undef, *not* an empty list.
105 return $self->gpp->get_object($sha1) || undef;
110 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
116 my ($self, $dir) = @_;
118 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
123 Call out to the C<git> binary and return a string consisting of the output.
128 my ($self, @args) = @_;
130 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
132 open my $fh, '-|', $self->git, @args
133 or die "failed to run git command";
134 binmode $fh, ':encoding(UTF-8)';
136 my $output = do { local $/ = undef; <$fh> };
144 The directory under which the given project will reside i.e C<.git/..>
149 my($self, $project) = @_;
151 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
152 ? $project->stringify
153 : $self->dir_from_project_name($project);
156 if -f dir($dir)->file('.git/HEAD');
163 Run a C<git> command in a given project and return the output as a string.
168 my ($self, $project, @args) = @_;
170 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
175 Run a C<git> command for the project specified in the C<p> parameter and
176 return the output as a list of strings corresponding to the lines of output.
181 my($self, @args) = @_;
183 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
185 return $output ? split(/\n/, $output) : ();
190 Returns a hash corresponding to a given project's properties. The keys will
194 description (empty if .git/description is empty/unnamed)
201 my ($self, $project) = @_;
205 $self->get_project_properties(
206 $self->dir_from_project_name($project),
211 =head2 get_project_properties
213 Called by C<project_info> to get a project's properties.
217 sub get_project_properties {
218 my ($self, $dir) = @_;
222 $props{description} = $dir->file('description')->slurp;
223 chomp $props{description};
226 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
227 delete $props{description};
230 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
232 my $output = $self->run_cmd_in($dir, qw{
233 for-each-ref --format=%(committer)
234 --sort=-committerdate --count=1 refs/heads
237 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
238 my $dt = DateTime->from_epoch(epoch => $epoch);
239 $dt->set_time_zone($tz);
240 $props{last_change} = $dt;
248 For the C<repo_dir> specified in the config return an array of projects where
249 each item will contain the contents of L</project_info>.
254 my ($self, $dir) = @_;
256 my $base = dir($dir || $self->repo_dir);
259 my $dh = $base->open or die("Cannot open dir $base");
260 while (my $file = $dh->read) {
261 next if $file =~ /^.{1,2}$/;
263 my $obj = $base->subdir($file);
265 next unless $self->is_git_repo($obj);
266 # XXX Leaky abstraction alert!
267 my $is_bare = !-d $obj->subdir('.git');
269 my $name = (File::Spec->splitdir($obj))[-1];
271 name => ($name . ( $is_bare ? '' : '/.git' )),
272 $self->get_project_properties(
273 $is_bare ? $obj : $obj->subdir('.git')
278 return [sort { $a->{name} cmp $b->{name} } @ret];
281 =head2 dir_from_project_name
283 Get the corresponding directory of a given project.
287 sub dir_from_project_name {
288 my ($self, $project) = @_;
290 return dir($self->repo_dir)->subdir($project);
295 Find the hash of a given head (defaults to HEAD) of given (or current) project.
300 my ($self, $head, $project) = @_;
302 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
303 return unless defined $output;
305 my($sha1) = $output =~ /^($SHA1RE)$/;
311 For a given tree sha1 return an array describing the tree's contents. Where
312 the keys for each item will be:
322 my ($self, $rev, $project) = @_;
324 $project ||= $self->project;
325 $rev ||= $self->head_hash($project);
327 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
328 return unless defined $output;
331 for my $line (split /\0/, $output) {
332 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
336 # XXX I wonder why directories always turn up as 040000 ...
337 modestr => $self->get_object_mode_string({mode=>oct $mode}),
347 =head2 get_object_mode_string
349 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
353 sub get_object_mode_string {
354 my ($self, $object) = @_;
356 return unless $object && $object->{mode};
357 return mode_to_string($object->{mode});
360 =head2 get_object_type
364 sub get_object_type {
365 my ($self, $object, $project) = @_;
367 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
368 return unless $output;
375 Return the contents of a given file.
380 my ($self, $object, $project) = @_;
382 my $type = $self->get_object_type($object, $project);
383 die "object `$object' is not a file\n"
384 if (!defined $type || $type ne 'blob');
386 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
387 return unless $output;
394 For a given sha1 and path find the corresponding hash. Useful for find blobs.
399 my($self, $base, $path, $type) = @_;
403 my($line) = $self->command('ls-tree', $base, '--', $path)
406 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
407 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
408 return defined $type && $type ne $2
415 Check whether a given rev is valid i.e looks like a sha1.
420 my ($self, $rev) = @_;
423 return ($rev =~ /^($SHA1RE)$/);
428 Provides the raw output of a diff.
432 # gitweb uses the following sort of command for diffing merges:
433 # /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 --
434 # and for regular diffs
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 2e3454ca0749641b42f063730b0090e1 316cf158df3f6207afbae7270bcc5ba0 --
438 my ($self, @args) = @_;
440 return $self->command(
441 qw(diff-tree -r -M --no-commit-id --full-index),
447 diff --git a/TODO b/TODO
448 index 6a05e77..2071fd0 100644
452 * An action to find what branches have been merged, either as a list or through a search mechanism.
453 * An action to find which branches a given commit is on.
454 * Fix any not text/html bits e.g the patch action.
455 -* Simplify the creation of links.
456 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
457 index 706d024..7fac165 100644
458 --- a/lib/Gitalist/Controller/Root.pm
459 +++ b/lib/Gitalist/Controller/Root.pm
460 @@ -157,23 +157,6 @@ sub shortlog : Local {
466 -The tree of a given commit.
471 Returns a list of diff chunks corresponding to the files contained in the diff
472 and some associated metadata.
476 # XXX Ideally this would return a wee object instead of ad hoc structures.
478 my($self, %args) = @_;
480 # So either a parent is specifed, or we use the commit's parent if there's
481 # only one, otherwise it was a merge commit.
482 my $parent = $args{parent}
484 : @{$args{commit}->parents} <= 1
485 ? $args{commit}->parent_sha1
488 ( $args{file} ? ('--', $args{file}) : () ),
491 my @out = $self->raw_diff(
492 ( $args{patch} ? '--patch-with-raw' : () ),
493 $parent, $args{commit}->sha1, @etc
496 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
497 my @difftree = $self->parse_diff_tree(\@out);
502 # The blank line between the tree and the patch.
505 # XXX And no I'm not happy about having diff return tree + patch.
506 return \@difftree, [$self->parse_diff(@out)];
510 my($self, @diff) = @_;
514 # This regex is a little pathological.
515 if(m{^diff --git (a/(.*?)) (b/\2)}) {
526 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
527 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
531 # XXX Somewhat hacky. Ahem.
532 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
538 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
539 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
541 =head2 parse_diff_tree
543 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
544 to the C<diff-tree> output.
548 sub parse_diff_tree {
549 my($self, $diff) = @_;
551 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
553 while(@$diff and $diff->[0] =~ /^:\d+/) {
554 my $line = shift @$diff;
555 # see. man git-diff-tree for more info
556 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
557 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
558 my %line = zip @keys, @vals;
559 # Some convenience keys
560 $line{file} = $line{src};
561 $line{sha1} = $line{sha1dst};
562 $line{is_new} = $line{sha1src} =~ /^0+$/
564 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
565 if $line{status} =~ /^R/;
572 =head2 parse_rev_list
574 Given the output of the C<rev-list> command return a list of hashes.
579 my ($self, $output) = @_;
582 map $self->get_object($_),
583 grep $self->valid_rev($_),
584 map split(/\n/, $_, 6), split /\0/, $output;
589 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
595 my ($self, %args) = @_;
597 $args{sha1} = $self->head_hash($args{sha1})
598 if !$args{sha1} || $args{sha1} !~ $SHA1RE;
602 my $sargs = $args{search};
603 $sargs->{type} = 'grep'
604 if $sargs->{type} eq 'commit';
606 # This seems a little fragile ...
607 qq[--$sargs->{type}=$sargs->{text}],
608 '--regexp-ignore-case',
609 $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
613 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
615 (defined $args{ count } ? "--max-count=$args{count}" : ()),
616 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
620 ($args{file} ? $args{file} : ()),
622 return unless $output;
624 my @revs = $self->parse_rev_list($output);
631 Get a single piece of revision information for a given sha1.
636 my($self, $rev, $project) = @_;
638 return unless $self->valid_rev($rev);
640 return $self->list_revs(
641 rev => $rev, count => 1,
642 ( $project ? (project => $project) : () )
648 Calls the C<reflog> command and returns a list of hashes.
653 my ($self, @logargs) = @_;
656 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
657 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
660 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
661 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
663 Author: Foo Barsby <fbarsby@example.com>
664 Date: Thu Sep 17 12:26:05 2009 +0100
666 Merge branch 'abc123'
671 # XXX Stuff like this makes me want to switch to Git::PurePerl
672 my($sha1, $type, $author, $date)
674 ^ commit \s+ ($SHA1RE)$
676 Reflog[ ]message: \s+ (.+?)$ \s+
677 Author: \s+ ([^<]+) <.*?$ \s+
681 pos($_) = index($_, $date) + length $date;
683 # Yeah, I just did that.
685 my($msg) = /\G\s+(\S.*)/sg;
692 # XXX Add DateTime goodness.
701 Returns an array of hashes representing the heads (aka branches) for the
702 given, or current, project.
707 my ($self, $project) = @_;
709 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
712 for my $line (@output) {
713 my ($rev, $head, $commiter) = split /\0/, $line, 3;
714 $head =~ s!^refs/heads/!!;
716 push @ret, { sha1 => $rev, name => $head };
718 #FIXME: That isn't the time I'm looking for..
719 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
720 my $dt = DateTime->from_epoch(epoch => $epoch);
721 $dt->set_time_zone($tz);
722 $ret[-1]->{last_change} = $dt;
731 For a given sha1 check which branches currently point at it.
736 my($self, $sha1) = @_;
738 my $refs = $self->references->{$sha1};
740 return $refs ? @$refs : ();
745 A wrapper for C<git show-ref --dereference>. Based on gitweb's
746 C<git_get_references>.
753 return $self->{references}
754 if $self->{references};
756 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
757 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
758 my @reflist = $self->command(qw(show-ref --dereference))
763 push @{$refs{$1}}, $2
764 if m!^($SHA1RE)\srefs/(.*)$!;
767 return $self->{references} = \%refs;
772 __PACKAGE__->meta->make_immutable;