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::Moose qw/Bool/;
58 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
62 # Should these live in a separate module? Or perhaps extended Regexp::Common?
63 # No, should be a MooseX::Types module!!
64 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
66 # These are static and only need to be setup on app start.
67 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
68 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
69 # These are dynamic and can be different from one request to the next.
70 has project => ( isa => NonEmptySimpleStr, is => 'rw');
71 has gpp => ( isa => 'Git::PurePerl', is => 'rw', lazy_build => 1 );
77 { # Show us the deprecated methods.
78 my $meta = __PACKAGE__->meta;
79 my @methods =map { $_->name }
80 grep { $_->package_name eq __PACKAGE__ }
81 $meta->get_all_methods;
82 foreach my $name (@methods) {
83 $meta->add_before_method_modifier($name, sub {
84 my ($package, $file, $line) = caller(2);
85 warn("Method " . $name . " called from $package line $line\n")
86 if $package ne __PACKAGE__;
93 my $meta = $self->meta;
94 $self->git; # Cause lazy value build.
99 my $git = File::Which::which('git');
103 Could not find a git executable.
104 Please specify the which git executable to use in gitweb.yml
113 A wrapper for the equivalent L<Git::PurePerl> method.
118 my($self, $sha1) = @_;
120 # We either want an object or undef, *not* an empty list.
121 return $self->gpp->get_object($sha1) || undef;
126 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
132 my ($self, $dir) = @_;
134 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
139 Call out to the C<git> binary and return a string consisting of the output.
144 my ($self, @args) = @_;
146 # print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
148 open my $fh, '-|', $self->git, @args
149 or die "failed to run git command";
150 binmode $fh, ':encoding(UTF-8)';
152 my $output = do { local $/ = undef; <$fh> };
160 The directory under which the given project will reside i.e C<.git/..>
165 my($self, $project) = @_;
167 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
168 ? $project->stringify
169 : $self->dir_from_project_name($project);
172 if -f dir($dir)->file('.git/HEAD');
179 Run a C<git> command in a given project and return the output as a string.
184 my ($self, $project, @args) = @_;
186 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
191 Run a C<git> command for the project specified in the C<p> parameter and
192 return the output as a list of strings corresponding to the lines of output.
197 my($self, @args) = @_;
199 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
201 return $output ? split(/\n/, $output) : ();
206 Returns a hash corresponding to a given project's properties. The keys will
210 description (empty if .git/description is empty/unnamed)
217 my ($self, $project) = @_;
221 $self->get_project_properties(
222 $self->dir_from_project_name($project),
227 =head2 get_project_properties
229 Called by C<project_info> to get a project's properties.
233 sub get_project_properties {
234 my ($self, $dir) = @_;
238 $props{description} = $dir->file('description')->slurp;
239 chomp $props{description};
242 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
243 delete $props{description};
246 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
248 my $output = $self->run_cmd_in($dir, qw{
249 for-each-ref --format=%(committer)
250 --sort=-committerdate --count=1 refs/heads
253 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
254 my $dt = DateTime->from_epoch(epoch => $epoch);
255 $dt->set_time_zone($tz);
256 $props{last_change} = $dt;
264 For the C<repo_dir> specified in the config return an array of projects where
265 each item will contain the contents of L</project_info>.
270 my ($self, $dir) = @_;
272 my $base = dir($dir || $self->repo_dir);
275 my $dh = $base->open or die("Cannot open dir $base");
276 while (my $file = $dh->read) {
277 next if $file =~ /^.{1,2}$/;
279 my $obj = $base->subdir($file);
281 next unless $self->is_git_repo($obj);
282 # XXX Leaky abstraction alert!
283 my $is_bare = !-d $obj->subdir('.git');
285 my $name = (File::Spec->splitdir($obj))[-1];
287 name => ($name . ( $is_bare ? '' : '/.git' )),
288 $self->get_project_properties(
289 $is_bare ? $obj : $obj->subdir('.git')
294 return [sort { $a->{name} cmp $b->{name} } @ret];
297 =head2 dir_from_project_name
299 Get the corresponding directory of a given project.
303 sub dir_from_project_name {
304 my ($self, $project) = @_;
306 return dir($self->repo_dir)->subdir($project);
311 Find the hash of a given head (defaults to HEAD) of given (or current) project.
316 my ($self, $head, $project) = @_;
318 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
319 return unless defined $output;
321 my($sha1) = $output =~ /^($SHA1RE)$/;
327 For a given tree sha1 return an array describing the tree's contents. Where
328 the keys for each item will be:
338 my ($self, $rev, $project) = @_;
340 $project ||= $self->project;
341 $rev ||= $self->head_hash($project);
343 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
344 return unless defined $output;
347 for my $line (split /\0/, $output) {
348 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
352 # XXX I wonder why directories always turn up as 040000 ...
353 modestr => $self->get_object_mode_string({mode=>oct $mode}),
363 =head2 get_object_mode_string
365 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
369 sub get_object_mode_string {
370 my ($self, $object) = @_;
372 return unless $object && $object->{mode};
373 return mode_to_string($object->{mode});
376 =head2 get_object_type
380 sub get_object_type {
381 my ($self, $object, $project) = @_;
383 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
384 return unless $output;
391 Return the contents of a given file.
396 my ($self, $object, $project) = @_;
398 my $type = $self->get_object_type($object, $project || $self->project);
399 die "object `$object' is not a file\n"
400 if (!defined $type || $type ne 'blob');
402 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
403 return unless $output;
410 For a given sha1 and path find the corresponding hash. Useful for find blobs.
415 my($self, $base, $path, $type) = @_;
419 my($line) = $self->command('ls-tree', $base, '--', $path)
422 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
423 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
424 return defined $type && $type ne $2
431 Check whether a given rev is valid i.e looks like a sha1.
436 my ($self, $rev) = @_;
439 return ($rev =~ /^($SHA1RE)$/);
444 Provides the raw output of a diff.
448 # gitweb uses the following sort of command for diffing merges:
449 # /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 --
450 # and for regular diffs
451 # /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 --
454 my ($self, @args) = @_;
456 return $self->command(
457 qw(diff-tree -r -M --no-commit-id --full-index),
463 diff --git a/TODO b/TODO
464 index 6a05e77..2071fd0 100644
468 * An action to find what branches have been merged, either as a list or through a search mechanism.
469 * An action to find which branches a given commit is on.
470 * Fix any not text/html bits e.g the patch action.
471 -* Simplify the creation of links.
472 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
473 index 706d024..7fac165 100644
474 --- a/lib/Gitalist/Controller/Root.pm
475 +++ b/lib/Gitalist/Controller/Root.pm
476 @@ -157,23 +157,6 @@ sub shortlog : Local {
482 -The tree of a given commit.
487 Returns a list of diff chunks corresponding to the files contained in the diff
488 and some associated metadata.
492 # XXX Ideally this would return a wee object instead of ad hoc structures.
494 my($self, %args) = @_;
496 # So either a parent is specifed, or we use the commit's parent if there's
497 # only one, otherwise it was a merge commit.
498 my $parent = $args{parent}
500 : $args{commit}->parents <= 1
501 ? $args{commit}->parent_sha1
504 ( $args{file} ? ('--', $args{file}) : () ),
507 my @out = $self->raw_diff(
508 ( $args{patch} ? '--patch-with-raw' : () ),
509 $parent, $args{commit}->sha1, @etc
512 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
513 my @difftree = $self->parse_diff_tree(\@out);
518 # The blank line between the tree and the patch.
521 # XXX And no I'm not happy about having diff return tree + patch.
522 return \@difftree, [$self->parse_diff(@out)];
526 my($self, @diff) = @_;
530 # This regex is a little pathological.
531 if(m{^diff --git (a/(.*?)) (b/\2)}) {
542 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
543 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
547 # XXX Somewhat hacky. Ahem.
548 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
554 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
555 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
557 =head2 parse_diff_tree
559 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
560 to the C<diff-tree> output.
564 sub parse_diff_tree {
565 my($self, $diff) = @_;
567 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
569 while(@$diff and $diff->[0] =~ /^:\d+/) {
570 my $line = shift @$diff;
571 # see. man git-diff-tree for more info
572 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
573 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
574 my %line = zip @keys, @vals;
575 # Some convenience keys
576 $line{file} = $line{src};
577 $line{sha1} = $line{sha1dst};
578 $line{is_new} = $line{sha1src} =~ /^0+$/
580 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
581 if $line{status} =~ /^R/;
588 =head2 parse_rev_list
590 Given the output of the C<rev-list> command return a list of hashes.
595 my ($self, $output) = @_;
598 map $self->get_object($_),
599 grep $self->valid_rev($_),
600 map split(/\n/, $_, 6), split /\0/, $output;
605 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
611 my ($self, %args) = @_;
613 $args{sha1} = $self->head_hash($args{sha1})
614 if !$args{sha1} || $args{sha1} !~ $SHA1RE;
618 my $sargs = $args{search};
619 $sargs->{type} = 'grep'
620 if $sargs->{type} eq 'commit';
622 # This seems a little fragile ...
623 qq[--$sargs->{type}=$sargs->{text}],
624 '--regexp-ignore-case',
625 $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
629 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
631 (defined $args{ count } ? "--max-count=$args{count}" : ()),
632 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
636 ($args{file} ? $args{file} : ()),
638 return unless $output;
640 my @revs = $self->parse_rev_list($output);
647 Get a single piece of revision information for a given sha1.
652 my($self, $rev, $project) = @_;
654 return unless $self->valid_rev($rev);
656 return $self->list_revs(
657 rev => $rev, count => 1,
658 ( $project ? (project => $project) : () )
664 Calls the C<reflog> command and returns a list of hashes.
669 my ($self, @logargs) = @_;
672 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
673 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
676 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
677 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
679 Author: Foo Barsby <fbarsby@example.com>
680 Date: Thu Sep 17 12:26:05 2009 +0100
682 Merge branch 'abc123'
687 # XXX Stuff like this makes me want to switch to Git::PurePerl
688 my($sha1, $type, $author, $date)
690 ^ commit \s+ ($SHA1RE)$
692 Reflog[ ]message: \s+ (.+?)$ \s+
693 Author: \s+ ([^<]+) <.*?$ \s+
697 pos($_) = index($_, $date) + length $date;
699 # Yeah, I just did that.
701 my($msg) = /\G\s+(\S.*)/sg;
708 # XXX Add DateTime goodness.
717 Returns an array of hashes representing the heads (aka branches) for the
718 given, or current, project.
723 my ($self, $project) = @_;
725 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
728 for my $line (@output) {
729 my ($rev, $head, $commiter) = split /\0/, $line, 3;
730 $head =~ s!^refs/heads/!!;
732 push @ret, { sha1 => $rev, name => $head };
734 #FIXME: That isn't the time I'm looking for..
735 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
736 my $dt = DateTime->from_epoch(epoch => $epoch);
737 $dt->set_time_zone($tz);
738 $ret[-1]->{last_change} = $dt;
747 For a given sha1 check which branches currently point at it.
752 my($self, $sha1) = @_;
754 my $refs = $self->references->{$sha1};
756 return $refs ? @$refs : ();
761 A wrapper for C<git show-ref --dereference>. Based on gitweb's
762 C<git_get_references>.
769 return $self->{references}
770 if $self->{references};
772 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
773 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
774 my @reflist = $self->command(qw(show-ref --dereference))
779 push @{$refs{$1}}, $2
780 if m!^($SHA1RE)\srefs/(.*)$!;
783 return $self->{references} = \%refs;
788 # Yes, yes, I am a bad man. So sue me.
789 #__PACKAGE__->meta->make_immutable;