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 # We either want an object or undef, *not* an empty list.
89 return $_[0]->gpp->get_object($_[1]) || undef;
94 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
100 my ($self, $dir) = @_;
102 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
107 Call out to the C<git> binary and return a string consisting of the output.
112 my ($self, @args) = @_;
114 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
116 open my $fh, '-|', $self->git, @args
117 or die "failed to run git command";
118 binmode $fh, ':encoding(UTF-8)';
120 my $output = do { local $/ = undef; <$fh> };
128 The directory under which the given project will reside i.e C<.git/..>
133 my($self, $project) = @_;
135 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
136 ? $project->stringify
137 : $self->dir_from_project_name($project);
140 if -f dir($dir)->file('.git/HEAD');
147 Run a C<git> command in a given project and return the output as a string.
152 my ($self, $project, @args) = @_;
154 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
159 Run a C<git> command for the project specified in the C<p> parameter and
160 return the output as a list of strings corresponding to the lines of output.
165 my($self, @args) = @_;
167 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
169 return $output ? split(/\n/, $output) : ();
174 Returns a hash corresponding to a given project's properties. The keys will
178 description (empty if .git/description is empty/unnamed)
185 my ($self, $project) = @_;
189 $self->get_project_properties(
190 $self->dir_from_project_name($project),
195 =head2 get_project_properties
197 Called by C<project_info> to get a project's properties.
201 sub get_project_properties {
202 my ($self, $dir) = @_;
206 $props{description} = $dir->file('description')->slurp;
207 chomp $props{description};
210 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
211 delete $props{description};
214 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
216 my $output = $self->run_cmd_in($dir, qw{
217 for-each-ref --format=%(committer)
218 --sort=-committerdate --count=1 refs/heads
221 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
222 my $dt = DateTime->from_epoch(epoch => $epoch);
223 $dt->set_time_zone($tz);
224 $props{last_change} = $dt;
232 For the C<repo_dir> specified in the config return an array of projects where
233 each item will contain the contents of L</project_info>.
238 my ($self, $dir) = @_;
240 my $base = dir($dir || $self->repo_dir);
243 my $dh = $base->open;
244 while (my $file = $dh->read) {
245 next if $file =~ /^.{1,2}$/;
247 my $obj = $base->subdir($file);
249 next unless $self->is_git_repo($obj);
251 # XXX Leaky abstraction alert!
252 my $is_bare = !-d $obj->subdir('.git');
254 my $name = (File::Spec->splitdir($obj))[-1];
256 name => ($name . ( $is_bare ? '' : '/.git' )),
257 $self->get_project_properties(
258 $is_bare ? $obj : $obj->subdir('.git')
263 return [sort { $a->{name} cmp $b->{name} } @ret];
266 =head2 dir_from_project_name
268 Get the corresponding directory of a given project.
272 sub dir_from_project_name {
273 my ($self, $project) = @_;
275 return dir($self->repo_dir)->subdir($project);
280 Find the hash of a given head (defaults to HEAD) of given (or current) project.
285 my ($self, $head, $project) = @_;
287 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
288 return unless defined $output;
290 my ($head) = $output =~ /^($SHA1RE)$/;
296 For a given tree sha1 return an array describing the tree's contents. Where
297 the keys for each item will be:
307 my ($self, $rev, $project) = @_;
309 $project ||= $self->project;
310 $rev ||= $self->head_hash($project);
312 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
313 return unless defined $output;
316 for my $line (split /\0/, $output) {
317 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
321 # XXX I wonder why directories always turn up as 040000 ...
322 modestr => $self->get_object_mode_string({mode=>oct $mode}),
332 =head2 get_object_mode_string
334 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
338 sub get_object_mode_string {
339 my ($self, $object) = @_;
341 return unless $object && $object->{mode};
342 return mode_to_string($object->{mode});
345 =head2 get_object_type
349 sub get_object_type {
350 my ($self, $object, $project) = @_;
352 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
353 return unless $output;
360 Return the contents of a given file.
365 my ($self, $object, $project) = @_;
367 my $type = $self->get_object_type($object);
368 die "object `$object' is not a file\n"
369 if (!defined $type || $type ne 'blob');
371 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
372 return unless $output;
379 For a given sha1 and path find the corresponding hash. Useful for find blobs.
384 my($self, $base, $path, $type) = @_;
388 my($line) = $self->command('ls-tree', $base, '--', $path)
391 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
392 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
393 return defined $type && $type ne $2
400 Check whether a given rev is valid i.e looks like a sha1.
405 my ($self, $rev) = @_;
408 return ($rev =~ /^($SHA1RE)$/);
413 Provides the raw output of a diff.
418 my ($self, @revs) = @_;
420 croak("Gitalist::Model::Git::diff needs either one or two revisions, got: @revs")
423 || any { !$self->valid_rev($_) } @revs;
425 return $self->command(diff => '--full-index', @revs);
429 diff --git a/TODO b/TODO
430 index 6a05e77..2071fd0 100644
434 * An action to find what branches have been merged, either as a list or through a search mechanism.
435 * An action to find which branches a given commit is on.
436 * Fix any not text/html bits e.g the patch action.
437 -* Simplify the creation of links.
438 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
439 index 706d024..7fac165 100644
440 --- a/lib/Gitalist/Controller/Root.pm
441 +++ b/lib/Gitalist/Controller/Root.pm
442 @@ -157,23 +157,6 @@ sub shortlog : Local {
448 -The tree of a given commit.
453 Returns a list of diff chunks corresponding to the files contained in the diff
454 and some associated metadata.
459 my($self, @revs) = @_;
461 my @diff = $self->raw_diff(@revs);
465 # This regex is a little pathological.
466 if(m{^diff --git (a/(.*?)) (b/\2)}) {
477 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
478 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
482 croak("No diff found for @revs")
485 # XXX Somewhat hacky. Ahem.
486 $ret[-1]{diff} .= "$_\n";
492 =head2 parse_rev_list
494 Given the output of the C<rev-list> command return a list of hashes.
499 my ($self, $output) = @_;
502 my @revs = split /\0/, $output;
504 for my $rev (split /\0/, $output) {
505 for my $line (split /\n/, $rev, 6) {
509 if ($self->valid_rev($line)) {
510 push @ret, $self->get_object($line);
520 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
526 my ($self, %args) = @_;
528 $args{sha1} ||= $self->head_hash($args{project});
530 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
532 (defined $args{ count } ? "--max-count=$args{count}" : ()),
533 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
536 ($args{file} ? $args{file} : ()),
538 return unless $output;
540 my @revs = $self->parse_rev_list($output);
547 Get a single piece of revision information for a given sha1.
552 my($self, $rev, $project) = @_;
554 return unless $self->valid_rev($rev);
556 return $self->list_revs(
557 rev => $rev, count => 1,
558 ( $project ? (project => $project) : () )
564 Calls the C<reflog> command and returns a list of hashes.
569 my ($self, @logargs) = @_;
572 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
573 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
577 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
578 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
580 Author: Foo Barsby <fbarsby@example.com>
581 Date: Thu Sep 17 12:26:05 2009 +0100
583 Merge branch 'abc123'
588 # XXX Stuff like this makes me want to switch to Git::PurePerl
589 my($sha1, $type, $author, $date)
591 ^ commit \s+ ($SHA1RE)$
593 Reflog[ ]message: \s+ (.+?)$ \s+
594 Author: \s+ ([^<]+) <.*?$ \s+
598 pos($_) = index($_, $date) + length $date;
600 # Yeah, I just did that.
602 my($msg) = /\G\s+(\S.*)/sg;
609 # XXX Add DateTime goodness.
618 Returns an array of hashes representing the heads (aka branches) for the
619 given, or current, project.
624 my ($self, $project) = @_;
626 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
629 for my $line (@output) {
630 my ($rev, $head, $commiter) = split /\0/, $line, 3;
631 $head =~ s!^refs/heads/!!;
633 push @ret, { sha1 => $rev, name => $head };
635 #FIXME: That isn't the time I'm looking for..
636 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
637 my $dt = DateTime->from_epoch(epoch => $epoch);
638 $dt->set_time_zone($tz);
639 $ret[-1]->{last_change} = $dt;
648 For a given sha1 check which branches currently point at it.
653 my($self, $sha1) = @_;
655 my $refs = $self->references->{$sha1};
657 return $refs ? @$refs : ();
662 A wrapper for C<git show-ref --dereference>. Based on gitweb's
663 C<git_get_references>.
670 return $self->{references}
671 if $self->{references};
673 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
674 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
675 my @reflist = $self->command(qw(show-ref --dereference))
680 push @{$refs{$1}}, $2
681 if m!^($SHA1RE)\srefs/(.*)$!;
684 return $self->{references} = \%refs;
689 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
690 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M TODO
691 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M lib/Gitalist/Controller/Root.pm
692 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M lib/Gitalist/View/Default.pm
693 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A lib/Gitalist/View/SyntaxHighlight.pm
694 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A root/static/css/syntax-dark.css
695 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
699 use List::MoreUtils qw(zip);
700 # XXX Hrm, getting called twice, not sure why.
703 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
704 to the C<diff-tree> output.
709 my($self, $commit) = @_;
711 my @dtout = $self->command(
712 # XXX should really deal with multple parents ...
713 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
716 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
718 # see. man git-diff-tree for more info
719 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
720 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
721 my %line = zip @keys, @vals;
722 # Some convenience keys
723 $line{file} = $line{src};
724 $line{sha1} = $line{sha1dst};
725 $line{is_new} = $line{sha1src} =~ /^0+$/;
734 __PACKAGE__->meta->make_immutable;