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;
329 =head2 get_object_mode_string
331 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
335 sub get_object_mode_string {
336 my ($self, $object) = @_;
338 return unless $object && $object->{mode};
339 return mode_to_string($object->{mode});
342 =head2 get_object_type
346 sub get_object_type {
347 my ($self, $object, $project) = @_;
349 chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
350 return unless $output;
357 Return the contents of a given file.
362 my ($self, $object, $project) = @_;
364 my $type = $self->get_object_type($object);
365 die "object `$object' is not a file\n"
366 if (!defined $type || $type ne 'blob');
368 my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
369 return unless $output;
376 For a given sha1 and path find the corresponding hash. Useful for find blobs.
381 my($self, $base, $path, $type) = @_;
385 my($line) = $self->command('ls-tree', $base, '--', $path)
388 #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa panic.c'
389 $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
390 return defined $type && $type ne $2
397 Check whether a given rev is valid i.e looks like a sha1.
402 my ($self, $rev) = @_;
405 return ($rev =~ /^($SHA1RE)$/);
415 my ($self, @revs, $project) = @_;
417 croak("Gitalist::Model::Git::diff needs a project and either one or two revisions")
420 || any { !$self->valid_rev($_) } @revs;
422 my $output = $self->run_cmd_in($project || $self->project, 'diff', @revs);
423 return unless $output;
429 my $formatter = DateTime::Format::Mail->new;
431 =head2 parse_rev_list
433 Given the output of the C<rev-list> command return a list of hashes.
438 my ($self, $output) = @_;
441 my @revs = split /\0/, $output;
443 for my $rev (split /\0/, $output) {
444 for my $line (split /\n/, $rev, 6) {
448 if ($self->valid_rev($line)) {
449 push @ret, {rev => $line};
453 if (my ($key, $value) = $line =~ /^(tree|parent)\s+(.*)$/) {
454 $ret[-1]->{$key} = $value;
458 if (my ($key, $value, $epoch, $tz) = $line =~ /^(author|committer)\s+(.*)\s+(\d+)\s+([+-]\d+)$/) {
459 $ret[-1]->{$key} = $value;
461 $ret[-1]->{ $key . "_datetime" } = DateTime->from_epoch(epoch => $epoch);
462 $ret[-1]->{ $key . "_datetime" }->set_time_zone($tz);
463 $ret[-1]->{ $key . "_datetime" }->set_formatter($formatter);
467 $ret[-1]->{ $key . "_datetime" } = "$epoch $tz";
470 if (my ($name, $email) = $value =~ /^([^<]+)\s+<([^>]+)>$/) {
471 $ret[-1]->{ $key . "_name" } = $name;
472 $ret[-1]->{ $key . "_email" } = $email;
476 $line =~ s/^\n?\s{4}//;
477 $ret[-1]->{longmessage} = $line;
478 $ret[-1]->{message} = (split /\n/, $line, 2)[0];
488 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
494 my ($self, %args) = @_;
496 $args{rev} ||= $self->head_hash($args{project});
498 my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
500 (defined $args{ count } ? "--max-count=$args{count}" : ()),
501 (defined $args{ skip } ? "--skip=$args{skip}" : ()),
504 ($args{file} ? $args{file} : ()),
506 return unless $output;
508 my @revs = $self->parse_rev_list($output);
515 Get a single piece of revision information for a given sha1.
520 my($self, $rev, $project) = @_;
522 return unless $self->valid_rev($rev);
524 return $self->list_revs(
525 rev => $rev, count => 1,
526 ( $project ? (project => $project) : () )
532 Calls the C<reflog> command and returns a list of hashes.
537 my ($self, @logargs) = @_;
540 = $self->run_cmd_in($self->project, qw(log -g), @logargs)
541 =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
545 commit 02526fc15beddf2c64798a947fecdd8d11bf993d
546 Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
548 Author: Foo Barsby <fbarsby@example.com>
549 Date: Thu Sep 17 12:26:05 2009 +0100
551 Merge branch 'abc123'
556 # XXX Stuff like this makes me want to switch to Git::PurePerl
557 my($sha1, $type, $author, $date)
559 ^ commit \s+ ($SHA1RE)$
561 Reflog[ ]message: \s+ (.+?)$ \s+
562 Author: \s+ ([^<]+) <.*?$ \s+
566 pos($_) = index($_, $date) + length $date;
568 # Yeah, I just did that.
570 my($msg) = /\G\s+(\S.*)/sg;
577 # XXX Add DateTime goodness.
586 Returns an array of hashes representing the heads (aka branches) for the
587 given, or current, project.
592 my ($self, $project) = @_;
594 my $output = $self->run_cmd_in($project || $self->project, qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
595 return unless $output;
598 for my $line (split /\n/, $output) {
599 my ($rev, $head, $commiter) = split /\0/, $line, 3;
600 $head =~ s!^refs/heads/!!;
602 push @ret, { rev => $rev, name => $head };
604 #FIXME: That isn't the time I'm looking for..
605 if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
606 my $dt = DateTime->from_epoch(epoch => $epoch);
607 $dt->set_time_zone($tz);
608 $ret[-1]->{last_change} = $dt;
617 For a given sha1 check which branches currently point at it.
622 my($self, $sha1) = @_;
624 my $refs = $self->references->{$sha1};
626 return $refs ? @$refs : ();
631 A wrapper for C<git show-ref --dereference>. Based on gitweb's
632 C<git_get_references>.
639 return $self->{references}
640 if $self->{references};
642 # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
643 # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
644 my @reflist = $self->command(qw(show-ref --dereference))
649 push @{$refs{$1}}, $2
650 if m!^($SHA1RE)\srefs/(.*)$!;
653 return $self->{references} = \%refs;
658 $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
659 :100644 100644 8976ebc7df65475b3def53a1653533c3f61070d0 852b6e170f1bad1fbd9930d3178dda8fdf1feae7 M TODO
660 :100644 100644 75f5e5f9ed10ae82a960fde77ecf138159c37610 7f54f8c3a4ad426f6889b13cfba5f5ad9969e3c6 M lib/Gitalist/Controller/Root.pm
661 :100644 100644 2c65caa46b56302502b9e6eef952b6f379c71fee e418acf5f7b5f771b0b2ef8be784e8dcd60a4271 M lib/Gitalist/View/Default.pm
662 :000000 100644 0000000000000000000000000000000000000000 642599f9ccfc4dbc7034987ad3233655010ff348 A lib/Gitalist/View/SyntaxHighlight.pm
663 :000000 100644 0000000000000000000000000000000000000000 3d2e533c41f01276b6f844bae98297273b38dffc A root/static/css/syntax-dark.css
664 :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M templates/blob.tt2
668 use List::MoreUtils qw(zip);
669 # XXX Hrm, getting called twice, not sure why.
672 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
673 to the C<diff-tree> output.
678 my($self, $commit) = @_;
680 my @dtout = $self->command(
681 # XXX should really deal with multple parents ...
682 qw(diff-tree -r --no-commit-id -M), $commit->parent_sha1, $commit->sha1
685 my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
687 # see. man git-diff-tree for more info
688 # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
689 my @vals = /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX])\t([^\t]+)(?:\t([^\n]+))?$/;
690 my %line = zip @keys, @vals;
691 # Some convenience keys
692 $line{file} = $line{src};
693 $line{sha1} = $line{sha1dst};
694 $line{is_new} = $line{sha1src} =~ /^0+$/;
703 __PACKAGE__->meta->make_immutable;