1 package Gitalist::Model::Git;
4 use namespace::autoclean;
6 BEGIN { extends 'Catalyst::Model' }
13 use DateTime::Format::Mail;
14 use File::Stat::ModeString;
15 use List::MoreUtils qw/any/;
16 use Scalar::Util qw/blessed/;
17 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
21 Gitalist::Model::Git - the model for git interactions
25 [enter your description here]
31 # Should these live in a separate module? Or perhaps extended Regexp::Common?
32 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
34 has project => ( isa => NonEmptySimpleStr, is => 'rw');
35 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 ); # Fixme - path::class
36 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
44 $self->git; # Cause lazy value build.
51 #isa => 'Git::PurePerl'
57 (my $pd = $self->project_dir( $self->project )) =~ s{/\.git$}();
58 return Git::PurePerl->new(
65 my $git = File::Which::which('git');
69 Could not find a git executable.
70 Please specify the which git executable to use in gitweb.yml
78 return Gitalist->config->{repo_dir};
83 A wrapper for the equivalent L<Git::PurePerl> method.
88 $_[0]->gpp->get_object($_[1]);
93 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
99 my ($self, $dir) = @_;
101 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
106 Call out to the C<git> binary and return a string consisting of the output.
111 my ($self, @args) = @_;
113 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
115 open my $fh, '-|', $self->git, @args
116 or die "failed to run git command";
117 binmode $fh, ':encoding(UTF-8)';
119 my $output = do { local $/ = undef; <$fh> };
127 The directory under which the given project will reside i.e C<.git/..>
132 my($self, $project) = @_;
134 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
135 ? $project->stringify
136 : $self->dir_from_project_name($project);
139 if -f dir($dir)->file('.git/HEAD');
146 Run a C<git> command in a given project and return the output as a string.
151 my ($self, $project, @args) = @_;
153 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
158 Run a C<git> command for the project specified in the C<p> parameter and
159 return the output as a list of strings corresponding to the lines of output.
164 my($self, @args) = @_;
166 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
168 return $output ? split(/\n/, $output) : ();
173 Returns a hash corresponding to a given project's properties. The keys will
177 description (empty if .git/description is empty/unnamed)
184 my ($self, $project) = @_;
188 $self->get_project_properties(
189 $self->dir_from_project_name($project),
194 =head2 get_project_properties
196 Called by C<project_info> to get a project's properties.
200 sub get_project_properties {
201 my ($self, $dir) = @_;
205 $props{description} = $dir->file('description')->slurp;
206 chomp $props{description};
209 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
210 delete $props{description};
213 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
215 my $output = $self->run_cmd_in($dir, qw{
216 for-each-ref --format=%(committer)
217 --sort=-committerdate --count=1 refs/heads
220 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
221 my $dt = DateTime->from_epoch(epoch => $epoch);
222 $dt->set_time_zone($tz);
223 $props{last_change} = $dt;
231 For the C<repo_dir> specified in the config return an array of projects where
232 each item will contain the contents of L</project_info>.
237 my ($self, $dir) = @_;
239 my $base = dir($dir || $self->repo_dir);
242 my $dh = $base->open;
243 while (my $file = $dh->read) {
244 next if $file =~ /^.{1,2}$/;
246 my $obj = $base->subdir($file);
248 next unless $self->is_git_repo($obj);
250 # XXX Leaky abstraction alert!
251 my $is_bare = !-d $obj->subdir('.git');
253 my $name = (File::Spec->splitdir($obj))[-1];
255 name => ($name . ( $is_bare ? '' : '/.git' )),
256 $self->get_project_properties(
257 $is_bare ? $obj : $obj->subdir('.git')
262 return [sort { $a->{name} cmp $b->{name} } @ret];
265 =head2 dir_from_project_name
267 Get the corresponding directory of a given project.
271 sub dir_from_project_name {
272 my ($self, $project) = @_;
274 return dir($self->repo_dir)->subdir($project);
279 Find the C<HEAD> of given (or current) project.
284 my ($self, $project) = @_;
286 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify HEAD/ );
287 return unless defined $output;
289 my ($head) = $output =~ /^($SHA1RE)$/;
295 For a given tree sha1 return an array describing the tree's contents. Where
296 the keys for each item will be:
306 my ($self, $rev, $project) = @_;
308 $project ||= $self->project;
309 $rev ||= $self->head_hash($project);
311 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
312 return unless defined $output;
315 for my $line (split /\0/, $output) {
316 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
320 modestr => $self->get_object_mode_string({mode=>oct $mode}),
330 =head2 get_object_mode_string
332 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
336 sub get_object_mode_string {
337 my ($self, $object) = @_;
339 return unless $object && $object->{mode};
340 return mode_to_string($object->{mode});
343 =head2 get_object_type
347 sub get_object_type {
348 my ($self, $object, $project) = @_;
350 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
351 return unless $output;
358 Return the contents of a given file.
363 my ($self, $object, $project) = @_;
365 my $type = $self->get_object_type($object);
366 die "object `$object' is not a file\n"
367 if (!defined $type || $type ne 'blob');
369 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
370 return unless $output;
377 For a given sha1 and path find the corresponding hash. Useful for find blobs.
382 my($self, $base, $path, $type) = @_;
386 my($line) = $self->command('ls-tree', $base, '--', $path)
389 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
390 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
391 return defined $type && $type ne $2
398 Check whether a given rev is valid i.e looks like a sha1.
403 my ($self, $rev) = @_;
406 return ($rev =~ /^($SHA1RE)$/);
411 Provides the raw output of a diff.
416 my ($self, @revs) = @_;
418 croak("Gitalist::Model::Git::diff needs either one or two revisions, got: @revs")
421 || any { !$self->valid_rev($_) } @revs;
423 return $self->command(diff => @revs);
427 diff --git a/TODO b/TODO
428 index 6a05e77..2071fd0 100644
432 * An action to find what branches have been merged, either as a list or through a search mechanism.
433 * An action to find which branches a given commit is on.
434 * Fix any not text/html bits e.g the patch action.
435 -* Simplify the creation of links.
436 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
437 index 706d024..7fac165 100644
438 --- a/lib/Gitalist/Controller/Root.pm
439 +++ b/lib/Gitalist/Controller/Root.pm
440 @@ -157,23 +157,6 @@ sub shortlog : Local {
446 -The tree of a given commit.
451 Returns a list of diff chunks corresponding to the files contained in the diff
452 and some associated metadata.
457 my($self, @revs) = @_;
459 my @diff = $self->raw_diff(@revs);
462 for my $line (@diff) {
463 # This regex is a little pathological.
464 if($line =~ m{^diff --git (a/(.*?)) (b/\2)}) {
475 if($line =~ /^index (\w+)\.\.(\w+) (\d+)$/) {
476 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
480 croak("No diff found for @revs")
483 # XXX Somewhat hacky. Ahem.
484 $ret[-1]{diff} .= "$line\n";
490 =head2 parse_rev_list
492 Given the output of the C<rev-list> command return a list of hashes.
497 my ($self, $output) = @_;
500 my @revs = split /\0/, $output;
502 for my $rev (split /\0/, $output) {
503 for my $line (split /\n/, $rev, 6) {
507 if ($self->valid_rev($line)) {
508 push @ret, $self->get_object($line);
518 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
524 my ($self, %args) = @_;
526 $args{rev} ||= $self->head_hash($args{project});
528 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
530 (defined $args{ count } ? "--max-count=$args{count}" : ()),
531 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
534 ($args{file} ? $args{file} : ()),
536 return unless $output;
538 my @revs = $self->parse_rev_list($output);
545 Get a single piece of revision information for a given sha1.
550 my($self, $rev, $project) = @_;
552 return unless $self->valid_rev($rev);
554 return $self->list_revs(
555 rev => $rev, count => 1,
556 ( $project ? (project => $project) : () )
562 Calls the C<reflog> command and returns a list of hashes.
567 my ($self, @logargs) = @_;
570 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
571 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
575 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
576 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
578 Author: Foo Barsby <fbarsby@example.com>
579 Date: Thu Sep 17 12:26:05 2009 +0100
581 Merge branch 'abc123'
586 # XXX Stuff like this makes me want to switch to Git::PurePerl
587 my($sha1, $type, $author, $date)
589 ^ commit \s+ ($SHA1RE)$
591 Reflog[ ]message: \s+ (.+?)$ \s+
592 Author: \s+ ([^<]+) <.*?$ \s+
596 pos($_) = index($_, $date) + length $date;
598 # Yeah, I just did that.
600 my($msg) = /\G\s+(\S.*)/sg;
607 # XXX Add DateTime goodness.
616 Returns an array of hashes representing the heads (aka branches) for the
617 given, or current, project.
622 my ($self, $project) = @_;
624 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
627 for my $line (@output) {
628 my ($rev, $head, $commiter) = split /\0/, $line, 3;
629 $head =~ s!^refs/heads/!!;
631 push @ret, { sha1 => $rev, name => $head };
633 #FIXME: That isn't the time I'm looking for..
634 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
635 my $dt = DateTime->from_epoch(epoch => $epoch);
636 $dt->set_time_zone($tz);
637 $ret[-1]->{last_change} = $dt;
646 For a given sha1 check which branches currently point at it.
651 my($self, $sha1) = @_;
653 my $refs = $self->references->{$sha1};
655 return $refs ? @$refs : ();
660 A wrapper for C<git show-ref --dereference>. Based on gitweb's
661 C<git_get_references>.
668 return $self->{references}
669 if $self->{references};
671 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
672 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
673 my @reflist = $self->command(qw(show-ref --dereference))
678 push @{$refs{$1}}, $2
679 if m!^($SHA1RE)\srefs/(.*)$!;
682 return $self->{references} = \%refs;
687 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
688 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M TODO
689 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M lib/Gitalist/Controller/Root.pm
690 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M lib/Gitalist/View/Default.pm
691 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A lib/Gitalist/View/SyntaxHighlight.pm
692 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A root/static/css/syntax-dark.css
693 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
697 use List::MoreUtils qw(zip);
698 # XXX Hrm, getting called twice, not sure why.
701 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
702 to the C<diff-tree> output.
707 my($self, $commit) = @_;
709 my @dtout = $self->command(
710 # XXX should really deal with multple parents ...
711 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
714 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
716 # see. man git-diff-tree for more info
717 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
718 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
719 my %line = zip @keys, @vals;
720 # Some convenience keys
721 $line{file} = $line{src};
722 $line{sha1} = $line{sha1dst};
723 $line{is_new} = $line{sha1src} =~ /^0+$/;
732 __PACKAGE__->meta->make_immutable;