Git.pm: Add support for subdirectories inside of working copies
[git/dscho.git] / perl / Git.pm
blob7bbb5be77e1731bd378307826078843f7785cbc2
1 =head1 NAME
3 Git - Perl interface to the Git version control system
5 =cut
8 package Git;
10 use strict;
13 BEGIN {
15 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
17 # Totally unstable API.
18 $VERSION = '0.01';
21 =head1 SYNOPSIS
23 use Git;
25 my $version = Git::command_oneline('version');
27 git_cmd_try { Git::command_noisy('update-server-info') }
28 '%s failed w/ code %d';
30 my $repo = Git->repository (Directory => '/srv/git/cogito.git');
33 my @revs = $repo->command('rev-list', '--since=last monday', '--all');
35 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
36 my $lastrev = <$fh>; chomp $lastrev;
37 $repo->command_close_pipe($fh, $c);
39 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
40 STDERR => 0 );
42 =cut
45 require Exporter;
47 @ISA = qw(Exporter);
49 @EXPORT = qw(git_cmd_try);
51 # Methods which can be called as standalone functions as well:
52 @EXPORT_OK = qw(command command_oneline command_noisy
53 command_output_pipe command_input_pipe command_close_pipe
54 version exec_path hash_object git_cmd_try);
57 =head1 DESCRIPTION
59 This module provides Perl scripts easy way to interface the Git version control
60 system. The modules have an easy and well-tested way to call arbitrary Git
61 commands; in the future, the interface will also provide specialized methods
62 for doing easily operations which are not totally trivial to do over
63 the generic command interface.
65 While some commands can be executed outside of any context (e.g. 'version'
66 or 'init-db'), most operations require a repository context, which in practice
67 means getting an instance of the Git object using the repository() constructor.
68 (In the future, we will also get a new_repository() constructor.) All commands
69 called as methods of the object are then executed in the context of the
70 repository.
72 Part of the "repository state" is also information about path to the attached
73 working copy (unless you work with a bare repository). You can also navigate
74 inside of the working copy using the C<wc_chdir()> method. (Note that
75 the repository object is self-contained and will not change working directory
76 of your process.)
78 TODO: In the future, we might also do
80 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
81 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
82 my @refs = $remoterepo->refs();
84 Currently, the module merely wraps calls to external Git tools. In the future,
85 it will provide a much faster way to interact with Git by linking directly
86 to libgit. This should be completely opaque to the user, though (performance
87 increate nonwithstanding).
89 =cut
92 use Carp qw(carp croak); # but croak is bad - throw instead
93 use Error qw(:try);
94 use Cwd qw(abs_path);
96 require XSLoader;
97 XSLoader::load('Git', $VERSION);
102 =head1 CONSTRUCTORS
104 =over 4
106 =item repository ( OPTIONS )
108 =item repository ( DIRECTORY )
110 =item repository ()
112 Construct a new repository object.
113 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
114 Possible options are:
116 B<Repository> - Path to the Git repository.
118 B<WorkingCopy> - Path to the associated working copy; not strictly required
119 as many commands will happily crunch on a bare repository.
121 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
122 Just left undefined if you do not want to limit the scope of operations.
124 B<Directory> - Path to the Git working directory in its usual setup.
125 The C<.git> directory is searched in the directory and all the parent
126 directories; if found, C<WorkingCopy> is set to the directory containing
127 it and C<Repository> to the C<.git> directory itself. If no C<.git>
128 directory was found, the C<Directory> is assumed to be a bare repository,
129 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
130 If the C<$GIT_DIR> environment variable is set, things behave as expected
131 as well.
133 You should not use both C<Directory> and either of C<Repository> and
134 C<WorkingCopy> - the results of that are undefined.
136 Alternatively, a directory path may be passed as a single scalar argument
137 to the constructor; it is equivalent to setting only the C<Directory> option
138 field.
140 Calling the constructor with no options whatsoever is equivalent to
141 calling it with C<< Directory => '.' >>. In general, if you are building
142 a standard porcelain command, simply doing C<< Git->repository() >> should
143 do the right thing and setup the object to reflect exactly where the user
144 is right now.
146 =cut
148 sub repository {
149 my $class = shift;
150 my @args = @_;
151 my %opts = ();
152 my $self;
154 if (defined $args[0]) {
155 if ($#args % 2 != 1) {
156 # Not a hash.
157 $#args == 0 or throw Error::Simple("bad usage");
158 %opts = ( Directory => $args[0] );
159 } else {
160 %opts = @args;
164 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
165 $opts{Directory} ||= '.';
168 if ($opts{Directory}) {
169 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
171 my $search = Git->repository(WorkingCopy => $opts{Directory});
172 my $dir;
173 try {
174 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
175 STDERR => 0);
176 } catch Git::Error::Command with {
177 $dir = undef;
180 if ($dir) {
181 $opts{Repository} = abs_path($dir);
183 # If --git-dir went ok, this shouldn't die either.
184 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
185 $dir = abs_path($opts{Directory}) . '/';
186 if ($prefix) {
187 if (substr($dir, -length($prefix)) ne $prefix) {
188 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
190 substr($dir, -length($prefix)) = '';
192 $opts{WorkingCopy} = $dir;
193 $opts{WorkingSubdir} = $prefix;
195 } else {
196 # A bare repository? Let's see...
197 $dir = $opts{Directory};
199 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
200 # Mimick git-rev-parse --git-dir error message:
201 throw Error::Simple('fatal: Not a git repository');
203 my $search = Git->repository(Repository => $dir);
204 try {
205 $search->command('symbolic-ref', 'HEAD');
206 } catch Git::Error::Command with {
207 # Mimick git-rev-parse --git-dir error message:
208 throw Error::Simple('fatal: Not a git repository');
211 $opts{Repository} = abs_path($dir);
214 delete $opts{Directory};
217 $self = { opts => \%opts };
218 bless $self, $class;
222 =back
224 =head1 METHODS
226 =over 4
228 =item command ( COMMAND [, ARGUMENTS... ] )
230 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
232 Execute the given Git C<COMMAND> (specify it without the 'git-'
233 prefix), optionally with the specified extra C<ARGUMENTS>.
235 The second more elaborate form can be used if you want to further adjust
236 the command execution. Currently, only one option is supported:
238 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
239 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
240 it to be thrown away. If you want to process it, you can get it in a filehandle
241 you specify, but you must be extremely careful; if the error output is not
242 very short and you want to read it in the same process as where you called
243 C<command()>, you are set up for a nice deadlock!
245 The method can be called without any instance or on a specified Git repository
246 (in that case the command will be run in the repository context).
248 In scalar context, it returns all the command output in a single string
249 (verbatim).
251 In array context, it returns an array containing lines printed to the
252 command's stdout (without trailing newlines).
254 In both cases, the command's stdin and stderr are the same as the caller's.
256 =cut
258 sub command {
259 my ($fh, $ctx) = command_output_pipe(@_);
261 if (not defined wantarray) {
262 # Nothing to pepper the possible exception with.
263 _cmd_close($fh, $ctx);
265 } elsif (not wantarray) {
266 local $/;
267 my $text = <$fh>;
268 try {
269 _cmd_close($fh, $ctx);
270 } catch Git::Error::Command with {
271 # Pepper with the output:
272 my $E = shift;
273 $E->{'-outputref'} = \$text;
274 throw $E;
276 return $text;
278 } else {
279 my @lines = <$fh>;
280 chomp @lines;
281 try {
282 _cmd_close($fh, $ctx);
283 } catch Git::Error::Command with {
284 my $E = shift;
285 $E->{'-outputref'} = \@lines;
286 throw $E;
288 return @lines;
293 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
295 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
297 Execute the given C<COMMAND> in the same way as command()
298 does but always return a scalar string containing the first line
299 of the command's standard output.
301 =cut
303 sub command_oneline {
304 my ($fh, $ctx) = command_output_pipe(@_);
306 my $line = <$fh>;
307 defined $line and chomp $line;
308 try {
309 _cmd_close($fh, $ctx);
310 } catch Git::Error::Command with {
311 # Pepper with the output:
312 my $E = shift;
313 $E->{'-outputref'} = \$line;
314 throw $E;
316 return $line;
320 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
322 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
324 Execute the given C<COMMAND> in the same way as command()
325 does but return a pipe filehandle from which the command output can be
326 read.
328 The function can return C<($pipe, $ctx)> in array context.
329 See C<command_close_pipe()> for details.
331 =cut
333 sub command_output_pipe {
334 _command_common_pipe('-|', @_);
338 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
340 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
342 Execute the given C<COMMAND> in the same way as command_output_pipe()
343 does but return an input pipe filehandle instead; the command output
344 is not captured.
346 The function can return C<($pipe, $ctx)> in array context.
347 See C<command_close_pipe()> for details.
349 =cut
351 sub command_input_pipe {
352 _command_common_pipe('|-', @_);
356 =item command_close_pipe ( PIPE [, CTX ] )
358 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
359 whether the command finished successfuly. The optional C<CTX> argument
360 is required if you want to see the command name in the error message,
361 and it is the second value returned by C<command_*_pipe()> when
362 called in array context. The call idiom is:
364 my ($fh, $ctx) = $r->command_output_pipe('status');
365 while (<$fh>) { ... }
366 $r->command_close_pipe($fh, $ctx);
368 Note that you should not rely on whatever actually is in C<CTX>;
369 currently it is simply the command name but in future the context might
370 have more complicated structure.
372 =cut
374 sub command_close_pipe {
375 my ($self, $fh, $ctx) = _maybe_self(@_);
376 $ctx ||= '<unknown>';
377 _cmd_close($fh, $ctx);
381 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
383 Execute the given C<COMMAND> in the same way as command() does but do not
384 capture the command output - the standard output is not redirected and goes
385 to the standard output of the caller application.
387 While the method is called command_noisy(), you might want to as well use
388 it for the most silent Git commands which you know will never pollute your
389 stdout but you want to avoid the overhead of the pipe setup when calling them.
391 The function returns only after the command has finished running.
393 =cut
395 sub command_noisy {
396 my ($self, $cmd, @args) = _maybe_self(@_);
397 _check_valid_cmd($cmd);
399 my $pid = fork;
400 if (not defined $pid) {
401 throw Error::Simple("fork failed: $!");
402 } elsif ($pid == 0) {
403 _cmd_exec($self, $cmd, @args);
405 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
406 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
411 =item version ()
413 Return the Git version in use.
415 Implementation of this function is very fast; no external command calls
416 are involved.
418 =cut
420 # Implemented in Git.xs.
423 =item exec_path ()
425 Return path to the Git sub-command executables (the same as
426 C<git --exec-path>). Useful mostly only internally.
428 Implementation of this function is very fast; no external command calls
429 are involved.
431 =cut
433 # Implemented in Git.xs.
436 =item repo_path ()
438 Return path to the git repository. Must be called on a repository instance.
440 =cut
442 sub repo_path { $_[0]->{opts}->{Repository} }
445 =item wc_path ()
447 Return path to the working copy. Must be called on a repository instance.
449 =cut
451 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
454 =item wc_subdir ()
456 Return path to the subdirectory inside of a working copy. Must be called
457 on a repository instance.
459 =cut
461 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
464 =item wc_chdir ( SUBDIR )
466 Change the working copy subdirectory to work within. The C<SUBDIR> is
467 relative to the working copy root directory (not the current subdirectory).
468 Must be called on a repository instance attached to a working copy
469 and the directory must exist.
471 =cut
473 sub wc_chdir {
474 my ($self, $subdir) = @_;
476 $self->wc_path()
477 or throw Error::Simple("bare repository");
479 -d $self->wc_path().'/'.$subdir
480 or throw Error::Simple("subdir not found: $!");
481 # Of course we will not "hold" the subdirectory so anyone
482 # can delete it now and we will never know. But at least we tried.
484 $self->{opts}->{WorkingSubdir} = $subdir;
488 =item hash_object ( FILENAME [, TYPE ] )
490 =item hash_object ( FILEHANDLE [, TYPE ] )
492 Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
493 C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>
494 (default), C<commit>, C<tree>).
496 In case of C<FILEHANDLE> passed instead of file name, all the data
497 available are read and hashed, and the filehandle is automatically
498 closed. The file handle should be freshly opened - if you have already
499 read anything from the file handle, the results are undefined (since
500 this function works directly with the file descriptor and internal
501 PerlIO buffering might have messed things up).
503 The method can be called without any instance or on a specified Git repository,
504 it makes zero difference.
506 The function returns the SHA1 hash.
508 Implementation of this function is very fast; no external command calls
509 are involved.
511 =cut
513 # Implemented in Git.xs.
517 =back
519 =head1 ERROR HANDLING
521 All functions are supposed to throw Perl exceptions in case of errors.
522 See the L<Error> module on how to catch those. Most exceptions are mere
523 L<Error::Simple> instances.
525 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
526 functions suite can throw C<Git::Error::Command> exceptions as well: those are
527 thrown when the external command returns an error code and contain the error
528 code as well as access to the captured command's output. The exception class
529 provides the usual C<stringify> and C<value> (command's exit code) methods and
530 in addition also a C<cmd_output> method that returns either an array or a
531 string with the captured command output (depending on the original function
532 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
533 returns the command and its arguments (but without proper quoting).
535 Note that the C<command_*_pipe()> functions cannot throw this exception since
536 it has no idea whether the command failed or not. You will only find out
537 at the time you C<close> the pipe; if you want to have that automated,
538 use C<command_close_pipe()>, which can throw the exception.
540 =cut
543 package Git::Error::Command;
545 @Git::Error::Command::ISA = qw(Error);
547 sub new {
548 my $self = shift;
549 my $cmdline = '' . shift;
550 my $value = 0 + shift;
551 my $outputref = shift;
552 my(@args) = ();
554 local $Error::Depth = $Error::Depth + 1;
556 push(@args, '-cmdline', $cmdline);
557 push(@args, '-value', $value);
558 push(@args, '-outputref', $outputref);
560 $self->SUPER::new(-text => 'command returned error', @args);
563 sub stringify {
564 my $self = shift;
565 my $text = $self->SUPER::stringify;
566 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
569 sub cmdline {
570 my $self = shift;
571 $self->{'-cmdline'};
574 sub cmd_output {
575 my $self = shift;
576 my $ref = $self->{'-outputref'};
577 defined $ref or undef;
578 if (ref $ref eq 'ARRAY') {
579 return @$ref;
580 } else { # SCALAR
581 return $$ref;
586 =over 4
588 =item git_cmd_try { CODE } ERRMSG
590 This magical statement will automatically catch any C<Git::Error::Command>
591 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
592 on its lips; the message will have %s substituted for the command line
593 and %d for the exit status. This statement is useful mostly for producing
594 more user-friendly error messages.
596 In case of no exception caught the statement returns C<CODE>'s return value.
598 Note that this is the only auto-exported function.
600 =cut
602 sub git_cmd_try(&$) {
603 my ($code, $errmsg) = @_;
604 my @result;
605 my $err;
606 my $array = wantarray;
607 try {
608 if ($array) {
609 @result = &$code;
610 } else {
611 $result[0] = &$code;
613 } catch Git::Error::Command with {
614 my $E = shift;
615 $err = $errmsg;
616 $err =~ s/\%s/$E->cmdline()/ge;
617 $err =~ s/\%d/$E->value()/ge;
618 # We can't croak here since Error.pm would mangle
619 # that to Error::Simple.
621 $err and croak $err;
622 return $array ? @result : $result[0];
626 =back
628 =head1 COPYRIGHT
630 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
632 This module is free software; it may be used, copied, modified
633 and distributed under the terms of the GNU General Public Licence,
634 either version 2, or (at your option) any later version.
636 =cut
639 # Take raw method argument list and return ($obj, @args) in case
640 # the method was called upon an instance and (undef, @args) if
641 # it was called directly.
642 sub _maybe_self {
643 # This breaks inheritance. Oh well.
644 ref $_[0] eq 'Git' ? @_ : (undef, @_);
647 # Check if the command id is something reasonable.
648 sub _check_valid_cmd {
649 my ($cmd) = @_;
650 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
653 # Common backend for the pipe creators.
654 sub _command_common_pipe {
655 my $direction = shift;
656 my ($self, @p) = _maybe_self(@_);
657 my (%opts, $cmd, @args);
658 if (ref $p[0]) {
659 ($cmd, @args) = @{shift @p};
660 %opts = ref $p[0] ? %{$p[0]} : @p;
661 } else {
662 ($cmd, @args) = @p;
664 _check_valid_cmd($cmd);
666 my $pid = open(my $fh, $direction);
667 if (not defined $pid) {
668 throw Error::Simple("open failed: $!");
669 } elsif ($pid == 0) {
670 if (defined $opts{STDERR}) {
671 close STDERR;
673 if ($opts{STDERR}) {
674 open (STDERR, '>&', $opts{STDERR})
675 or die "dup failed: $!";
677 _cmd_exec($self, $cmd, @args);
679 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
682 # When already in the subprocess, set up the appropriate state
683 # for the given repository and execute the git command.
684 sub _cmd_exec {
685 my ($self, @args) = @_;
686 if ($self) {
687 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
688 $self->wc_path() and chdir($self->wc_path());
689 $self->wc_subdir() and chdir($self->wc_subdir());
691 _execv_git_cmd(@args);
692 die "exec failed: $!";
695 # Execute the given Git command ($_[0]) with arguments ($_[1..])
696 # by searching for it at proper places.
697 # _execv_git_cmd(), implemented in Git.xs.
699 # Close pipe to a subprocess.
700 sub _cmd_close {
701 my ($fh, $ctx) = @_;
702 if (not close $fh) {
703 if ($!) {
704 # It's just close, no point in fatalities
705 carp "error closing pipe: $!";
706 } elsif ($? >> 8) {
707 # The caller should pepper this.
708 throw Git::Error::Command($ctx, $? >> 8);
710 # else we might e.g. closed a live stream; the command
711 # dying of SIGPIPE would drive us here.
716 # Trickery for .xs routines: In order to avoid having some horrid
717 # C code trying to do stuff with undefs and hashes, we gate all
718 # xs calls through the following and in case we are being ran upon
719 # an instance call a C part of the gate which will set up the
720 # environment properly.
721 sub _call_gate {
722 my $xsfunc = shift;
723 my ($self, @args) = _maybe_self(@_);
725 if (defined $self) {
726 # XXX: We ignore the WorkingCopy! To properly support
727 # that will require heavy changes in libgit.
729 # XXX: And we ignore everything else as well. libgit
730 # at least needs to be extended to let us specify
731 # the $GIT_DIR instead of looking it up in environment.
732 #xs_call_gate($self->{opts}->{Repository});
735 # Having to call throw from the C code is a sure path to insanity.
736 local $SIG{__DIE__} = sub { throw Error::Simple("@_"); };
737 &$xsfunc(@args);
740 sub AUTOLOAD {
741 my $xsname;
742 our $AUTOLOAD;
743 ($xsname = $AUTOLOAD) =~ s/.*:://;
744 throw Error::Simple("&Git::$xsname not defined") if $xsname =~ /^xs_/;
745 $xsname = 'xs_'.$xsname;
746 _call_gate(\&$xsname, @_);
749 sub DESTROY { }
752 1; # Famous last words