"test" in Solaris' /bin/sh does not support -e
[gitweb.git] / perl / Git.pm
index 11ec62d4068f6ca19c24166273f3ad025fe2506e..05814477577d79cfda03b1850402de5c40b8b616 100644 (file)
@@ -36,7 +36,8 @@ =head1 SYNOPSIS
   my $lastrev = <$fh>; chomp $lastrev;
   $repo->command_close_pipe($fh, $c);
 
-  my $lastrev = $repo->command_oneline('rev-list', '--all');
+  my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
+                                        STDERR => 0 );
 
 =cut
 
@@ -68,20 +69,18 @@ =head1 DESCRIPTION
 called as methods of the object are then executed in the context of the
 repository.
 
-TODO: In the future, we might also do
+Part of the "repository state" is also information about path to the attached
+working copy (unless you work with a bare repository). You can also navigate
+inside of the working copy using the C<wc_chdir()> method. (Note that
+the repository object is self-contained and will not change working directory
+of your process.)
 
-       my $subdir = $repo->subdir('Documentation');
-       # Gets called in the subdirectory context:
-       $subdir->command('status');
+TODO: In the future, we might also do
 
        my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
        $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
        my @refs = $remoterepo->refs();
 
-So far, all functions just die if anything goes wrong. If you don't want that,
-make appropriate provisions to catch the possible deaths. Better error recovery
-mechanisms will be provided in the future.
-
 Currently, the module merely wraps calls to external Git tools. In the future,
 it will provide a much faster way to interact with Git by linking directly
 to libgit. This should be completely opaque to the user, though (performance
@@ -92,6 +91,7 @@ =head1 DESCRIPTION
 
 use Carp qw(carp croak); # but croak is bad - throw instead
 use Error qw(:try);
+use Cwd qw(abs_path);
 
 require XSLoader;
 XSLoader::load('Git', $VERSION);
@@ -118,12 +118,17 @@ =head1 CONSTRUCTORS
 B<WorkingCopy> - Path to the associated working copy; not strictly required
 as many commands will happily crunch on a bare repository.
 
-B<Directory> - Path to the Git working directory in its usual setup. This
-is just for convenient setting of both C<Repository> and C<WorkingCopy>
-at once: If the directory as a C<.git> subdirectory, C<Repository> is pointed
-to the subdirectory and the directory is assumed to be the working copy.
-If the directory does not have the subdirectory, C<WorkingCopy> is left
-undefined and C<Repository> is pointed to the directory itself.
+B<WorkingSubdir> - Subdirectory in the working copy to work inside.
+Just left undefined if you do not want to limit the scope of operations.
+
+B<Directory> - Path to the Git working directory in its usual setup.
+The C<.git> directory is searched in the directory and all the parent
+directories; if found, C<WorkingCopy> is set to the directory containing
+it and C<Repository> to the C<.git> directory itself. If no C<.git>
+directory was found, the C<Directory> is assumed to be a bare repository,
+C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
+If the C<$GIT_DIR> environment variable is set, things behave as expected
+as well.
 
 You should not use both C<Directory> and either of C<Repository> and
 C<WorkingCopy> - the results of that are undefined.
@@ -133,7 +138,10 @@ =head1 CONSTRUCTORS
 field.
 
 Calling the constructor with no options whatsoever is equivalent to
-calling it with C<< Directory => '.' >>.
+calling it with C<< Directory => '.' >>. In general, if you are building
+a standard porcelain command, simply doing C<< Git->repository() >> should
+do the right thing and setup the object to reflect exactly where the user
+is right now.
 
 =cut
 
@@ -151,18 +159,60 @@ sub repository {
                } else {
                        %opts = @args;
                }
+       }
+
+       if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
+               $opts{Directory} ||= '.';
+       }
+
+       if ($opts{Directory}) {
+               -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
+
+               my $search = Git->repository(WorkingCopy => $opts{Directory});
+               my $dir;
+               try {
+                       $dir = $search->command_oneline(['rev-parse', '--git-dir'],
+                                                       STDERR => 0);
+               } catch Git::Error::Command with {
+                       $dir = undef;
+               };
+
+               if ($dir) {
+                       $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
+                       $opts{Repository} = $dir;
+
+                       # If --git-dir went ok, this shouldn't die either.
+                       my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
+                       $dir = abs_path($opts{Directory}) . '/';
+                       if ($prefix) {
+                               if (substr($dir, -length($prefix)) ne $prefix) {
+                                       throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
+                               }
+                               substr($dir, -length($prefix)) = '';
+                       }
+                       $opts{WorkingCopy} = $dir;
+                       $opts{WorkingSubdir} = $prefix;
+
+               } else {
+                       # A bare repository? Let's see...
+                       $dir = $opts{Directory};
 
-               if ($opts{Directory}) {
-                       -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
-                       if (-d $opts{Directory}."/.git") {
-                               # TODO: Might make this more clever
-                               $opts{WorkingCopy} = $opts{Directory};
-                               $opts{Repository} = $opts{Directory}."/.git";
-                       } else {
-                               $opts{Repository} = $opts{Directory};
+                       unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
+                               # Mimick git-rev-parse --git-dir error message:
+                               throw Error::Simple('fatal: Not a git repository');
+                       }
+                       my $search = Git->repository(Repository => $dir);
+                       try {
+                               $search->command('symbolic-ref', 'HEAD');
+                       } catch Git::Error::Command with {
+                               # Mimick git-rev-parse --git-dir error message:
+                               throw Error::Simple('fatal: Not a git repository');
                        }
-                       delete $opts{Directory};
+
+                       $opts{Repository} = abs_path($dir);
                }
+
+               delete $opts{Directory};
        }
 
        $self = { opts => \%opts };
@@ -178,9 +228,21 @@ =head1 METHODS
 
 =item command ( COMMAND [, ARGUMENTS... ] )
 
+=item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
+
 Execute the given Git C<COMMAND> (specify it without the 'git-'
 prefix), optionally with the specified extra C<ARGUMENTS>.
 
+The second more elaborate form can be used if you want to further adjust
+the command execution. Currently, only one option is supported:
+
+B<STDERR> - How to deal with the command's error output. By default (C<undef>)
+it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
+it to be thrown away. If you want to process it, you can get it in a filehandle
+you specify, but you must be extremely careful; if the error output is not
+very short and you want to read it in the same process as where you called
+C<command()>, you are set up for a nice deadlock!
+
 The method can be called without any instance or on a specified Git repository
 (in that case the command will be run in the repository context).
 
@@ -231,6 +293,8 @@ sub command {
 
 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
 
+=item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
+
 Execute the given C<COMMAND> in the same way as command()
 does but always return a scalar string containing the first line
 of the command's standard output.
@@ -241,7 +305,7 @@ sub command_oneline {
        my ($fh, $ctx) = command_output_pipe(@_);
 
        my $line = <$fh>;
-       chomp $line;
+       defined $line and chomp $line;
        try {
                _cmd_close($fh, $ctx);
        } catch Git::Error::Command with {
@@ -256,6 +320,8 @@ sub command_oneline {
 
 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
 
+=item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
+
 Execute the given C<COMMAND> in the same way as command()
 does but return a pipe filehandle from which the command output can be
 read.
@@ -272,6 +338,8 @@ sub command_output_pipe {
 
 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
 
+=item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
+
 Execute the given C<COMMAND> in the same way as command_output_pipe()
 does but return an input pipe filehandle instead; the command output
 is not captured.
@@ -355,7 +423,7 @@ sub command_noisy {
 
 =item exec_path ()
 
-Return path to the git sub-command executables (the same as
+Return path to the Git sub-command executables (the same as
 C<git --exec-path>). Useful mostly only internally.
 
 Implementation of this function is very fast; no external command calls
@@ -366,13 +434,65 @@ sub command_noisy {
 # Implemented in Git.xs.
 
 
-=item hash_object ( FILENAME [, TYPE ] )
+=item repo_path ()
+
+Return path to the git repository. Must be called on a repository instance.
+
+=cut
+
+sub repo_path { $_[0]->{opts}->{Repository} }
+
 
-=item hash_object ( FILEHANDLE [, TYPE ] )
+=item wc_path ()
+
+Return path to the working copy. Must be called on a repository instance.
+
+=cut
+
+sub wc_path { $_[0]->{opts}->{WorkingCopy} }
+
+
+=item wc_subdir ()
+
+Return path to the subdirectory inside of a working copy. Must be called
+on a repository instance.
+
+=cut
+
+sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
+
+
+=item wc_chdir ( SUBDIR )
+
+Change the working copy subdirectory to work within. The C<SUBDIR> is
+relative to the working copy root directory (not the current subdirectory).
+Must be called on a repository instance attached to a working copy
+and the directory must exist.
+
+=cut
+
+sub wc_chdir {
+       my ($self, $subdir) = @_;
+
+       $self->wc_path()
+               or throw Error::Simple("bare repository");
+
+       -d $self->wc_path().'/'.$subdir
+               or throw Error::Simple("subdir not found: $!");
+       # Of course we will not "hold" the subdirectory so anyone
+       # can delete it now and we will never know. But at least we tried.
+
+       $self->{opts}->{WorkingSubdir} = $subdir;
+}
+
+
+=item hash_object ( TYPE, FILENAME )
+
+=item hash_object ( TYPE, FILEHANDLE )
 
 Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
-C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>
-(default), C<commit>, C<tree>).
+C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>,
+C<commit>, C<tree>).
 
 In case of C<FILEHANDLE> passed instead of file name, all the data
 available are read and hashed, and the filehandle is automatically
@@ -534,14 +654,39 @@ sub _check_valid_cmd {
 # Common backend for the pipe creators.
 sub _command_common_pipe {
        my $direction = shift;
-       my ($self, $cmd, @args) = _maybe_self(@_);
+       my ($self, @p) = _maybe_self(@_);
+       my (%opts, $cmd, @args);
+       if (ref $p[0]) {
+               ($cmd, @args) = @{shift @p};
+               %opts = ref $p[0] ? %{$p[0]} : @p;
+       } else {
+               ($cmd, @args) = @p;
+       }
        _check_valid_cmd($cmd);
 
-       my $pid = open(my $fh, $direction);
-       if (not defined $pid) {
-               throw Error::Simple("open failed: $!");
-       } elsif ($pid == 0) {
-               _cmd_exec($self, $cmd, @args);
+       my $fh;
+       if ($^O eq '##INSERT_ACTIVESTATE_STRING_HERE##') {
+               # ActiveState Perl
+               #defined $opts{STDERR} and
+               #       warn 'ignoring STDERR option - running w/ ActiveState';
+               $direction eq '-|' or
+                       die 'input pipe for ActiveState not implemented';
+               tie ($fh, 'Git::activestate_pipe', $cmd, @args);
+
+       } else {
+               my $pid = open($fh, $direction);
+               if (not defined $pid) {
+                       throw Error::Simple("open failed: $!");
+               } elsif ($pid == 0) {
+                       if (defined $opts{STDERR}) {
+                               close STDERR;
+                       }
+                       if ($opts{STDERR}) {
+                               open (STDERR, '>&', $opts{STDERR})
+                                       or die "dup failed: $!";
+                       }
+                       _cmd_exec($self, $cmd, @args);
+               }
        }
        return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
 }
@@ -551,8 +696,9 @@ sub _command_common_pipe {
 sub _cmd_exec {
        my ($self, @args) = @_;
        if ($self) {
-               $self->{opts}->{Repository} and $ENV{'GIT_DIR'} = $self->{opts}->{Repository};
-               $self->{opts}->{WorkingCopy} and chdir($self->{opts}->{WorkingCopy});
+               $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
+               $self->wc_path() and chdir($self->wc_path());
+               $self->wc_subdir() and chdir($self->wc_subdir());
        }
        _execv_git_cmd(@args);
        die "exec failed: $!";
@@ -615,4 +761,39 @@ sub AUTOLOAD {
 sub DESTROY { }
 
 
+# Pipe implementation for ActiveState Perl.
+
+package Git::activestate_pipe;
+use strict;
+
+sub TIEHANDLE {
+       my ($class, @params) = @_;
+       # FIXME: This is probably horrible idea and the thing will explode
+       # at the moment you give it arguments that require some quoting,
+       # but I have no ActiveState clue... --pasky
+       my $cmdline = join " ", @params;
+       my @data = qx{$cmdline};
+       bless { i => 0, data => \@data }, $class;
+}
+
+sub READLINE {
+       my $self = shift;
+       if ($self->{i} >= scalar @{$self->{data}}) {
+               return undef;
+       }
+       return $self->{'data'}->[ $self->{i}++ ];
+}
+
+sub CLOSE {
+       my $self = shift;
+       delete $self->{data};
+       delete $self->{i};
+}
+
+sub EOF {
+       my $self = shift;
+       return ($self->{i} >= scalar @{$self->{data}});
+}
+
+
 1; # Famous last words