1 package Gitalist::Model::Git;
4 use namespace::autoclean;
7 extends 'Catalyst::Model';
8 with 'Catalyst::Component::InstancePerContext';
12 Gitalist::Model::Git - the model for git interactions
16 [enter your description here]
24 sub build_per_context_instance {
25 my ( $self, $c ) = @_;
27 my $app = blessed($c) || $c;
28 my $model = Git::Repos->new(
29 project => ([$c->req->parameters->{p} || '/']->flatten)[0],
30 repo_dir => $app->config->{repo_dir}, # FIXME - Move to model config
33 # This is fugly as fuck. Move Git::PurePerl construction into attribute builders..
34 (my $pd = $self->project_dir( $self->project )) =~ s{/\.git$}();
35 $model->gpp( Git::PurePerl->new(directory => $pd) );
40 package Git::Repos; # Better name? Split out into own file once we have a sane name.
42 use namespace::autoclean;
48 use DateTime::Format::Mail;
49 use File::Stat::ModeString;
50 use List::MoreUtils qw/any zip/;
51 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
55 # Should these live in a separate module? Or perhaps extended Regexp::Common?
56 # No, should be a MooseX::Types module!!
57 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
59 # These are static and only need to be setup on app start.
60 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
61 has git => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
62 # These are dynamic and can be different from one request to the next.
63 has project => ( isa => NonEmptySimpleStr, is => 'rw');
64 has gpp => ( isa => 'Git::PurePerl', is => 'rw', lazy_build => 1 );
74 $self->git; # Cause lazy value build.
79 my $git = File::Which::which('git');
83 Could not find a git executable.
84 Please specify the which git executable to use in gitweb.yml
93 A wrapper for the equivalent L<Git::PurePerl> method.
98 my($self, $sha1) = @_;
100 # We either want an object or undef, *not* an empty list.
101 return $self->gpp->get_object($sha1) || undef;
106 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
112 my ($self, $dir) = @_;
114 return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
119 Call out to the C<git> binary and return a string consisting of the output.
124 my ($self, @args) = @_;
126 print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
128 open my $fh, '-|', $self->git, @args
129 or die "failed to run git command";
130 binmode $fh, ':encoding(UTF-8)';
132 my $output = do { local $/ = undef; <$fh> };
140 The directory under which the given project will reside i.e C<.git/..>
145 my($self, $project) = @_;
147 my $dir = blessed($project) && $project->isa('Path::Class::Dir')
148 ? $project->stringify
149 : $self->dir_from_project_name($project);
152 if -f dir($dir)->file('.git/HEAD');
159 Run a C<git> command in a given project and return the output as a string.
164 my ($self, $project, @args) = @_;
166 return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
171 Run a C<git> command for the project specified in the C<p> parameter and
172 return the output as a list of strings corresponding to the lines of output.
177 my($self, @args) = @_;
179 my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
181 return $output ? split(/\n/, $output) : ();
186 Returns a hash corresponding to a given project's properties. The keys will
190 description (empty if .git/description is empty/unnamed)
197 my ($self, $project) = @_;
201 $self->get_project_properties(
202 $self->dir_from_project_name($project),
207 =head2 get_project_properties
209 Called by C<project_info> to get a project's properties.
213 sub get_project_properties {
214 my ($self, $dir) = @_;
218 $props{description} = $dir->file('description')->slurp;
219 chomp $props{description};
222 if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
223 delete $props{description};
226 ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
228 my $output = $self->run_cmd_in($dir, qw{
229 for-each-ref --format=%(committer)
230 --sort=-committerdate --count=1 refs/heads
233 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
234 my $dt = DateTime->from_epoch(epoch => $epoch);
235 $dt->set_time_zone($tz);
236 $props{last_change} = $dt;
244 For the C<repo_dir> specified in the config return an array of projects where
245 each item will contain the contents of L</project_info>.
250 my ($self, $dir) = @_;
252 my $base = dir($dir || $self->repo_dir);
255 my $dh = $base->open or die("Cannot open dir $base");
256 while (my $file = $dh->read) {
257 next if $file =~ /^.{1,2}$/;
259 my $obj = $base->subdir($file);
261 next unless $self->is_git_repo($obj);
262 # XXX Leaky abstraction alert!
263 my $is_bare = !-d $obj->subdir('.git');
265 my $name = (File::Spec->splitdir($obj))[-1];
267 name => ($name . ( $is_bare ? '' : '/.git' )),
268 $self->get_project_properties(
269 $is_bare ? $obj : $obj->subdir('.git')
274 return [sort { $a->{name} cmp $b->{name} } @ret];
277 =head2 dir_from_project_name
279 Get the corresponding directory of a given project.
283 sub dir_from_project_name {
284 my ($self, $project) = @_;
286 return dir($self->repo_dir)->subdir($project);
291 Find the hash of a given head (defaults to HEAD) of given (or current) project.
296 my ($self, $head, $project) = @_;
298 my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
299 return unless defined $output;
301 my($sha1) = $output =~ /^($SHA1RE)$/;
307 For a given tree sha1 return an array describing the tree's contents. Where
308 the keys for each item will be:
318 my ($self, $rev, $project) = @_;
320 $project ||= $self->project;
321 $rev ||= $self->head_hash($project);
323 my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
324 return unless defined $output;
327 for my $line (split /\0/, $output) {
328 my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
332 # XXX I wonder why directories always turn up as 040000 ...
333 modestr => $self->get_object_mode_string({mode=>oct $mode}),
343 =head2 get_object_mode_string
345 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
349 sub get_object_mode_string {
350 my ($self, $object) = @_;
352 return unless $object && $object->{mode};
353 return mode_to_string($object->{mode});
356 =head2 get_object_type
360 sub get_object_type {
361 my ($self, $object, $project) = @_;
363 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
364 return unless $output;
371 Return the contents of a given file.
376 my ($self, $object, $project) = @_;
378 my $type = $self->get_object_type($object, $project);
379 die "object `$object' is not a file\n"
380 if (!defined $type || $type ne 'blob');
382 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
383 return unless $output;
390 For a given sha1 and path find the corresponding hash. Useful for find blobs.
395 my($self, $base, $path, $type) = @_;
399 my($line) = $self->command('ls-tree', $base, '--', $path)
402 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
403 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
404 return defined $type && $type ne $2
411 Check whether a given rev is valid i.e looks like a sha1.
416 my ($self, $rev) = @_;
419 return ($rev =~ /^($SHA1RE)$/);
424 Provides the raw output of a diff.
428 # gitweb uses the following sort of command for diffing merges:
429 # /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 --
430 # and for regular diffs
431 # /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 --
434 my ($self, @args) = @_;
436 return $self->command(
437 qw(diff-tree -r -M --no-commit-id --full-index),
443 diff --git a/TODO b/TODO
444 index 6a05e77..2071fd0 100644
448 * An action to find what branches have been merged, either as a list or through a search mechanism.
449 * An action to find which branches a given commit is on.
450 * Fix any not text/html bits e.g the patch action.
451 -* Simplify the creation of links.
452 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
453 index 706d024..7fac165 100644
454 --- a/lib/Gitalist/Controller/Root.pm
455 +++ b/lib/Gitalist/Controller/Root.pm
456 @@ -157,23 +157,6 @@ sub shortlog : Local {
462 -The tree of a given commit.
467 Returns a list of diff chunks corresponding to the files contained in the diff
468 and some associated metadata.
472 # XXX Ideally this would return a wee object instead of ad hoc structures.
474 my($self, %args) = @_;
476 # So either a parent is specifed, or we use the commit's parent if there's
477 # only one, otherwise it was a merge commit.
478 my $parent = $args{parent}
480 : @{$args{commit}->parents} <= 1
481 ? $args{commit}->parent_sha1
484 ( $args{file} ? ('--', $args{file}) : () ),
487 my @out = $self->raw_diff(
488 ( $args{patch} ? '--patch-with-raw' : () ),
489 $parent, $args{commit}->sha1, @etc
492 # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
493 my @difftree = $self->parse_diff_tree(\@out);
498 # The blank line between the tree and the patch.
501 # XXX And no I'm not happy about having diff return tree + patch.
502 return \@difftree, [$self->parse_diff(@out)];
506 my($self, @diff) = @_;
510 # This regex is a little pathological.
511 if(m{^diff --git (a/(.*?)) (b/\2)}) {
522 if(/^index (\w+)\.\.(\w+) (\d+)$/) {
523 @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
527 # XXX Somewhat hacky. Ahem.
528 $ret[@ret ? -1 : 0]{diff} .= "$_\n";
534 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
535 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
537 =head2 parse_diff_tree
539 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
540 to the C<diff-tree> output.
544 sub parse_diff_tree {
545 my($self, $diff) = @_;
547 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
549 while(@$diff and $diff->[0] =~ /^:\d+/) {
550 my $line = shift @$diff;
551 # see. man git-diff-tree for more info
552 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
553 my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
554 my %line = zip @keys, @vals;
555 # Some convenience keys
556 $line{file} = $line{src};
557 $line{sha1} = $line{sha1dst};
558 $line{is_new} = $line{sha1src} =~ /^0+$/
560 @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
561 if $line{status} =~ /^R/;
568 =head2 parse_rev_list
570 Given the output of the C<rev-list> command return a list of hashes.
575 my ($self, $output) = @_;
578 my @revs = split /\0/, $output;
580 for my $rev (split /\0/, $output) {
581 for my $line (split /\n/, $rev, 6) {
585 if ($self->valid_rev($line)) {
586 push @ret, $self->get_object($line);
596 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
602 my ($self, %args) = @_;
604 $args{sha1} ||= $self->head_hash($args{project});
606 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
608 (defined $args{ count } ? "--max-count=$args{count}" : ()),
609 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
612 ($args{file} ? $args{file} : ()),
614 return unless $output;
616 my @revs = $self->parse_rev_list($output);
623 Get a single piece of revision information for a given sha1.
628 my($self, $rev, $project) = @_;
630 return unless $self->valid_rev($rev);
632 return $self->list_revs(
633 rev => $rev, count => 1,
634 ( $project ? (project => $project) : () )
640 Calls the C<reflog> command and returns a list of hashes.
645 my ($self, @logargs) = @_;
648 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
649 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
652 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
653 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
655 Author: Foo Barsby <fbarsby@example.com>
656 Date: Thu Sep 17 12:26:05 2009 +0100
658 Merge branch 'abc123'
663 # XXX Stuff like this makes me want to switch to Git::PurePerl
664 my($sha1, $type, $author, $date)
666 ^ commit \s+ ($SHA1RE)$
668 Reflog[ ]message: \s+ (.+?)$ \s+
669 Author: \s+ ([^<]+) <.*?$ \s+
673 pos($_) = index($_, $date) + length $date;
675 # Yeah, I just did that.
677 my($msg) = /\G\s+(\S.*)/sg;
684 # XXX Add DateTime goodness.
693 Returns an array of hashes representing the heads (aka branches) for the
694 given, or current, project.
699 my ($self, $project) = @_;
701 my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
704 for my $line (@output) {
705 my ($rev, $head, $commiter) = split /\0/, $line, 3;
706 $head =~ s!^refs/heads/!!;
708 push @ret, { sha1 => $rev, name => $head };
710 #FIXME: That isn't the time I'm looking for..
711 if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
712 my $dt = DateTime->from_epoch(epoch => $epoch);
713 $dt->set_time_zone($tz);
714 $ret[-1]->{last_change} = $dt;
723 For a given sha1 check which branches currently point at it.
728 my($self, $sha1) = @_;
730 my $refs = $self->references->{$sha1};
732 return $refs ? @$refs : ();
737 A wrapper for C<git show-ref --dereference>. Based on gitweb's
738 C<git_get_references>.
745 return $self->{references}
746 if $self->{references};
748 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
749 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
750 my @reflist = $self->command(qw(show-ref --dereference))
755 push @{$refs{$1}}, $2
756 if m!^($SHA1RE)\srefs/(.*)$!;
759 return $self->{references} = \%refs;
764 __PACKAGE__->meta->make_immutable;