git@vger.kernel.org mailing list mirror (one of many)
 help / color / mirror / code / Atom feed
* [PATCH 01/12] Introduce Git.pm (v4)
@ 2006-06-24  2:34 Petr Baudis
  2006-06-24  2:34 ` [PATCH 02/12] Git.pm: Implement Git::exec_path() Petr Baudis
                   ` (11 more replies)
  0 siblings, 12 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

This patch introduces a very basic and barebone Git.pm module
with a sketch of how the generic interface would look like;
most functions are missing, but this should give some good base.
I will continue expanding it.

Most desirable now is more careful error reporting, generic_in() for feeding
input to Git commands and the repository() constructor doing some poking
with git-rev-parse to get the git directory and subdirectory prefix.
Those three are basically the prerequisities for converting git-mv.
I will send them as follow-ups to this patch.

Currently Git.pm just wraps up exec()s of Git commands, but even that
is not trivial to get right and various Git perl scripts do it in
various inconsistent ways. In addition to Git.pm, there is now also
Git.xs which provides barebone Git.xs for directly interfacing with
libgit.a, and as an example providing the hash_object() function using
libgit.

This adds the Git module, integrates it to the build system and as
an example converts the git-fmt-merge-msg.perl script to it (the result
is not very impressive since its advantage is not quite apparent in this
one, but I just picked up the simplest Git user around).

Compared to v3, only very minor things were fixed in this patch (some
whitespaces, a missing export, tiny bug in git-fmt-merge-msg.perl);
at first I wanted to post them as a separate patch but since this
is still only in pu, I decided that it will be cleaner to just resend
the patch.

My current working state is available all the time at

	http://pasky.or.cz/~xpasky/git-perl/Git.pm

and an irregularily updated API documentation is at

	http://pasky.or.cz/~xpasky/git-perl/Git.html

Many thanks to Jakub Narebski, Junio and others for their feedback.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 Makefile               |   12 +
 git-fmt-merge-msg.perl |   13 +-
 perl/.gitignore        |    7 +
 perl/Git.pm            |  408 ++++++++++++++++++++++++++++++++++++++++++++++++
 perl/Git.xs            |   64 ++++++++
 perl/Makefile.PL       |   21 ++
 6 files changed, 516 insertions(+), 9 deletions(-)

diff --git a/Makefile b/Makefile
index a5b6784..4d20b22 100644
--- a/Makefile
+++ b/Makefile
@@ -476,7 +476,8 @@ ### Build rules
 
 all: $(ALL_PROGRAMS) $(BUILT_INS) git$X gitk
 
-all:
+all: perl/Makefile
+	$(MAKE) -C perl
 	$(MAKE) -C templates
 
 strip: $(PROGRAMS) git$X
@@ -508,7 +509,7 @@ common-cmds.h: Documentation/git-*.txt
 
 $(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
 	rm -f $@ $@+
-	sed -e '1s|#!.*perl|#!$(PERL_PATH_SQ)|' \
+	sed -e '1s|#!.*perl\(.*\)|#!$(PERL_PATH_SQ)\1 -I'"$$(make -s -C perl instlibdir)"'|' \
 	    -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
 	    $@.perl >$@+
 	chmod +x $@+
@@ -594,6 +595,9 @@ XDIFF_OBJS=xdiff/xdiffi.o xdiff/xprepare
 	rm -f $@ && $(AR) rcs $@ $(XDIFF_OBJS)
 
 
+perl/Makefile:	perl/Git.pm perl/Makefile.PL
+	(cd perl && $(PERL_PATH) Makefile.PL PREFIX="$(prefix)" DEFINE="$(ALL_CFLAGS)" LIBS="$(LIBS)")
+
 doc:
 	$(MAKE) -C Documentation all
 
@@ -649,6 +653,7 @@ install: all
 	$(INSTALL) $(ALL_PROGRAMS) '$(DESTDIR_SQ)$(gitexecdir_SQ)'
 	$(INSTALL) git$X gitk '$(DESTDIR_SQ)$(bindir_SQ)'
 	$(MAKE) -C templates install
+	$(MAKE) -C perl install
 	$(INSTALL) -d -m755 '$(DESTDIR_SQ)$(GIT_PYTHON_DIR_SQ)'
 	$(INSTALL) $(PYMODULES) '$(DESTDIR_SQ)$(GIT_PYTHON_DIR_SQ)'
 	if test 'z$(bindir_SQ)' != 'z$(gitexecdir_SQ)'; \
@@ -716,7 +721,8 @@ clean:
 	rm -f $(GIT_TARNAME).tar.gz git-core_$(GIT_VERSION)-*.tar.gz
 	rm -f $(htmldocs).tar.gz $(manpages).tar.gz
 	$(MAKE) -C Documentation/ clean
-	$(MAKE) -C templates clean
+	[ ! -e perl/Makefile ] || $(MAKE) -C perl/ clean
+	$(MAKE) -C templates/ clean
 	$(MAKE) -C t/ clean
 	rm -f GIT-VERSION-FILE GIT-CFLAGS
 
diff --git a/git-fmt-merge-msg.perl b/git-fmt-merge-msg.perl
index 5986e54..be2a48c 100755
--- a/git-fmt-merge-msg.perl
+++ b/git-fmt-merge-msg.perl
@@ -6,6 +6,9 @@ # Read .git/FETCH_HEAD and make a human 
 # by grouping branches and tags together to form a single line.
 
 use strict;
+use Git;
+
+my $repo = Git->repository();
 
 my @src;
 my %src;
@@ -28,13 +31,12 @@ sub andjoin {
 }
 
 sub repoconfig {
-	my ($val) = qx{git-repo-config --get merge.summary};
+	my ($val) = $repo->command_oneline('repo-config', '--get', 'merge.summary');
 	return $val;
 }
 
 sub current_branch {
-	my ($bra) = qx{git-symbolic-ref HEAD};
-	chomp($bra);
+	my ($bra) = $repo->command_oneline('symbolic-ref', 'HEAD');
 	$bra =~ s|^refs/heads/||;
 	if ($bra ne 'master') {
 		$bra = " into $bra";
@@ -47,11 +49,10 @@ sub current_branch {
 sub shortlog {
 	my ($tip) = @_;
 	my @result;
-	foreach ( qx{git-log --no-merges --topo-order --pretty=oneline $tip ^HEAD} ) {
+	foreach ($repo->command('log', '--no-merges', '--topo-order', '--pretty=oneline', $tip, '^HEAD')) {
 		s/^[0-9a-f]{40}\s+//;
 		push @result, $_;
 	}
-	die "git-log failed\n" if $?;
 	return @result;
 }
 
@@ -168,6 +169,6 @@ for (@origin) {
 			print "  ...\n";
 			last;
 		}
-		print "  $log";
+		print "  $log\n";
 	}
 }
diff --git a/perl/.gitignore b/perl/.gitignore
new file mode 100644
index 0000000..6d778f3
--- /dev/null
+++ b/perl/.gitignore
@@ -0,0 +1,7 @@
+Git.bs
+Git.c
+Makefile
+blib
+blibdirs
+pm_to_blib
+ppport.h
diff --git a/perl/Git.pm b/perl/Git.pm
new file mode 100644
index 0000000..8fff785
--- /dev/null
+++ b/perl/Git.pm
@@ -0,0 +1,408 @@
+=head1 NAME
+
+Git - Perl interface to the Git version control system
+
+=cut
+
+
+package Git;
+
+use strict;
+
+
+BEGIN {
+
+our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
+
+# Totally unstable API.
+$VERSION = '0.01';
+
+
+=head1 SYNOPSIS
+
+  use Git;
+
+  my $version = Git::command_oneline('version');
+
+  Git::command_noisy('update-server-info');
+
+  my $repo = Git->repository (Directory => '/srv/git/cogito.git');
+
+
+  my @revs = $repo->command('rev-list', '--since=last monday', '--all');
+
+  my $fh = $repo->command_pipe('rev-list', '--since=last monday', '--all');
+  my $lastrev = <$fh>; chomp $lastrev;
+  close $fh; # You may want to test rev-list exit status here
+
+  my $lastrev = $repo->command_oneline('rev-list', '--all');
+
+=cut
+
+
+require Exporter;
+
+@ISA = qw(Exporter);
+
+@EXPORT = qw();
+
+# Methods which can be called as standalone functions as well:
+@EXPORT_OK = qw(command command_oneline command_pipe command_noisy
+                hash_object);
+
+
+=head1 DESCRIPTION
+
+This module provides Perl scripts easy way to interface the Git version control
+system. The modules have an easy and well-tested way to call arbitrary Git
+commands; in the future, the interface will also provide specialized methods
+for doing easily operations which are not totally trivial to do over
+the generic command interface.
+
+While some commands can be executed outside of any context (e.g. 'version'
+or 'init-db'), most operations require a repository context, which in practice
+means getting an instance of the Git object using the repository() constructor.
+(In the future, we will also get a new_repository() constructor.) All commands
+called as methods of the object are then executed in the context of the
+repository.
+
+TODO: In the future, we might also do
+
+	my $subdir = $repo->subdir('Documentation');
+	# Gets called in the subdirectory context:
+	$subdir->command('status');
+
+	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
+increate nonwithstanding).
+
+=cut
+
+
+use Carp qw(carp croak);
+
+require XSLoader;
+XSLoader::load('Git', $VERSION);
+
+}
+
+
+=head1 CONSTRUCTORS
+
+=over 4
+
+=item repository ( OPTIONS )
+
+=item repository ( DIRECTORY )
+
+=item repository ()
+
+Construct a new repository object.
+C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
+Possible options are:
+
+B<Repository> - Path to the Git repository.
+
+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<GitPath> - Path to the C<git> binary executable. By default the C<$PATH>
+is searched for it.
+
+You should not use both C<Directory> and either of C<Repository> and
+C<WorkingCopy> - the results of that are undefined.
+
+Alternatively, a directory path may be passed as a single scalar argument
+to the constructor; it is equivalent to setting only the C<Directory> option
+field.
+
+Calling the constructor with no options whatsoever is equivalent to
+calling it with C<< Directory => '.' >>.
+
+=cut
+
+sub repository {
+	my $class = shift;
+	my @args = @_;
+	my %opts = ();
+	my $self;
+
+	if (defined $args[0]) {
+		if ($#args % 2 != 1) {
+			# Not a hash.
+			$#args == 0 or croak "bad usage";
+			%opts = (Directory => $args[0]);
+		} else {
+			%opts = @args;
+		}
+
+		if ($opts{Directory}) {
+			-d $opts{Directory} or croak "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};
+			}
+			delete $opts{Directory};
+		}
+	}
+
+	$self = { opts => \%opts };
+	bless $self, $class;
+}
+
+
+=back
+
+=head1 METHODS
+
+=over 4
+
+=item command ( COMMAND [, ARGUMENTS... ] )
+
+Execute the given Git C<COMMAND> (specify it without the 'git-'
+prefix), optionally with the specified extra C<ARGUMENTS>.
+
+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).
+
+In scalar context, it returns all the command output in a single string
+(verbatim).
+
+In array context, it returns an array containing lines printed to the
+command's stdout (without trailing newlines).
+
+In both cases, the command's stdin and stderr are the same as the caller's.
+
+=cut
+
+sub command {
+	my $fh = command_pipe(@_);
+
+	if (not defined wantarray) {
+		_cmd_close($fh);
+
+	} elsif (not wantarray) {
+		local $/;
+		my $text = <$fh>;
+		_cmd_close($fh);
+		return $text;
+
+	} else {
+		my @lines = <$fh>;
+		_cmd_close($fh);
+		chomp @lines;
+		return @lines;
+	}
+}
+
+
+=item command_oneline ( COMMAND [, ARGUMENTS... ] )
+
+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.
+
+=cut
+
+sub command_oneline {
+	my $fh = command_pipe(@_);
+
+	my $line = <$fh>;
+	_cmd_close($fh);
+
+	chomp $line;
+	return $line;
+}
+
+
+=item command_pipe ( COMMAND [, ARGUMENTS... ] )
+
+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.
+
+=cut
+
+sub command_pipe {
+	my ($self, $cmd, @args) = _maybe_self(@_);
+
+	$cmd =~ /^[a-z0-9A-Z_-]+$/ or croak "bad command: $cmd";
+
+	my $pid = open(my $fh, "-|");
+	if (not defined $pid) {
+		croak "open failed: $!";
+	} elsif ($pid == 0) {
+		_cmd_exec($self, $cmd, @args);
+	}
+	return $fh;
+}
+
+
+=item command_noisy ( COMMAND [, ARGUMENTS... ] )
+
+Execute the given C<COMMAND> in the same way as command() does but do not
+capture the command output - the standard output is not redirected and goes
+to the standard output of the caller application.
+
+While the method is called command_noisy(), you might want to as well use
+it for the most silent Git commands which you know will never pollute your
+stdout but you want to avoid the overhead of the pipe setup when calling them.
+
+The function returns only after the command has finished running.
+
+=cut
+
+sub command_noisy {
+	my ($self, $cmd, @args) = _maybe_self(@_);
+
+	$cmd =~ /^[a-z0-9A-Z_-]+$/ or croak "bad command: $cmd";
+
+	my $pid = fork;
+	if (not defined $pid) {
+		croak "fork failed: $!";
+	} elsif ($pid == 0) {
+		_cmd_exec($self, $cmd, @args);
+	}
+	if (waitpid($pid, 0) > 0 and $? != 0) {
+		croak "exit status: $?";
+	}
+}
+
+
+=item hash_object ( FILENAME [, TYPE ] )
+
+=item hash_object ( FILEHANDLE [, TYPE ] )
+
+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>).
+
+In case of C<FILEHANDLE> passed instead of file name, all the data
+available are read and hashed, and the filehandle is automatically
+closed. The file handle should be freshly opened - if you have already
+read anything from the file handle, the results are undefined (since
+this function works directly with the file descriptor and internal
+PerlIO buffering might have messed things up).
+
+The method can be called without any instance or on a specified Git repository,
+it makes zero difference.
+
+The function returns the SHA1 hash.
+
+Implementation of this function is very fast; no external command calls
+are involved.
+
+=cut
+
+# Implemented in Git.xs.
+
+
+=back
+
+=head1 TODO
+
+This is still fairly crude.
+We need some good way to report errors back except just dying.
+
+=head1 COPYRIGHT
+
+Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
+
+This module is free software; it may be used, copied, modified
+and distributed under the terms of the GNU General Public Licence,
+either version 2, or (at your option) any later version.
+
+=cut
+
+
+# Take raw method argument list and return ($obj, @args) in case
+# the method was called upon an instance and (undef, @args) if
+# it was called directly.
+sub _maybe_self {
+	# This breaks inheritance. Oh well.
+	ref $_[0] eq 'Git' ? @_ : (undef, @_);
+}
+
+# When already in the subprocess, set up the appropriate state
+# for the given repository and execute the git command.
+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});
+	}
+	my $git = $self->{opts}->{GitPath};
+	$git ||= 'git';
+	exec ($git, @args) or croak "exec failed: $!";
+}
+
+# Close pipe to a subprocess.
+sub _cmd_close {
+	my ($fh) = @_;
+	if (not close $fh) {
+		if ($!) {
+			# It's just close, no point in fatalities
+			carp "error closing pipe: $!";
+		} elsif ($? >> 8) {
+			croak "exit status: ".($? >> 8);
+		}
+		# else we might e.g. closed a live stream; the command
+		# dying of SIGPIPE would drive us here.
+	}
+}
+
+
+# Trickery for .xs routines: In order to avoid having some horrid
+# C code trying to do stuff with undefs and hashes, we gate all
+# xs calls through the following and in case we are being ran upon
+# an instance call a C part of the gate which will set up the
+# environment properly.
+sub _call_gate {
+	my $xsfunc = shift;
+	my ($self, @args) = _maybe_self(@_);
+
+	if (defined $self) {
+		# XXX: We ignore the WorkingCopy! To properly support
+		# that will require heavy changes in libgit.
+
+		# XXX: And we ignore everything else as well. libgit
+		# at least needs to be extended to let us specify
+		# the $GIT_DIR instead of looking it up in environment.
+		#xs_call_gate($self->{opts}->{Repository});
+	}
+
+	&$xsfunc(@args);
+}
+
+sub AUTOLOAD {
+	my $xsname;
+	our $AUTOLOAD;
+	($xsname = $AUTOLOAD) =~ s/.*:://;
+	croak "&Git::$xsname not defined" if $xsname =~ /^xs_/;
+	$xsname = 'xs_'.$xsname;
+	_call_gate(\&$xsname, @_);
+}
+
+sub DESTROY { }
+
+
+1; # Famous last words
diff --git a/perl/Git.xs b/perl/Git.xs
new file mode 100644
index 0000000..9885e2c
--- /dev/null
+++ b/perl/Git.xs
@@ -0,0 +1,64 @@
+/* By carefully stacking #includes here (even if WE don't really need them)
+ * we strive to make the thing actually compile. Git header files aren't very
+ * nice. Perl headers are one of the signs of the coming apocalypse. */
+#include <ctype.h>
+/* Ok, it hasn't been so bad so far. */
+
+/* libgit interface */
+#include "../cache.h"
+
+/* XS and Perl interface */
+#include "EXTERN.h"
+#include "perl.h"
+#include "XSUB.h"
+
+#include "ppport.h"
+
+
+MODULE = Git		PACKAGE = Git		
+
+PROTOTYPES: DISABLE
+
+# /* TODO: xs_call_gate(). See Git.pm. */
+
+char *
+xs_hash_object(file, type = "blob")
+	SV *file;
+	char *type;
+CODE:
+{
+	unsigned char sha1[20];
+
+	if (SvTYPE(file) == SVt_RV)
+		file = SvRV(file);
+
+	if (SvTYPE(file) == SVt_PVGV) {
+		/* Filehandle */
+		PerlIO *pio;
+
+		pio = IoIFP(sv_2io(file));
+		if (!pio)
+			croak("You passed me something weird - a dir glob?");
+		/* XXX: I just hope PerlIO didn't read anything from it yet.
+		 * --pasky */
+		if (index_pipe(sha1, PerlIO_fileno(pio), type, 0))
+			croak("Unable to hash given filehandle");
+		/* Avoid any nasty surprises. */
+		PerlIO_close(pio);
+
+	} else {
+		/* String */
+		char *path = SvPV_nolen(file);
+		int fd = open(path, O_RDONLY);
+		struct stat st;
+
+		if (fd < 0 ||
+		    fstat(fd, &st) < 0 ||
+		    index_fd(sha1, fd, &st, 0, type))
+			croak("Unable to hash %s", path);
+		close(fd);
+	}
+	RETVAL = sha1_to_hex(sha1);
+}
+OUTPUT:
+	RETVAL
diff --git a/perl/Makefile.PL b/perl/Makefile.PL
new file mode 100644
index 0000000..dd61056
--- /dev/null
+++ b/perl/Makefile.PL
@@ -0,0 +1,21 @@
+use ExtUtils::MakeMaker;
+
+sub MY::postamble {
+	return <<'MAKE_FRAG';
+instlibdir:
+	@echo $(INSTALLSITELIB)
+
+MAKE_FRAG
+}
+
+WriteMakefile(
+	NAME            => 'Git',
+	VERSION_FROM    => 'Git.pm',
+	MYEXTLIB        => '../libgit.a',
+	INC             => '-I. -I..',
+);
+
+
+use Devel::PPPort;
+
+-s 'ppport.h' or Devel::PPPort::WriteFile();

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 02/12] Git.pm: Implement Git::exec_path()
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 03/12] Git.pm: Call external commands using execv_git_cmd() Petr Baudis
                   ` (10 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

This patch implements Git::exec_path() (as a direct XS call).

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |   15 ++++++++++++++-
 perl/Git.xs |   12 ++++++++++++
 2 files changed, 26 insertions(+), 1 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index 8fff785..5c5ae12 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -48,7 +48,7 @@ require Exporter;
 
 # Methods which can be called as standalone functions as well:
 @EXPORT_OK = qw(command command_oneline command_pipe command_noisy
-                hash_object);
+                exec_path hash_object);
 
 
 =head1 DESCRIPTION
@@ -288,6 +288,19 @@ sub command_noisy {
 }
 
 
+=item exec_path ()
+
+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
+are involved.
+
+=cut
+
+# Implemented in Git.xs.
+
+
 =item hash_object ( FILENAME [, TYPE ] )
 
 =item hash_object ( FILEHANDLE [, TYPE ] )
diff --git a/perl/Git.xs b/perl/Git.xs
index 9885e2c..b6f6d13 100644
--- a/perl/Git.xs
+++ b/perl/Git.xs
@@ -6,6 +6,7 @@ #include <ctype.h>
 
 /* libgit interface */
 #include "../cache.h"
+#include "../exec_cmd.h"
 
 /* XS and Perl interface */
 #include "EXTERN.h"
@@ -21,6 +22,17 @@ PROTOTYPES: DISABLE
 
 # /* TODO: xs_call_gate(). See Git.pm. */
 
+
+const char *
+xs_exec_path()
+CODE:
+{
+	RETVAL = git_exec_path();
+}
+OUTPUT:
+	RETVAL
+
+
 char *
 xs_hash_object(file, type = "blob")
 	SV *file;

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 03/12] Git.pm: Call external commands using execv_git_cmd()
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
  2006-06-24  2:34 ` [PATCH 02/12] Git.pm: Implement Git::exec_path() Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 04/12] Git.pm: Implement Git::version() Petr Baudis
                   ` (9 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Instead of explicitly using the git wrapper to call external commands,
use the execv_git_cmd() function which will directly call whatever
needs to be called. GitBin option becomes useless so drop it.

This actually means the exec_path() thing I planned to use worthless
internally, but Jakub wants it in anyway and I don't mind, so...

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |   12 ++++++------
 perl/Git.xs |   22 ++++++++++++++++++++++
 2 files changed, 28 insertions(+), 6 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index 5c5ae12..212337e 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -122,9 +122,6 @@ to the subdirectory and the directory is
 If the directory does not have the subdirectory, C<WorkingCopy> is left
 undefined and C<Repository> is pointed to the directory itself.
 
-B<GitPath> - Path to the C<git> binary executable. By default the C<$PATH>
-is searched for it.
-
 You should not use both C<Directory> and either of C<Repository> and
 C<WorkingCopy> - the results of that are undefined.
 
@@ -363,11 +360,14 @@ sub _cmd_exec {
 		$self->{opts}->{Repository} and $ENV{'GIT_DIR'} = $self->{opts}->{Repository};
 		$self->{opts}->{WorkingCopy} and chdir($self->{opts}->{WorkingCopy});
 	}
-	my $git = $self->{opts}->{GitPath};
-	$git ||= 'git';
-	exec ($git, @args) or croak "exec failed: $!";
+	xs__execv_git_cmd(@args);
+	croak "exec failed: $!";
 }
 
+# Execute the given Git command ($_[0]) with arguments ($_[1..])
+# by searching for it at proper places.
+# _execv_git_cmd(), implemented in Git.xs.
+
 # Close pipe to a subprocess.
 sub _cmd_close {
 	my ($fh) = @_;
diff --git a/perl/Git.xs b/perl/Git.xs
index b6f6d13..c8220e2 100644
--- a/perl/Git.xs
+++ b/perl/Git.xs
@@ -33,6 +33,28 @@ OUTPUT:
 	RETVAL
 
 
+void
+xs__execv_git_cmd(...)
+CODE:
+{
+	const char **argv;
+	int i;
+
+	argv = malloc(sizeof(const char *) * (items + 1));
+	if (!argv)
+		croak("malloc failed");
+	for (i = 0; i < items; i++)
+		argv[i] = strdup(SvPV_nolen(ST(i)));
+	argv[i] = NULL;
+
+	execv_git_cmd(argv);
+
+	for (i = 0; i < items; i++)
+		if (argv[i])
+			free((char *) argv[i]);
+	free((char **) argv);
+}
+
 char *
 xs_hash_object(file, type = "blob")
 	SV *file;

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 04/12] Git.pm: Implement Git::version()
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
  2006-06-24  2:34 ` [PATCH 02/12] Git.pm: Implement Git::exec_path() Petr Baudis
  2006-06-24  2:34 ` [PATCH 03/12] Git.pm: Call external commands using execv_git_cmd() Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 05/12] Customizable error handlers Petr Baudis
                   ` (8 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Git::version() returns the Git version string.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 Makefile    |    5 ++++-
 perl/Git.pm |   14 +++++++++++++-
 perl/Git.xs |   10 ++++++++++
 3 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/Makefile b/Makefile
index 4d20b22..7842195 100644
--- a/Makefile
+++ b/Makefile
@@ -596,7 +596,10 @@ XDIFF_OBJS=xdiff/xdiffi.o xdiff/xprepare
 
 
 perl/Makefile:	perl/Git.pm perl/Makefile.PL
-	(cd perl && $(PERL_PATH) Makefile.PL PREFIX="$(prefix)" DEFINE="$(ALL_CFLAGS)" LIBS="$(LIBS)")
+	(cd perl && $(PERL_PATH) Makefile.PL \
+		PREFIX="$(prefix)" \
+		DEFINE="$(ALL_CFLAGS) -DGIT_VERSION=\\\"$(GIT_VERSION)\\\"" \
+		LIBS="$(LIBS)")
 
 doc:
 	$(MAKE) -C Documentation all
diff --git a/perl/Git.pm b/perl/Git.pm
index 212337e..dcd769b 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -48,7 +48,7 @@ require Exporter;
 
 # Methods which can be called as standalone functions as well:
 @EXPORT_OK = qw(command command_oneline command_pipe command_noisy
-                exec_path hash_object);
+                version exec_path hash_object);
 
 
 =head1 DESCRIPTION
@@ -285,6 +285,18 @@ sub command_noisy {
 }
 
 
+=item version ()
+
+Return the Git version in use.
+
+Implementation of this function is very fast; no external command calls
+are involved.
+
+=cut
+
+# Implemented in Git.xs.
+
+
 =item exec_path ()
 
 Return path to the git sub-command executables (the same as
diff --git a/perl/Git.xs b/perl/Git.xs
index c8220e2..9623fdd 100644
--- a/perl/Git.xs
+++ b/perl/Git.xs
@@ -24,6 +24,16 @@ # /* TODO: xs_call_gate(). See Git.pm. *
 
 
 const char *
+xs_version()
+CODE:
+{
+	RETVAL = GIT_VERSION;
+}
+OUTPUT:
+	RETVAL
+
+
+const char *
 xs_exec_path()
 CODE:
 {

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 05/12] Customizable error handlers
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (2 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 04/12] Git.pm: Implement Git::version() Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 06/12] Add Error.pm to the distribution Petr Baudis
                   ` (7 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

This patch makes the usage(), die() and error() handlers customizable.
Nothing in the git code itself uses that but many other libgit users
(like Git.pm) will.

This is implemented using the mutator functions primarily because you
cannot directly modifying global variables of libgit from a program that
dlopen()ed it, apparently. But having functions for that is a better API
anyway.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 git-compat-util.h |    4 ++++
 usage.c           |   46 ++++++++++++++++++++++++++++++++++++++++++----
 2 files changed, 46 insertions(+), 4 deletions(-)

diff --git a/git-compat-util.h b/git-compat-util.h
index 5d543d2..b3d4cf5 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -40,6 +40,10 @@ extern void usage(const char *err) NORET
 extern void die(const char *err, ...) NORETURN __attribute__((format (printf, 1, 2)));
 extern int error(const char *err, ...) __attribute__((format (printf, 1, 2)));
 
+extern void set_usage_routine(void (*routine)(const char *err) NORETURN);
+extern void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN);
+extern void set_error_routine(void (*routine)(const char *err, va_list params));
+
 #ifdef NO_MMAP
 
 #ifndef PROT_READ
diff --git a/usage.c b/usage.c
index 1fa924c..b781b00 100644
--- a/usage.c
+++ b/usage.c
@@ -12,20 +12,58 @@ static void report(const char *prefix, c
 	fputs("\n", stderr);
 }
 
-void usage(const char *err)
+void usage_builtin(const char *err)
 {
 	fprintf(stderr, "usage: %s\n", err);
 	exit(129);
 }
 
+void die_builtin(const char *err, va_list params)
+{
+	report("fatal: ", err, params);
+	exit(128);
+}
+
+void error_builtin(const char *err, va_list params)
+{
+	report("error: ", err, params);
+}
+
+
+/* If we are in a dlopen()ed .so write to a global variable would segfault
+ * (ugh), so keep things static. */
+static void (*usage_routine)(const char *err) NORETURN = usage_builtin;
+static void (*die_routine)(const char *err, va_list params) NORETURN = die_builtin;
+static void (*error_routine)(const char *err, va_list params) = error_builtin;
+
+void set_usage_routine(void (*routine)(const char *err) NORETURN)
+{
+	usage_routine = routine;
+}
+
+void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN)
+{
+	die_routine = routine;
+}
+
+void set_error_routine(void (*routine)(const char *err, va_list params))
+{
+	error_routine = routine;
+}
+
+
+void usage(const char *err)
+{
+	usage_routine(err);
+}
+
 void die(const char *err, ...)
 {
 	va_list params;
 
 	va_start(params, err);
-	report("fatal: ", err, params);
+	die_routine(err, params);
 	va_end(params);
-	exit(128);
 }
 
 int error(const char *err, ...)
@@ -33,7 +71,7 @@ int error(const char *err, ...)
 	va_list params;
 
 	va_start(params, err);
-	report("error: ", err, params);
+	error_routine(err, params);
 	va_end(params);
 	return -1;
 }

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 06/12] Add Error.pm to the distribution
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (3 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 05/12] Customizable error handlers Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 07/12] Git.pm: Better error handling Petr Baudis
                   ` (6 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

I have been thinking about how to do the error reporting the best
way and after scraping various overcomplicated concepts, I have
decided that by far the most elegant way is to throw Error exceptions;
the closest sane alternative is to catch the dies in Git.pm by
enclosing the calls in eval{}s and that's really _quite_ ugly.

The only "small" trouble is that Error.pm turns out sadly not to be
part of the standard distribution, and installation from CPAN is
a bother, especially if you can't install it system-wide. But since
it is very small, I've decided to just bundle it.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Error.pm    |  821 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 perl/Makefile.PL |   10 +
 2 files changed, 831 insertions(+), 0 deletions(-)

diff --git a/perl/Error.pm b/perl/Error.pm
new file mode 100644
index 0000000..17ad70a
--- /dev/null
+++ b/perl/Error.pm
@@ -0,0 +1,821 @@
+# Error.pm
+#
+# Copyright (c) 1997-8 Graham Barr <gbarr@ti.com>. All rights reserved.
+# This program is free software; you can redistribute it and/or
+# modify it under the same terms as Perl itself.
+#
+# Based on my original Error.pm, and Exceptions.pm by Peter Seibel
+# <peter@weblogic.com> and adapted by Jesse Glick <jglick@sig.bsh.com>.
+#
+# but modified ***significantly***
+
+package Error;
+
+use strict;
+use vars qw($VERSION);
+use 5.004;
+
+$VERSION = "0.15009"; 
+
+use overload (
+	'""'	   =>	'stringify',
+	'0+'	   =>	'value',
+	'bool'     =>	sub { return 1; },
+	'fallback' =>	1
+);
+
+$Error::Depth = 0;	# Depth to pass to caller()
+$Error::Debug = 0;	# Generate verbose stack traces
+@Error::STACK = ();	# Clause stack for try
+$Error::THROWN = undef;	# last error thrown, a workaround until die $ref works
+
+my $LAST;		# Last error created
+my %ERROR;		# Last error associated with package
+
+sub throw_Error_Simple
+{
+    my $args = shift;
+    return Error::Simple->new($args->{'text'});
+}
+
+$Error::ObjectifyCallback = \&throw_Error_Simple;
+
+
+# Exported subs are defined in Error::subs
+
+use Scalar::Util ();
+
+sub import {
+    shift;
+    local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
+    Error::subs->import(@_);
+}
+
+# I really want to use last for the name of this method, but it is a keyword
+# which prevent the syntax  last Error
+
+sub prior {
+    shift; # ignore
+
+    return $LAST unless @_;
+
+    my $pkg = shift;
+    return exists $ERROR{$pkg} ? $ERROR{$pkg} : undef
+	unless ref($pkg);
+
+    my $obj = $pkg;
+    my $err = undef;
+    if($obj->isa('HASH')) {
+	$err = $obj->{'__Error__'}
+	    if exists $obj->{'__Error__'};
+    }
+    elsif($obj->isa('GLOB')) {
+	$err = ${*$obj}{'__Error__'}
+	    if exists ${*$obj}{'__Error__'};
+    }
+
+    $err;
+}
+
+sub flush {
+    shift; #ignore
+    
+    unless (@_) {
+       $LAST = undef;
+       return;
+    }
+    
+    my $pkg = shift;
+    return unless ref($pkg);
+   
+    undef $ERROR{$pkg} if defined $ERROR{$pkg}; 
+} 
+
+# Return as much information as possible about where the error
+# happened. The -stacktrace element only exists if $Error::DEBUG
+# was set when the error was created
+
+sub stacktrace {
+    my $self = shift;
+
+    return $self->{'-stacktrace'}
+	if exists $self->{'-stacktrace'};
+
+    my $text = exists $self->{'-text'} ? $self->{'-text'} : "Died";
+
+    $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
+	unless($text =~ /\n$/s);
+
+    $text;
+}
+
+# Allow error propagation, ie
+#
+# $ber->encode(...) or
+#    return Error->prior($ber)->associate($ldap);
+
+sub associate {
+    my $err = shift;
+    my $obj = shift;
+
+    return unless ref($obj);
+
+    if($obj->isa('HASH')) {
+	$obj->{'__Error__'} = $err;
+    }
+    elsif($obj->isa('GLOB')) {
+	${*$obj}{'__Error__'} = $err;
+    }
+    $obj = ref($obj);
+    $ERROR{ ref($obj) } = $err;
+
+    return;
+}
+
+sub new {
+    my $self = shift;
+    my($pkg,$file,$line) = caller($Error::Depth);
+
+    my $err = bless {
+	'-package' => $pkg,
+	'-file'    => $file,
+	'-line'    => $line,
+	@_
+    }, $self;
+
+    $err->associate($err->{'-object'})
+	if(exists $err->{'-object'});
+
+    # To always create a stacktrace would be very inefficient, so
+    # we only do it if $Error::Debug is set
+
+    if($Error::Debug) {
+	require Carp;
+	local $Carp::CarpLevel = $Error::Depth;
+	my $text = defined($err->{'-text'}) ? $err->{'-text'} : "Error";
+	my $trace = Carp::longmess($text);
+	# Remove try calls from the trace
+	$trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
+	$trace =~ s/(\n\s+\S+__ANON__[^\n]+)?\n\s+eval[^\n]+\n\s+Error::subs::run_clauses[^\n]+\n\s+Error::subs::try[^\n]+(?=\n)//sog;
+	$err->{'-stacktrace'} = $trace
+    }
+
+    $@ = $LAST = $ERROR{$pkg} = $err;
+}
+
+# Throw an error. this contains some very gory code.
+
+sub throw {
+    my $self = shift;
+    local $Error::Depth = $Error::Depth + 1;
+
+    # if we are not rethrow-ing then create the object to throw
+    $self = $self->new(@_) unless ref($self);
+    
+    die $Error::THROWN = $self;
+}
+
+# syntactic sugar for
+#
+#    die with Error( ... );
+
+sub with {
+    my $self = shift;
+    local $Error::Depth = $Error::Depth + 1;
+
+    $self->new(@_);
+}
+
+# syntactic sugar for
+#
+#    record Error( ... ) and return;
+
+sub record {
+    my $self = shift;
+    local $Error::Depth = $Error::Depth + 1;
+
+    $self->new(@_);
+}
+
+# catch clause for
+#
+# try { ... } catch CLASS with { ... }
+
+sub catch {
+    my $pkg = shift;
+    my $code = shift;
+    my $clauses = shift || {};
+    my $catch = $clauses->{'catch'} ||= [];
+
+    unshift @$catch,  $pkg, $code;
+
+    $clauses;
+}
+
+# Object query methods
+
+sub object {
+    my $self = shift;
+    exists $self->{'-object'} ? $self->{'-object'} : undef;
+}
+
+sub file {
+    my $self = shift;
+    exists $self->{'-file'} ? $self->{'-file'} : undef;
+}
+
+sub line {
+    my $self = shift;
+    exists $self->{'-line'} ? $self->{'-line'} : undef;
+}
+
+sub text {
+    my $self = shift;
+    exists $self->{'-text'} ? $self->{'-text'} : undef;
+}
+
+# overload methods
+
+sub stringify {
+    my $self = shift;
+    defined $self->{'-text'} ? $self->{'-text'} : "Died";
+}
+
+sub value {
+    my $self = shift;
+    exists $self->{'-value'} ? $self->{'-value'} : undef;
+}
+
+package Error::Simple;
+
+@Error::Simple::ISA = qw(Error);
+
+sub new {
+    my $self  = shift;
+    my $text  = "" . shift;
+    my $value = shift;
+    my(@args) = ();
+
+    local $Error::Depth = $Error::Depth + 1;
+
+    @args = ( -file => $1, -line => $2)
+	if($text =~ s/\s+at\s+(\S+)\s+line\s+(\d+)(?:,\s*<[^>]*>\s+line\s+\d+)?\.?\n?$//s);
+    push(@args, '-value', 0 + $value)
+	if defined($value);
+
+    $self->SUPER::new(-text => $text, @args);
+}
+
+sub stringify {
+    my $self = shift;
+    my $text = $self->SUPER::stringify;
+    $text .= sprintf(" at %s line %d.\n", $self->file, $self->line)
+	unless($text =~ /\n$/s);
+    $text;
+}
+
+##########################################################################
+##########################################################################
+
+# Inspired by code from Jesse Glick <jglick@sig.bsh.com> and
+# Peter Seibel <peter@weblogic.com>
+
+package Error::subs;
+
+use Exporter ();
+use vars qw(@EXPORT_OK @ISA %EXPORT_TAGS);
+
+@EXPORT_OK   = qw(try with finally except otherwise);
+%EXPORT_TAGS = (try => \@EXPORT_OK);
+
+@ISA = qw(Exporter);
+
+sub run_clauses ($$$\@) {
+    my($clauses,$err,$wantarray,$result) = @_;
+    my $code = undef;
+
+    $err = $Error::ObjectifyCallback->({'text' =>$err}) unless ref($err);
+
+    CATCH: {
+
+	# catch
+	my $catch;
+	if(defined($catch = $clauses->{'catch'})) {
+	    my $i = 0;
+
+	    CATCHLOOP:
+	    for( ; $i < @$catch ; $i += 2) {
+		my $pkg = $catch->[$i];
+		unless(defined $pkg) {
+		    #except
+		    splice(@$catch,$i,2,$catch->[$i+1]->());
+		    $i -= 2;
+		    next CATCHLOOP;
+		}
+		elsif(Scalar::Util::blessed($err) && $err->isa($pkg)) {
+		    $code = $catch->[$i+1];
+		    while(1) {
+			my $more = 0;
+			local($Error::THROWN);
+			my $ok = eval {
+			    if($wantarray) {
+				@{$result} = $code->($err,\$more);
+			    }
+			    elsif(defined($wantarray)) {
+			        @{$result} = ();
+				$result->[0] = $code->($err,\$more);
+			    }
+			    else {
+				$code->($err,\$more);
+			    }
+			    1;
+			};
+			if( $ok ) {
+			    next CATCHLOOP if $more;
+			    undef $err;
+			}
+			else {
+			    $err = defined($Error::THROWN)
+				    ? $Error::THROWN : $@;
+                $err = $Error::ObjectifyCallback->({'text' =>$err})
+                    unless ref($err);
+			}
+			last CATCH;
+		    };
+		}
+	    }
+	}
+
+	# otherwise
+	my $owise;
+	if(defined($owise = $clauses->{'otherwise'})) {
+	    my $code = $clauses->{'otherwise'};
+	    my $more = 0;
+	    my $ok = eval {
+		if($wantarray) {
+		    @{$result} = $code->($err,\$more);
+		}
+		elsif(defined($wantarray)) {
+		    @{$result} = ();
+		    $result->[0] = $code->($err,\$more);
+		}
+		else {
+		    $code->($err,\$more);
+		}
+		1;
+	    };
+	    if( $ok ) {
+		undef $err;
+	    }
+	    else {
+		$err = defined($Error::THROWN)
+			? $Error::THROWN : $@;
+            
+        $err = $Error::ObjectifyCallback->({'text' =>$err}) 
+            unless ref($err);
+	    }
+	}
+    }
+    $err;
+}
+
+sub try (&;$) {
+    my $try = shift;
+    my $clauses = @_ ? shift : {};
+    my $ok = 0;
+    my $err = undef;
+    my @result = ();
+
+    unshift @Error::STACK, $clauses;
+
+    my $wantarray = wantarray();
+
+    do {
+	local $Error::THROWN = undef;
+    local $@ = undef;
+
+	$ok = eval {
+	    if($wantarray) {
+		@result = $try->();
+	    }
+	    elsif(defined $wantarray) {
+		$result[0] = $try->();
+	    }
+	    else {
+		$try->();
+	    }
+	    1;
+	};
+
+	$err = defined($Error::THROWN) ? $Error::THROWN : $@
+	    unless $ok;
+    };
+
+    shift @Error::STACK;
+
+    $err = run_clauses($clauses,$err,wantarray,@result)
+	unless($ok);
+
+    $clauses->{'finally'}->()
+	if(defined($clauses->{'finally'}));
+
+    if (defined($err))
+    {
+        if (Scalar::Util::blessed($err) && $err->can('throw'))
+        {
+            throw $err;
+        }
+        else
+        {
+            die $err;
+        }
+    }
+
+    wantarray ? @result : $result[0];
+}
+
+# Each clause adds a sub to the list of clauses. The finally clause is
+# always the last, and the otherwise clause is always added just before
+# the finally clause.
+#
+# All clauses, except the finally clause, add a sub which takes one argument
+# this argument will be the error being thrown. The sub will return a code ref
+# if that clause can handle that error, otherwise undef is returned.
+#
+# The otherwise clause adds a sub which unconditionally returns the users
+# code reference, this is why it is forced to be last.
+#
+# The catch clause is defined in Error.pm, as the syntax causes it to
+# be called as a method
+
+sub with (&;$) {
+    @_
+}
+
+sub finally (&) {
+    my $code = shift;
+    my $clauses = { 'finally' => $code };
+    $clauses;
+}
+
+# The except clause is a block which returns a hashref or a list of
+# key-value pairs, where the keys are the classes and the values are subs.
+
+sub except (&;$) {
+    my $code = shift;
+    my $clauses = shift || {};
+    my $catch = $clauses->{'catch'} ||= [];
+    
+    my $sub = sub {
+	my $ref;
+	my(@array) = $code->($_[0]);
+	if(@array == 1 && ref($array[0])) {
+	    $ref = $array[0];
+	    $ref = [ %$ref ]
+		if(UNIVERSAL::isa($ref,'HASH'));
+	}
+	else {
+	    $ref = \@array;
+	}
+	@$ref
+    };
+
+    unshift @{$catch}, undef, $sub;
+
+    $clauses;
+}
+
+sub otherwise (&;$) {
+    my $code = shift;
+    my $clauses = shift || {};
+
+    if(exists $clauses->{'otherwise'}) {
+	require Carp;
+	Carp::croak("Multiple otherwise clauses");
+    }
+
+    $clauses->{'otherwise'} = $code;
+
+    $clauses;
+}
+
+1;
+__END__
+
+=head1 NAME
+
+Error - Error/exception handling in an OO-ish way
+
+=head1 SYNOPSIS
+
+    use Error qw(:try);
+
+    throw Error::Simple( "A simple error");
+
+    sub xyz {
+        ...
+	record Error::Simple("A simple error")
+	    and return;
+    }
+ 
+    unlink($file) or throw Error::Simple("$file: $!",$!);
+
+    try {
+	do_some_stuff();
+	die "error!" if $condition;
+	throw Error::Simple -text => "Oops!" if $other_condition;
+    }
+    catch Error::IO with {
+	my $E = shift;
+	print STDERR "File ", $E->{'-file'}, " had a problem\n";
+    }
+    except {
+	my $E = shift;
+	my $general_handler=sub {send_message $E->{-description}};
+	return {
+	    UserException1 => $general_handler,
+	    UserException2 => $general_handler
+	};
+    }
+    otherwise {
+	print STDERR "Well I don't know what to say\n";
+    }
+    finally {
+	close_the_garage_door_already(); # Should be reliable
+    }; # Don't forget the trailing ; or you might be surprised
+
+=head1 DESCRIPTION
+
+The C<Error> package provides two interfaces. Firstly C<Error> provides
+a procedural interface to exception handling. Secondly C<Error> is a
+base class for errors/exceptions that can either be thrown, for
+subsequent catch, or can simply be recorded.
+
+Errors in the class C<Error> should not be thrown directly, but the
+user should throw errors from a sub-class of C<Error>.
+
+=head1 PROCEDURAL INTERFACE
+
+C<Error> exports subroutines to perform exception handling. These will
+be exported if the C<:try> tag is used in the C<use> line.
+
+=over 4
+
+=item try BLOCK CLAUSES
+
+C<try> is the main subroutine called by the user. All other subroutines
+exported are clauses to the try subroutine.
+
+The BLOCK will be evaluated and, if no error is throw, try will return
+the result of the block.
+
+C<CLAUSES> are the subroutines below, which describe what to do in the
+event of an error being thrown within BLOCK.
+
+=item catch CLASS with BLOCK
+
+This clauses will cause all errors that satisfy C<$err-E<gt>isa(CLASS)>
+to be caught and handled by evaluating C<BLOCK>.
+
+C<BLOCK> will be passed two arguments. The first will be the error
+being thrown. The second is a reference to a scalar variable. If this
+variable is set by the catch block then, on return from the catch
+block, try will continue processing as if the catch block was never
+found.
+
+To propagate the error the catch block may call C<$err-E<gt>throw>
+
+If the scalar reference by the second argument is not set, and the
+error is not thrown. Then the current try block will return with the
+result from the catch block.
+
+=item except BLOCK
+
+When C<try> is looking for a handler, if an except clause is found
+C<BLOCK> is evaluated. The return value from this block should be a
+HASHREF or a list of key-value pairs, where the keys are class names
+and the values are CODE references for the handler of errors of that
+type.
+
+=item otherwise BLOCK
+
+Catch any error by executing the code in C<BLOCK>
+
+When evaluated C<BLOCK> will be passed one argument, which will be the
+error being processed.
+
+Only one otherwise block may be specified per try block
+
+=item finally BLOCK
+
+Execute the code in C<BLOCK> either after the code in the try block has
+successfully completed, or if the try block throws an error then
+C<BLOCK> will be executed after the handler has completed.
+
+If the handler throws an error then the error will be caught, the
+finally block will be executed and the error will be re-thrown.
+
+Only one finally block may be specified per try block
+
+=back
+
+=head1 CLASS INTERFACE
+
+=head2 CONSTRUCTORS
+
+The C<Error> object is implemented as a HASH. This HASH is initialized
+with the arguments that are passed to it's constructor. The elements
+that are used by, or are retrievable by the C<Error> class are listed
+below, other classes may add to these.
+
+	-file
+	-line
+	-text
+	-value
+	-object
+
+If C<-file> or C<-line> are not specified in the constructor arguments
+then these will be initialized with the file name and line number where
+the constructor was called from.
+
+If the error is associated with an object then the object should be
+passed as the C<-object> argument. This will allow the C<Error> package
+to associate the error with the object.
+
+The C<Error> package remembers the last error created, and also the
+last error associated with a package. This could either be the last
+error created by a sub in that package, or the last error which passed
+an object blessed into that package as the C<-object> argument.
+
+=over 4
+
+=item throw ( [ ARGS ] )
+
+Create a new C<Error> object and throw an error, which will be caught
+by a surrounding C<try> block, if there is one. Otherwise it will cause
+the program to exit.
+
+C<throw> may also be called on an existing error to re-throw it.
+
+=item with ( [ ARGS ] )
+
+Create a new C<Error> object and returns it. This is defined for
+syntactic sugar, eg
+
+    die with Some::Error ( ... );
+
+=item record ( [ ARGS ] )
+
+Create a new C<Error> object and returns it. This is defined for
+syntactic sugar, eg
+
+    record Some::Error ( ... )
+	and return;
+
+=back
+
+=head2 STATIC METHODS
+
+=over 4
+
+=item prior ( [ PACKAGE ] )
+
+Return the last error created, or the last error associated with
+C<PACKAGE>
+
+=item flush ( [ PACKAGE ] )
+
+Flush the last error created, or the last error associated with
+C<PACKAGE>.It is necessary to clear the error stack before exiting the
+package or uncaught errors generated using C<record> will be reported.
+
+     $Error->flush;
+
+=cut
+
+=back
+
+=head2 OBJECT METHODS
+
+=over 4
+
+=item stacktrace
+
+If the variable C<$Error::Debug> was non-zero when the error was
+created, then C<stacktrace> returns a string created by calling
+C<Carp::longmess>. If the variable was zero the C<stacktrace> returns
+the text of the error appended with the filename and line number of
+where the error was created, providing the text does not end with a
+newline.
+
+=item object
+
+The object this error was associated with
+
+=item file
+
+The file where the constructor of this error was called from
+
+=item line
+
+The line where the constructor of this error was called from
+
+=item text
+
+The text of the error
+
+=back
+
+=head2 OVERLOAD METHODS
+
+=over 4
+
+=item stringify
+
+A method that converts the object into a string. This method may simply
+return the same as the C<text> method, or it may append more
+information. For example the file name and line number.
+
+By default this method returns the C<-text> argument that was passed to
+the constructor, or the string C<"Died"> if none was given.
+
+=item value
+
+A method that will return a value that can be associated with the
+error. For example if an error was created due to the failure of a
+system call, then this may return the numeric value of C<$!> at the
+time.
+
+By default this method returns the C<-value> argument that was passed
+to the constructor.
+
+=back
+
+=head1 PRE-DEFINED ERROR CLASSES
+
+=over 4
+
+=item Error::Simple
+
+This class can be used to hold simple error strings and values. It's
+constructor takes two arguments. The first is a text value, the second
+is a numeric value. These values are what will be returned by the
+overload methods.
+
+If the text value ends with C<at file line 1> as $@ strings do, then
+this infomation will be used to set the C<-file> and C<-line> arguments
+of the error object.
+
+This class is used internally if an eval'd block die's with an error
+that is a plain string. (Unless C<$Error::ObjectifyCallback> is modified)
+
+=back
+
+=head1 $Error::ObjectifyCallback
+
+This variable holds a reference to a subroutine that converts errors that
+are plain strings to objects. It is used by Error.pm to convert textual
+errors to objects, and can be overrided by the user.
+
+It accepts a single argument which is a hash reference to named parameters. 
+Currently the only named parameter passed is C<'text'> which is the text
+of the error, but others may be available in the future.
+
+For example the following code will cause Error.pm to throw objects of the
+class MyError::Bar by default:
+
+    sub throw_MyError_Bar
+    {
+        my $args = shift;
+        my $err = MyError::Bar->new();
+        $err->{'MyBarText'} = $args->{'text'};
+        return $err;
+    }
+
+    {
+        local $Error::ObjectifyCallback = \&throw_MyError_Bar;
+
+        # Error handling here.
+    }
+
+=head1 KNOWN BUGS
+
+None, but that does not mean there are not any.
+
+=head1 AUTHORS
+
+Graham Barr <gbarr@pobox.com>
+
+The code that inspired me to write this was originally written by
+Peter Seibel <peter@weblogic.com> and adapted by Jesse Glick
+<jglick@sig.bsh.com>.
+
+=head1 MAINTAINER
+
+Shlomi Fish <shlomif@iglu.org.il>
+
+=head1 PAST MAINTAINERS
+
+Arun Kumar U <u_arunkumar@yahoo.com>
+
+=cut
diff --git a/perl/Makefile.PL b/perl/Makefile.PL
index dd61056..54e8b20 100644
--- a/perl/Makefile.PL
+++ b/perl/Makefile.PL
@@ -8,9 +8,19 @@ instlibdir:
 MAKE_FRAG
 }
 
+my %pm = ('Git.pm' => '$(INST_LIBDIR)/Git.pm');
+
+# We come with our own bundled Error.pm. It's not in the set of default
+# Perl modules so install it if it's not available on the system yet.
+eval { require 'Error' };
+if ($@) {
+	$pm{'Error.pm'} = '$(INST_LIBDIR)/Error.pm';
+}
+
 WriteMakefile(
 	NAME            => 'Git',
 	VERSION_FROM    => 'Git.pm',
+	PM		=> \%pm,
 	MYEXTLIB        => '../libgit.a',
 	INC             => '-I. -I..',
 );

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 07/12] Git.pm: Better error handling
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (4 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 06/12] Add Error.pm to the distribution Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  8:37   ` Junio C Hamano
  2006-06-24  2:34 ` [PATCH 08/12] Git.pm: Handle failed commands' output Petr Baudis
                   ` (5 subsequent siblings)
  11 siblings, 1 reply; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

So far, errors just killed the whole program and in case of an error
inside of libgit it would be totally uncatchable. This patch makes
Git.pm throw standard Perl exceptions instead. In the future we might
subclass Error to Git::Error or something but for now Error::Simple
is more than enough.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |   37 +++++++++++++++++++++----------------
 perl/Git.xs |   39 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 60 insertions(+), 16 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index dcd769b..733fec9 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -88,7 +88,8 @@ increate nonwithstanding).
 =cut
 
 
-use Carp qw(carp croak);
+use Carp qw(carp); # croak is bad - throw instead
+use Error qw(:try);
 
 require XSLoader;
 XSLoader::load('Git', $VERSION);
@@ -143,14 +144,14 @@ sub repository {
 	if (defined $args[0]) {
 		if ($#args % 2 != 1) {
 			# Not a hash.
-			$#args == 0 or croak "bad usage";
-			%opts = (Directory => $args[0]);
+			$#args == 0 or throw Error::Simple("bad usage");
+			%opts = ( Directory => $args[0] );
 		} else {
 			%opts = @args;
 		}
 
 		if ($opts{Directory}) {
-			-d $opts{Directory} or croak "Directory not found: $!";
+			-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};
@@ -242,11 +243,11 @@ read.
 sub command_pipe {
 	my ($self, $cmd, @args) = _maybe_self(@_);
 
-	$cmd =~ /^[a-z0-9A-Z_-]+$/ or croak "bad command: $cmd";
+	$cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
 
 	my $pid = open(my $fh, "-|");
 	if (not defined $pid) {
-		croak "open failed: $!";
+		throw Error::Simple("open failed: $!");
 	} elsif ($pid == 0) {
 		_cmd_exec($self, $cmd, @args);
 	}
@@ -271,16 +272,17 @@ The function returns only after the comm
 sub command_noisy {
 	my ($self, $cmd, @args) = _maybe_self(@_);
 
-	$cmd =~ /^[a-z0-9A-Z_-]+$/ or croak "bad command: $cmd";
+	$cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
 
 	my $pid = fork;
 	if (not defined $pid) {
-		croak "fork failed: $!";
+		throw Error::Simple("fork failed: $!");
 	} elsif ($pid == 0) {
 		_cmd_exec($self, $cmd, @args);
 	}
 	if (waitpid($pid, 0) > 0 and $? != 0) {
-		croak "exit status: $?";
+		# This is the best candidate for a custom exception class.
+		throw Error::Simple("exit status: $?");
 	}
 }
 
@@ -340,10 +342,10 @@ # Implemented in Git.xs.
 
 =back
 
-=head1 TODO
+=head1 ERROR HANDLING
 
-This is still fairly crude.
-We need some good way to report errors back except just dying.
+All functions are supposed to throw Perl exceptions in case of errors.
+See L<Error>.
 
 =head1 COPYRIGHT
 
@@ -372,8 +374,8 @@ sub _cmd_exec {
 		$self->{opts}->{Repository} and $ENV{'GIT_DIR'} = $self->{opts}->{Repository};
 		$self->{opts}->{WorkingCopy} and chdir($self->{opts}->{WorkingCopy});
 	}
-	xs__execv_git_cmd(@args);
-	croak "exec failed: $!";
+	_execv_git_cmd(@args);
+	die "exec failed: $!";
 }
 
 # Execute the given Git command ($_[0]) with arguments ($_[1..])
@@ -388,7 +390,8 @@ sub _cmd_close {
 			# It's just close, no point in fatalities
 			carp "error closing pipe: $!";
 		} elsif ($? >> 8) {
-			croak "exit status: ".($? >> 8);
+			# This is the best candidate for a custom exception class.
+			throw Error::Simple("exit status: ".($? >> 8));
 		}
 		# else we might e.g. closed a live stream; the command
 		# dying of SIGPIPE would drive us here.
@@ -415,6 +418,8 @@ sub _call_gate {
 		#xs_call_gate($self->{opts}->{Repository});
 	}
 
+	# Having to call throw from the C code is a sure path to insanity.
+	local $SIG{__DIE__} = sub { throw Error::Simple("@_"); };
 	&$xsfunc(@args);
 }
 
@@ -422,7 +427,7 @@ sub AUTOLOAD {
 	my $xsname;
 	our $AUTOLOAD;
 	($xsname = $AUTOLOAD) =~ s/.*:://;
-	croak "&Git::$xsname not defined" if $xsname =~ /^xs_/;
+	throw Error::Simple("&Git::$xsname not defined") if $xsname =~ /^xs_/;
 	$xsname = 'xs_'.$xsname;
 	_call_gate(\&$xsname, @_);
 }
diff --git a/perl/Git.xs b/perl/Git.xs
index 9623fdd..ebaac4b 100644
--- a/perl/Git.xs
+++ b/perl/Git.xs
@@ -8,6 +8,8 @@ #include <ctype.h>
 #include "../cache.h"
 #include "../exec_cmd.h"
 
+#define die perlyshadow_die__
+
 /* XS and Perl interface */
 #include "EXTERN.h"
 #include "perl.h"
@@ -15,11 +17,48 @@ #include "XSUB.h"
 
 #include "ppport.h"
 
+#undef die
+
+
+static char *
+report_xs(const char *prefix, const char *err, va_list params)
+{
+	static char buf[4096];
+	strcpy(buf, prefix);
+	vsnprintf(buf + strlen(prefix), 4096 - strlen(prefix), err, params);
+	return buf;
+}
+
+void
+die_xs(const char *err, va_list params)
+{
+	char *str;
+	str = report_xs("fatal: ", err, params);
+	croak(str);
+}
+
+int
+error_xs(const char *err, va_list params)
+{
+	char *str;
+	str = report_xs("error: ", err, params);
+	warn(str);
+	return -1;
+}
+
 
 MODULE = Git		PACKAGE = Git		
 
 PROTOTYPES: DISABLE
 
+
+BOOT:
+{
+	set_error_routine(error_xs);
+	set_die_routine(die_xs);
+}
+
+
 # /* TODO: xs_call_gate(). See Git.pm. */
 
 

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 08/12] Git.pm: Handle failed commands' output
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (5 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 07/12] Git.pm: Better error handling Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 09/12] Git.pm: Enhance the command_pipe() mechanism Petr Baudis
                   ` (4 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Currently if an external command returns error exit code, a generic exception
is thrown and there is no chance for the caller to retrieve the command's
output.

This patch introduces a Git::Error::Command exception class which is thrown
in this case and contains both the error code and the captured command output.
You can use the new git_cmd_try statement to fatally catch the exception
while producing a user-friendly message.

It also adds command_close_pipe() for easier checking of exit status of
a command we have just a pipe handle of. It has partial forward dependency
on the next patch, but basically only in the area of documentation.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 git-fmt-merge-msg.perl |   13 +++
 perl/Git.pm            |  192 +++++++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 183 insertions(+), 22 deletions(-)

diff --git a/git-fmt-merge-msg.perl b/git-fmt-merge-msg.perl
index be2a48c..f86231e 100755
--- a/git-fmt-merge-msg.perl
+++ b/git-fmt-merge-msg.perl
@@ -7,6 +7,7 @@ # by grouping branches and tags together
 
 use strict;
 use Git;
+use Error qw(:try);
 
 my $repo = Git->repository();
 
@@ -31,7 +32,17 @@ sub andjoin {
 }
 
 sub repoconfig {
-	my ($val) = $repo->command_oneline('repo-config', '--get', 'merge.summary');
+	my $val;
+	try {
+		$val = $repo->command_oneline('repo-config', '--get', 'merge.summary');
+	} catch Git::Error::Command with {
+		my ($E) = shift;
+		if ($E->value() == 1) {
+			return undef;
+		} else {
+			throw $E;
+		}
+	};
 	return $val;
 }
 
diff --git a/perl/Git.pm b/perl/Git.pm
index 733fec9..4205ac5 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -24,16 +24,17 @@ # Totally unstable API.
 
   my $version = Git::command_oneline('version');
 
-  Git::command_noisy('update-server-info');
+  git_cmd_try { Git::command_noisy('update-server-info') }
+              '%s failed w/ code %d';
 
   my $repo = Git->repository (Directory => '/srv/git/cogito.git');
 
 
   my @revs = $repo->command('rev-list', '--since=last monday', '--all');
 
-  my $fh = $repo->command_pipe('rev-list', '--since=last monday', '--all');
+  my ($fh, $c) = $repo->command_pipe('rev-list', '--since=last monday', '--all');
   my $lastrev = <$fh>; chomp $lastrev;
-  close $fh; # You may want to test rev-list exit status here
+  $repo->command_close_pipe($fh, $c);
 
   my $lastrev = $repo->command_oneline('rev-list', '--all');
 
@@ -44,11 +45,11 @@ require Exporter;
 
 @ISA = qw(Exporter);
 
-@EXPORT = qw();
+@EXPORT = qw(git_cmd_try);
 
 # Methods which can be called as standalone functions as well:
 @EXPORT_OK = qw(command command_oneline command_pipe command_noisy
-                version exec_path hash_object);
+                version exec_path hash_object git_cmd_try);
 
 
 =head1 DESCRIPTION
@@ -88,7 +89,7 @@ increate nonwithstanding).
 =cut
 
 
-use Carp qw(carp); # croak is bad - throw instead
+use Carp qw(carp croak); # but croak is bad - throw instead
 use Error qw(:try);
 
 require XSLoader;
@@ -193,21 +194,35 @@ In both cases, the command's stdin and s
 =cut
 
 sub command {
-	my $fh = command_pipe(@_);
+	my ($fh, $ctx) = command_pipe(@_);
 
 	if (not defined wantarray) {
-		_cmd_close($fh);
+		# Nothing to pepper the possible exception with.
+		_cmd_close($fh, $ctx);
 
 	} elsif (not wantarray) {
 		local $/;
 		my $text = <$fh>;
-		_cmd_close($fh);
+		try {
+			_cmd_close($fh, $ctx);
+		} catch Git::Error::Command with {
+			# Pepper with the output:
+			my $E = shift;
+			$E->{'-outputref'} = \$text;
+			throw $E;
+		};
 		return $text;
 
 	} else {
 		my @lines = <$fh>;
-		_cmd_close($fh);
 		chomp @lines;
+		try {
+			_cmd_close($fh, $ctx);
+		} catch Git::Error::Command with {
+			my $E = shift;
+			$E->{'-outputref'} = \@lines;
+			throw $E;
+		};
 		return @lines;
 	}
 }
@@ -222,12 +237,18 @@ of the command's standard output.
 =cut
 
 sub command_oneline {
-	my $fh = command_pipe(@_);
+	my ($fh, $ctx) = command_pipe(@_);
 
 	my $line = <$fh>;
-	_cmd_close($fh);
-
 	chomp $line;
+	try {
+		_cmd_close($fh, $ctx);
+	} catch Git::Error::Command with {
+		# Pepper with the output:
+		my $E = shift;
+		$E->{'-outputref'} = \$line;
+		throw $E;
+	};
 	return $line;
 }
 
@@ -251,7 +272,32 @@ sub command_pipe {
 	} elsif ($pid == 0) {
 		_cmd_exec($self, $cmd, @args);
 	}
-	return $fh;
+	return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
+}
+
+
+=item command_close_pipe ( PIPE [, CTX ] )
+
+Close the C<PIPE> as returned from C<command_pipe()>, checking
+whether the command finished successfuly. The optional C<CTX> argument
+is required if you want to see the command name in the error message,
+and it is the second value returned by C<command_pipe()> when
+called in array context. The call idiom is:
+
+       my ($fh, $ctx) = $r->command_pipe('status');
+       while (<$fh>) { ... }
+       $r->command_close_pipe($fh, $ctx);
+
+Note that you should not rely on whatever actually is in C<CTX>;
+currently it is simply the command name but in future the context might
+have more complicated structure.
+
+=cut
+
+sub command_close_pipe {
+	my ($self, $fh, $ctx) = _maybe_self(@_);
+	$ctx ||= '<unknown>';
+	_cmd_close($fh, $ctx);
 }
 
 
@@ -280,9 +326,8 @@ sub command_noisy {
 	} elsif ($pid == 0) {
 		_cmd_exec($self, $cmd, @args);
 	}
-	if (waitpid($pid, 0) > 0 and $? != 0) {
-		# This is the best candidate for a custom exception class.
-		throw Error::Simple("exit status: $?");
+	if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
+		throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
 	}
 }
 
@@ -340,12 +385,117 @@ are involved.
 # Implemented in Git.xs.
 
 
+
 =back
 
 =head1 ERROR HANDLING
 
 All functions are supposed to throw Perl exceptions in case of errors.
-See L<Error>.
+See the L<Error> module on how to catch those. Most exceptions are mere
+L<Error::Simple> instances.
+
+However, the C<command()>, C<command_oneline()> and C<command_noisy()>
+functions suite can throw C<Git::Error::Command> exceptions as well: those are
+thrown when the external command returns an error code and contain the error
+code as well as access to the captured command's output. The exception class
+provides the usual C<stringify> and C<value> (command's exit code) methods and
+in addition also a C<cmd_output> method that returns either an array or a
+string with the captured command output (depending on the original function
+call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
+returns the command and its arguments (but without proper quoting).
+
+Note that the C<command_pipe()> function cannot throw this exception since
+it has no idea whether the command failed or not. You will only find out
+at the time you C<close> the pipe; if you want to have that automated,
+use C<command_close_pipe()>, which can throw the exception.
+
+=cut
+
+{
+	package Git::Error::Command;
+
+	@Git::Error::Command::ISA = qw(Error);
+
+	sub new {
+		my $self = shift;
+		my $cmdline = '' . shift;
+		my $value = 0 + shift;
+		my $outputref = shift;
+		my(@args) = ();
+
+		local $Error::Depth = $Error::Depth + 1;
+
+		push(@args, '-cmdline', $cmdline);
+		push(@args, '-value', $value);
+		push(@args, '-outputref', $outputref);
+
+		$self->SUPER::new(-text => 'command returned error', @args);
+	}
+
+	sub stringify {
+		my $self = shift;
+		my $text = $self->SUPER::stringify;
+		$self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
+	}
+
+	sub cmdline {
+		my $self = shift;
+		$self->{'-cmdline'};
+	}
+
+	sub cmd_output {
+		my $self = shift;
+		my $ref = $self->{'-outputref'};
+		defined $ref or undef;
+		if (ref $ref eq 'ARRAY') {
+			return @$ref;
+		} else { # SCALAR
+			return $$ref;
+		}
+	}
+}
+
+=over 4
+
+=item git_cmd_try { CODE } ERRMSG
+
+This magical statement will automatically catch any C<Git::Error::Command>
+exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
+on its lips; the message will have %s substituted for the command line
+and %d for the exit status. This statement is useful mostly for producing
+more user-friendly error messages.
+
+In case of no exception caught the statement returns C<CODE>'s return value.
+
+Note that this is the only auto-exported function.
+
+=cut
+
+sub git_cmd_try(&$) {
+	my ($code, $errmsg) = @_;
+	my @result;
+	my $err;
+	my $array = wantarray;
+	try {
+		if ($array) {
+			@result = &$code;
+		} else {
+			$result[0] = &$code;
+		}
+	} catch Git::Error::Command with {
+		my $E = shift;
+		$err = $errmsg;
+		$err =~ s/\%s/$E->cmdline()/ge;
+		$err =~ s/\%d/$E->value()/ge;
+		# We can't croak here since Error.pm would mangle
+		# that to Error::Simple.
+	};
+	$err and croak $err;
+	return $array ? @result : $result[0];
+}
+
+
+=back
 
 =head1 COPYRIGHT
 
@@ -384,14 +534,14 @@ # _execv_git_cmd(), implemented in Git.x
 
 # Close pipe to a subprocess.
 sub _cmd_close {
-	my ($fh) = @_;
+	my ($fh, $ctx) = @_;
 	if (not close $fh) {
 		if ($!) {
 			# It's just close, no point in fatalities
 			carp "error closing pipe: $!";
 		} elsif ($? >> 8) {
-			# This is the best candidate for a custom exception class.
-			throw Error::Simple("exit status: ".($? >> 8));
+			# The caller should pepper this.
+			throw Git::Error::Command($ctx, $? >> 8);
 		}
 		# else we might e.g. closed a live stream; the command
 		# dying of SIGPIPE would drive us here.

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 09/12] Git.pm: Enhance the command_pipe() mechanism
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (6 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 08/12] Git.pm: Handle failed commands' output Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 10/12] Git.pm: Implement options for the command interface Petr Baudis
                   ` (3 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Rename command_pipe() to command_output_pipe(), outsource
the functionality to _command_common_pipe().

Add command_input_pipe().

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |   76 +++++++++++++++++++++++++++++++++++++++++------------------
 1 files changed, 53 insertions(+), 23 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index 4205ac5..11ec62d 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -32,7 +32,7 @@ # Totally unstable API.
 
   my @revs = $repo->command('rev-list', '--since=last monday', '--all');
 
-  my ($fh, $c) = $repo->command_pipe('rev-list', '--since=last monday', '--all');
+  my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
   my $lastrev = <$fh>; chomp $lastrev;
   $repo->command_close_pipe($fh, $c);
 
@@ -48,7 +48,8 @@ require Exporter;
 @EXPORT = qw(git_cmd_try);
 
 # Methods which can be called as standalone functions as well:
-@EXPORT_OK = qw(command command_oneline command_pipe command_noisy
+@EXPORT_OK = qw(command command_oneline command_noisy
+                command_output_pipe command_input_pipe command_close_pipe
                 version exec_path hash_object git_cmd_try);
 
 
@@ -194,7 +195,7 @@ In both cases, the command's stdin and s
 =cut
 
 sub command {
-	my ($fh, $ctx) = command_pipe(@_);
+	my ($fh, $ctx) = command_output_pipe(@_);
 
 	if (not defined wantarray) {
 		# Nothing to pepper the possible exception with.
@@ -237,7 +238,7 @@ of the command's standard output.
 =cut
 
 sub command_oneline {
-	my ($fh, $ctx) = command_pipe(@_);
+	my ($fh, $ctx) = command_output_pipe(@_);
 
 	my $line = <$fh>;
 	chomp $line;
@@ -253,40 +254,49 @@ sub command_oneline {
 }
 
 
-=item command_pipe ( COMMAND [, ARGUMENTS... ] )
+=item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
 
 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.
 
+The function can return C<($pipe, $ctx)> in array context.
+See C<command_close_pipe()> for details.
+
 =cut
 
-sub command_pipe {
-	my ($self, $cmd, @args) = _maybe_self(@_);
+sub command_output_pipe {
+	_command_common_pipe('-|', @_);
+}
 
-	$cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
 
-	my $pid = open(my $fh, "-|");
-	if (not defined $pid) {
-		throw Error::Simple("open failed: $!");
-	} elsif ($pid == 0) {
-		_cmd_exec($self, $cmd, @args);
-	}
-	return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
+=item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
+
+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.
+
+The function can return C<($pipe, $ctx)> in array context.
+See C<command_close_pipe()> for details.
+
+=cut
+
+sub command_input_pipe {
+	_command_common_pipe('|-', @_);
 }
 
 
 =item command_close_pipe ( PIPE [, CTX ] )
 
-Close the C<PIPE> as returned from C<command_pipe()>, checking
+Close the C<PIPE> as returned from C<command_*_pipe()>, checking
 whether the command finished successfuly. The optional C<CTX> argument
 is required if you want to see the command name in the error message,
-and it is the second value returned by C<command_pipe()> when
+and it is the second value returned by C<command_*_pipe()> when
 called in array context. The call idiom is:
 
-       my ($fh, $ctx) = $r->command_pipe('status');
-       while (<$fh>) { ... }
-       $r->command_close_pipe($fh, $ctx);
+	my ($fh, $ctx) = $r->command_output_pipe('status');
+	while (<$fh>) { ... }
+	$r->command_close_pipe($fh, $ctx);
 
 Note that you should not rely on whatever actually is in C<CTX>;
 currently it is simply the command name but in future the context might
@@ -317,8 +327,7 @@ The function returns only after the comm
 
 sub command_noisy {
 	my ($self, $cmd, @args) = _maybe_self(@_);
-
-	$cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
+	_check_valid_cmd($cmd);
 
 	my $pid = fork;
 	if (not defined $pid) {
@@ -404,7 +413,7 @@ string with the captured command output 
 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
 returns the command and its arguments (but without proper quoting).
 
-Note that the C<command_pipe()> function cannot throw this exception since
+Note that the C<command_*_pipe()> functions cannot throw this exception since
 it has no idea whether the command failed or not. You will only find out
 at the time you C<close> the pipe; if you want to have that automated,
 use C<command_close_pipe()>, which can throw the exception.
@@ -516,6 +525,27 @@ sub _maybe_self {
 	ref $_[0] eq 'Git' ? @_ : (undef, @_);
 }
 
+# Check if the command id is something reasonable.
+sub _check_valid_cmd {
+	my ($cmd) = @_;
+	$cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
+}
+
+# Common backend for the pipe creators.
+sub _command_common_pipe {
+	my $direction = shift;
+	my ($self, $cmd, @args) = _maybe_self(@_);
+	_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);
+	}
+	return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
+}
+
 # When already in the subprocess, set up the appropriate state
 # for the given repository and execute the git command.
 sub _cmd_exec {

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 10/12] Git.pm: Implement options for the command interface
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (7 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 09/12] Git.pm: Enhance the command_pipe() mechanism Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 11/12] Git.pm: Add support for subdirectories inside of working copies Petr Baudis
                   ` (2 subsequent siblings)
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

This gives the user a way to easily pass options to the command routines.
Currently only the STDERR option is implemented and can be used to adjust
what shall be done with error output of the called command (most usefully,
it can be used to silence it).

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |   37 +++++++++++++++++++++++++++++++++++--
 1 files changed, 35 insertions(+), 2 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index 11ec62d..e2b66c4 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -36,7 +36,8 @@ # Totally unstable API.
   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
 
@@ -178,9 +179,21 @@ sub repository {
 
 =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 +244,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.
@@ -256,6 +271,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 +289,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.
@@ -534,13 +553,27 @@ 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) {
+		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;

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 11/12] Git.pm: Add support for subdirectories inside of working copies
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (8 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 10/12] Git.pm: Implement options for the command interface Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:34 ` [PATCH 12/12] Convert git-mv to use Git.pm Petr Baudis
  2006-06-24  2:46 ` [PATCH 01/12] Introduce Git.pm (v4) Junio C Hamano
  11 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

This patch adds support for subdirectories inside of working copies;
you can specify them in the constructor either as the Directory
option (it will just get autodetected using rev-parse) or explicitly
using the WorkingSubdir option. This makes Git->repository() do the
exact same path setup and repository lookup as the Git porcelain
does.

This patch also introduces repo_path(), wc_path() and wc_subdir()
accessor methods and wc_chdir() mutator.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.pm |  157 ++++++++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 129 insertions(+), 28 deletions(-)

diff --git a/perl/Git.pm b/perl/Git.pm
index e2b66c4..7bbb5be 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -69,20 +69,18 @@ (In the future, we will also get a new_r
 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
@@ -93,6 +91,7 @@ increate nonwithstanding).
 
 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);
@@ -119,12 +118,17 @@ B<Repository> - Path to the Git reposito
 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.
@@ -134,7 +138,10 @@ to the constructor; it is equivalent to 
 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
 
@@ -152,18 +159,59 @@ 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 ($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};
+		if ($dir) {
+			$opts{Repository} = abs_path($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)) = '';
 			}
-			delete $opts{Directory};
+			$opts{WorkingCopy} = $dir;
+			$opts{WorkingSubdir} = $prefix;
+
+		} else {
+			# A bare repository? Let's see...
+			$dir = $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');
+			}
+
+			$opts{Repository} = abs_path($dir);
 		}
+
+		delete $opts{Directory};
 	}
 
 	$self = { opts => \%opts };
@@ -256,7 +304,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 {
@@ -374,7 +422,7 @@ # Implemented in Git.xs.
 
 =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
@@ -385,6 +433,58 @@ are involved.
 # Implemented in Git.xs.
 
 
+=item repo_path ()
+
+Return path to the git repository. Must be called on a repository instance.
+
+=cut
+
+sub repo_path { $_[0]->{opts}->{Repository} }
+
+
+=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 ( FILENAME [, TYPE ] )
 
 =item hash_object ( FILEHANDLE [, TYPE ] )
@@ -584,8 +684,9 @@ # for the given repository and execute t
 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: $!";

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 12/12] Convert git-mv to use Git.pm
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (9 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 11/12] Git.pm: Add support for subdirectories inside of working copies Petr Baudis
@ 2006-06-24  2:34 ` Petr Baudis
  2006-06-24  2:39   ` Petr Baudis
  2006-06-24  2:46 ` [PATCH 01/12] Introduce Git.pm (v4) Junio C Hamano
  11 siblings, 1 reply; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:34 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Fairly straightforward.

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 git-mv.perl |   46 ++++++++++++++++++++++------------------------
 1 files changed, 22 insertions(+), 24 deletions(-)

diff --git a/git-mv.perl b/git-mv.perl
index 75aa8fe..b9e3537 100755
--- a/git-mv.perl
+++ b/git-mv.perl
@@ -10,6 +10,8 @@ # at the discretion of Linus Torvalds.
 use warnings;
 use strict;
 use Getopt::Std;
+use Git;
+use Error qw(:try);
 
 sub usage() {
 	print <<EOT;
@@ -24,9 +26,7 @@ getopts("hnfkv") || usage;
 usage() if $opt_h;
 @ARGV >= 1 or usage;
 
-my $GIT_DIR = `git rev-parse --git-dir`;
-exit 1 if $?; # rev-parse would have given "not a git dir" message.
-chomp($GIT_DIR);
+my $repo = Git->repository();
 
 my (@srcArgs, @dstArgs, @srcs, @dsts);
 my ($src, $dst, $base, $dstDir);
@@ -62,11 +62,11 @@ else {
     $dstDir = "";
 }
 
-my $subdir_prefix = `git rev-parse --show-prefix`;
-chomp($subdir_prefix);
+my $subdir_prefix = $repo->wc_subdir();
 
 # run in git base directory, so that git-ls-files lists all revisioned files
-chdir "$GIT_DIR/..";
+chdir $repo->wc_path();
+$repo->wc_chdir('');
 
 # normalize paths, needed to compare against versioned files and update-index
 # also, this is nicer to end-users by doing ".//a/./b/.//./c" ==> "a/b/c"
@@ -84,12 +84,10 @@ my (@allfiles,@srcfiles,@dstfiles);
 my $safesrc;
 my (%overwritten, %srcForDst);
 
-$/ = "\0";
-open(F, 'git-ls-files -z |')
-        or die "Failed to open pipe from git-ls-files: " . $!;
-
-@allfiles = map { chomp; $_; } <F>;
-close(F);
+{
+	local $/ = "\0";
+	@allfiles = $repo->command('ls-files', '-z');
+}
 
 
 my ($i, $bad);
@@ -219,28 +217,28 @@ if ($opt_n) {
 }
 else {
     if (@changedfiles) {
-	open(H, "| git-update-index -z --stdin")
-		or die "git-update-index failed to update changed files with code $!\n";
+	my ($fd, $ctx) = $repo->command_input_pipe('update-index', '-z', '--stdin');
 	foreach my $fileName (@changedfiles) {
-		print H "$fileName\0";
+		print $fd "$fileName\0";
 	}
-	close(H);
+	git_cmd_try { $repo->command_close_pipe($fd, $ctx); }
+		'git-update-index failed to update changed files with code %d';
     }
     if (@addedfiles) {
-	open(H, "| git-update-index --add -z --stdin")
-		or die "git-update-index failed to add new names with code $!\n";
+	my ($fd, $ctx) = $repo->command_input_pipe('update-index', '--add', '-z', '--stdin');
 	foreach my $fileName (@addedfiles) {
-		print H "$fileName\0";
+		print $fd "$fileName\0";
 	}
-	close(H);
+	git_cmd_try { $repo->command_close_pipe($fd, $ctx); }
+		'git-update-index failed to add new files with code %d';
     }
     if (@deletedfiles) {
-	open(H, "| git-update-index --remove -z --stdin")
-		or die "git-update-index failed to remove old names with code $!\n";
+	my ($fd, $ctx) = $repo->command_input_pipe('update-index', '--remove', '-z', '--stdin');
 	foreach my $fileName (@deletedfiles) {
-		print H "$fileName\0";
+		print $fd "$fileName\0";
 	}
-	close(H);
+	git_cmd_try { $repo->command_close_pipe($fd, $ctx); }
+		'git-update-index failed to remove old files with code %d';
     }
 }
 

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 12/12] Convert git-mv to use Git.pm
  2006-06-24  2:34 ` [PATCH 12/12] Convert git-mv to use Git.pm Petr Baudis
@ 2006-06-24  2:39   ` Petr Baudis
  0 siblings, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  2:39 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 04:34:53AM CEST, I got a letter
where Petr Baudis <pasky@suse.cz> said that...
> +use Error qw(:try);

Duh, no matter how long I stare at the patches before submitting them,
something always slips through. This isn't actually necessary anymore
since we have git_cmd_try now. (The try { } catch { } blocks turned
quite fat and ugly.)

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
                   ` (10 preceding siblings ...)
  2006-06-24  2:34 ` [PATCH 12/12] Convert git-mv to use Git.pm Petr Baudis
@ 2006-06-24  2:46 ` Junio C Hamano
  2006-06-24  3:14   ` Petr Baudis
  2006-06-24  8:33   ` Junio C Hamano
  11 siblings, 2 replies; 25+ messages in thread
From: Junio C Hamano @ 2006-06-24  2:46 UTC (permalink / raw
  To: Petr Baudis; +Cc: git

Just to let you know, I already have v3 in my tree which is
merged in "pu".  With the two fixes I sent you earlier I think
it is in a good shape to be cooked in "next".

I do not think I'd have trouble applying this new series (I
would probably start from "master" to apply it and perhaps merge
or --squash merge it onto pb/gitpm topic branch that has v3 with
the two fixes I sent you separately) but we will see soon
enough.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24  2:46 ` [PATCH 01/12] Introduce Git.pm (v4) Junio C Hamano
@ 2006-06-24  3:14   ` Petr Baudis
  2006-06-24  8:33   ` Junio C Hamano
  1 sibling, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24  3:14 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 04:46:15AM CEST, I got a letter
where Junio C Hamano <junkio@cox.net> said that...
> Just to let you know, I already have v3 in my tree which is
> merged in "pu".  With the two fixes I sent you earlier I think
> it is in a good shape to be cooked in "next".

Ah, yes, could you please apply your fixes as well? :-)

> I do not think I'd have trouble applying this new series (I
> would probably start from "master" to apply it and perhaps merge
> or --squash merge it onto pb/gitpm topic branch that has v3 with
> the two fixes I sent you separately) but we will see soon
> enough.

I noticed v3 in pu but thought that it should be trivial to just throw
that away from pu and take v4 instead - I'm sorry if that turns out to
be an issue.

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24  2:46 ` [PATCH 01/12] Introduce Git.pm (v4) Junio C Hamano
  2006-06-24  3:14   ` Petr Baudis
@ 2006-06-24  8:33   ` Junio C Hamano
  2006-06-24 11:16     ` Petr Baudis
  1 sibling, 1 reply; 25+ messages in thread
From: Junio C Hamano @ 2006-06-24  8:33 UTC (permalink / raw
  To: Petr Baudis; +Cc: git

Junio C Hamano <junkio@cox.net> writes:

> Just to let you know, I already have v3 in my tree which is
> merged in "pu".  With the two fixes I sent you earlier I think
> it is in a good shape to be cooked in "next".
>
> I do not think I'd have trouble applying this new series (I
> would probably start from "master" to apply it and perhaps merge
> or --squash merge it onto pb/gitpm topic branch that has v3 with
> the two fixes I sent you separately) but we will see soon
> enough.

EEEEEEEEEK.

git-fmt-merge-msg failed and git-pull did not notice it and went
ahead to call git-merge with an empty log message.  This screwed
up my tree rather big way.

The reason it failed?  Well, it could not find Git.pm because
the changes to fmt-merge-msg was done for distros not for people
who install under their home directories.

Now, I am quite unhappy about the situation (and it is not your
fault).  "git pull" is something almost everybody uses, and
having the series means they would need to make sure whereever
Git.pm is installed is on their PERL5LIB as things currently
stand.

In the case of git-merge-recursive.py, Fredrik does

	sys.path.append('''@@GIT_PYTHON_PATH@@''')

and while running test this invalid path is overridden by having
PYTHONPATH environment variable.  Since it is "append", the test
picks up the freshly built version, not the version from the
previous install (i.e. PYTHONPATH environment variable wins).

So you would probably want to have something like

	use lib '@@GIT_PERL_PATH@@';

inside git-fmt-merge-msg.perl, which will be turned into

	use lib '/home/junio/some/where/you/install/pm';

in git-fmt-merge-msg and things might start working.

... gitster mumbles something in his mouth, and in a puff of
smoke Merlyn appears and solves all our Perl problems ;-) ...

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 07/12] Git.pm: Better error handling
  2006-06-24  2:34 ` [PATCH 07/12] Git.pm: Better error handling Petr Baudis
@ 2006-06-24  8:37   ` Junio C Hamano
  2006-06-24 13:17     ` Petr Baudis
  0 siblings, 1 reply; 25+ messages in thread
From: Junio C Hamano @ 2006-06-24  8:37 UTC (permalink / raw
  To: Petr Baudis; +Cc: git

Petr Baudis <pasky@suse.cz> writes:

> +int
> +error_xs(const char *err, va_list params)
> +{

You said in git-compat-util.h that set_error_routine takes a
function that returns void, so this gives unnecessary type
clash.

--------------------------------
In file included from /usr/lib/perl/5.8/CORE/perl.h:756,
                 from Git.xs:15:
/usr/lib/perl/5.8/CORE/embed.h:4193:1: warning: "die" redefined
Git.xs:11:1: warning: this is the location of the previous definition
Git.xs: In function 'boot_Git':
Git.xs:57: warning: passing argument 1 of 'set_error_routine' from incompatible pointer type
Git.xs:58: warning: passing argument 1 of 'set_die_routine' makes qualified function pointer from unqualified
--------------------------------

Other troubles I saw with the v4 series while compiling:

--------------------------------
usage.c:35: warning: initialization makes qualified function pointer from unqualified
usage.c:36: warning: initialization makes qualified function pointer from unqualified

I'd fix it with this

diff --git a/usage.c b/usage.c
index b781b00..52c2e96 100644
--- a/usage.c
+++ b/usage.c
@@ -12,19 +12,19 @@ static void report(const char *prefix, c
 	fputs("\n", stderr);
 }
 
-void usage_builtin(const char *err)
+static NORETURN void usage_builtin(const char *err)
 {
 	fprintf(stderr, "usage: %s\n", err);
 	exit(129);
 }
 
-void die_builtin(const char *err, va_list params)
+static NORETURN void die_builtin(const char *err, va_list params)
 {
 	report("fatal: ", err, params);
 	exit(128);
 }
 
-void error_builtin(const char *err, va_list params)
+static void error_builtin(const char *err, va_list params)
 {
 	report("error: ", err, params);
 }

--------------------------------

(cd perl && /usr/bin/perl Makefile.PL \
                PREFIX="/home/junio/git-test" \
                DEFINE="-O2 -Wall -Wdeclaration-after-statement
                -g -DSHA1_HEADER='<openssl/sha.h>'
                -DGIT_VERSION=\\\"1.4.1.rc1.gab0df\\\"" \
                LIBS="libgit.a xdiff/lib.a -lz  -lcrypto")
Unrecognized argument in LIBS ignored: 'libgit.a'
Unrecognized argument in LIBS ignored: 'xdiff/lib.a'

Do you need to pass LIBS, and if so maybe this is not a way
Makefile.PL expects it to be passed perhaps?

--------------------------------
Makefile out-of-date with respect to Makefile.PL
Cleaning current config before rebuilding Makefile...
make -f Makefile.old clean > /dev/null 2>&1
/usr/bin/perl Makefile.PL "PREFIX=/home/junio/git-test" "DEFINE=-O2 -Wall -Wdeclaration-after-statement -g -DSHA1_HEADER='<openssl/sha.h>'  -DGIT_VERSION=\"1.4.1.rc1.gab0df\"" "LIBS=libgit.a xdiff/lib.a -lz  -lcrypto"
Unrecognized argument in LIBS ignored: 'libgit.a'
Unrecognized argument in LIBS ignored: 'xdiff/lib.a'
Writing Makefile for Git
==> Your Makefile has been rebuilt. <==
==> Please rerun the make command.  <==
false
make[1]: *** [Makefile] Error 1
--------------------------------

The latter is what Perl's build mechanism does so it is not
strictly your fault, but it nevertheless is irritating that we
have to say make clean twice.

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24  8:33   ` Junio C Hamano
@ 2006-06-24 11:16     ` Petr Baudis
  2006-06-24 11:52       ` Petr Baudis
  2006-06-24 11:57       ` Junio C Hamano
  0 siblings, 2 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24 11:16 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 10:33:52AM CEST, I got a letter
where Junio C Hamano <junkio@cox.net> said that...
> The reason it failed?  Well, it could not find Git.pm because
> the changes to fmt-merge-msg was done for distros not for people
> who install under their home directories.

I don't understand what are you trying to say here...

> Now, I am quite unhappy about the situation (and it is not your
> fault).  "git pull" is something almost everybody uses, and
> having the series means they would need to make sure whereever
> Git.pm is installed is on their PERL5LIB as things currently
> stand.

...because well, they do:

$(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
	rm -f $@ $@+
	sed -e '1s|#!.*perl\(.*\)|#!$(PERL_PATH_SQ)\1 -I'"$$(make -s -C perl instlibdir)"'|' \
	    -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
	    $@.perl >$@+
	chmod +x $@+
	mv $@+ $@

(This is also why I was a bit confused by your make test patch - it does
not "fix" anything per se since no tests directly use Git.pm.)

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24 11:16     ` Petr Baudis
@ 2006-06-24 11:52       ` Petr Baudis
  2006-06-24 11:57       ` Junio C Hamano
  1 sibling, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24 11:52 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 01:16:57PM CEST, I got a letter
where Petr Baudis <pasky@suse.cz> said that...
> $(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
> 	rm -f $@ $@+
> 	sed -e '1s|#!.*perl\(.*\)|#!$(PERL_PATH_SQ)\1 -I'"$$(make -s -C perl instlibdir)"'|' \
> 	    -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
> 	    $@.perl >$@+
> 	chmod +x $@+
> 	mv $@+ $@
> 
> (This is also why I was a bit confused by your make test patch - it does
> not "fix" anything per se since no tests directly use Git.pm.)

And this makes the Perl scripts work even without make install:

Signed-off-by: Petr Baudis <pasky@suse.cz>

diff --git a/Makefile b/Makefile
index 7842195..d614f18 100644
--- a/Makefile
+++ b/Makefile
@@ -509,7 +509,9 @@ common-cmds.h: Documentation/git-*.txt
 
 $(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
 	rm -f $@ $@+
-	sed -e '1s|#!.*perl\(.*\)|#!$(PERL_PATH_SQ)\1 -I'"$$(make -s -C perl instlibdir)"'|' \
+	sed -e '1s|#!.*perl|#!$(PERL_PATH_SQ)|' \
+	    -e '2i\
+	        use lib qw ('"$$(make -s -C perl instlibdir)"' '"$$(pwd)"'/perl/blib/lib);' \
 	    -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
 	    $@.perl >$@+
 	chmod +x $@+
diff --git a/perl/Makefile.PL b/perl/Makefile.PL
index 54e8b20..2cbd227 100644
--- a/perl/Makefile.PL
+++ b/perl/Makefile.PL
@@ -2,6 +2,9 @@ use ExtUtils::MakeMaker;
 
 sub MY::postamble {
 	return <<'MAKE_FRAG';
+all::
+	cp blib/arch/auto/Git/* blib/lib/auto/Git/
+
 instlibdir:
 	@echo $(INSTALLSITELIB)
 

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24 11:16     ` Petr Baudis
  2006-06-24 11:52       ` Petr Baudis
@ 2006-06-24 11:57       ` Junio C Hamano
  2006-06-24 13:02         ` Petr Baudis
  1 sibling, 1 reply; 25+ messages in thread
From: Junio C Hamano @ 2006-06-24 11:57 UTC (permalink / raw
  To: Petr Baudis; +Cc: git

Petr Baudis <pasky@suse.cz> writes:

> (This is also why I was a bit confused by your make test patch - it does
> not "fix" anything per se since no tests directly use Git.pm.)

You are right.

You do not want to be testing installed version, but the one
freshly built, so the patch does not have any effect, except for
one case: testing before installing Git.pm for the first time
anywhere yet.  -I prepends the directory to the search path, so
we are not testing the freshly built copy at all.

Is there a way from the environment to override this behaviour,
so that we can run the tests properly?  I think PERL5LIB and
PERLLIB are defeated by having -I there (that's why I said I
liked what Fredrik did with his Python script, which appends the
final installed location to the search path).  I think unshift
into @INC by hand (i.e. without even using use lib "$path")
would do what we want, but I feel that is a bit too ugly just 
for the testing X-<.

I suspect we would need to think this a bit more... sigh.

> ...because well, they do:
>
> $(patsubst %.perl,%,$(SCRIPT_PERL)) : % : %.perl
> 	rm -f $@ $@+
> 	sed -e '1s|#!.*perl\(.*\)|#!$(PERL_PATH_SQ)\1 -I'"$$(make -s -C perl instlibdir)"'|' \
> 	    -e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
> 	    $@.perl >$@+
> 	chmod +x $@+
> 	mv $@+ $@

I'll need to look at why it fails for me, but the above seems to
be doing the right thing, from a superficial look at least.

git-fmt-merge-msg substituted like the above begins with:

	#!/usr/bin/perl -w -I/home/junio/git-pu/share/perl/5.8.8

because my $(prefix) is /home/junio/git-pu/ when building from "pu"
branch.  Then it goes on to create ~/git-pu/{lib,share}/perl/5.8.8
and does this:

make -C perl install
make[1]: Entering directory `/opt/git/git.git/perl'
Installing /home/junio/git-pu/lib/perl/5.8.8/auto/Git/Git.so
Installing /home/junio/git-pu/lib/perl/5.8.8/auto/Git/Git.bs
Files found in blib/arch: installing files in blib/lib into architecture dependent library tree
Installing /home/junio/git-pu/lib/perl/5.8.8/Git.pm
Installing /home/junio/git-pu/lib/perl/5.8.8/Error.pm
Installing /home/junio/git-pu/man/man3/Error.3pm
Installing /home/junio/git-pu/man/man3/Git.3pm
Writing /home/junio/git-pu/lib/perl/5.8.8/auto/Git/.packlist
Appending installation info to /home/junio/git-pu/lib/perl/5.8.8/perllocal.pod

It appears that this is needed perhaps?

diff --git a/perl/Makefile.PL b/perl/Makefile.PL
index 54e8b20..92c140d 100644
--- a/perl/Makefile.PL
+++ b/perl/Makefile.PL
@@ -3,7 +3,7 @@ use ExtUtils::MakeMaker;
 sub MY::postamble {
 	return <<'MAKE_FRAG';
 instlibdir:
-	@echo $(INSTALLSITELIB)
+	@echo $(INSTALLSITEARCH)
 
 MAKE_FRAG
 }

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24 11:57       ` Junio C Hamano
@ 2006-06-24 13:02         ` Petr Baudis
  2006-06-25  3:12           ` Junio C Hamano
  0 siblings, 1 reply; 25+ messages in thread
From: Petr Baudis @ 2006-06-24 13:02 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 01:57:31PM CEST, I got a letter
where Junio C Hamano <junkio@cox.net> said that...
> Petr Baudis <pasky@suse.cz> writes:
> 
> > (This is also why I was a bit confused by your make test patch - it does
> > not "fix" anything per se since no tests directly use Git.pm.)
> 
> You are right.
> 
> You do not want to be testing installed version, but the one
> freshly built, so the patch does not have any effect, except for
> one case: testing before installing Git.pm for the first time
> anywhere yet.  -I prepends the directory to the search path, so
> we are not testing the freshly built copy at all.
> 
> Is there a way from the environment to override this behaviour,
> so that we can run the tests properly?  I think PERL5LIB and
> PERLLIB are defeated by having -I there (that's why I said I
> liked what Fredrik did with his Python script, which appends the
> final installed location to the search path).  I think unshift
> into @INC by hand (i.e. without even using use lib "$path")
> would do what we want, but I feel that is a bit too ugly just 
> for the testing X-<.

PERL5LIB and use lib at the same time works for me. Anyway, with the
second patch I've sent things should work well even if you don't have
Git.pm installed anywhere yet.

> diff --git a/perl/Makefile.PL b/perl/Makefile.PL
> index 54e8b20..92c140d 100644
> --- a/perl/Makefile.PL
> +++ b/perl/Makefile.PL
> @@ -3,7 +3,7 @@ use ExtUtils::MakeMaker;
>  sub MY::postamble {
>  	return <<'MAKE_FRAG';
>  instlibdir:
> -	@echo $(INSTALLSITELIB)
> +	@echo $(INSTALLSITEARCH)
>  
>  MAKE_FRAG
>  }

Oh, yes; that line came from the time when we had no .xs yet. It is not
visible here since both arch-specific and non-arch-specific libraries
get installed to ~/lib.

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 07/12] Git.pm: Better error handling
  2006-06-24  8:37   ` Junio C Hamano
@ 2006-06-24 13:17     ` Petr Baudis
  2006-06-25  1:13       ` Petr Baudis
  2006-06-25  1:30       ` Junio C Hamano
  0 siblings, 2 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-24 13:17 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 10:37:25AM CEST, I got a letter
where Junio C Hamano <junkio@cox.net> said that...
> Petr Baudis <pasky@suse.cz> writes:
> 
> > +int
> > +error_xs(const char *err, va_list params)
> > +{
> 
> You said in git-compat-util.h that set_error_routine takes a
> function that returns void, so this gives unnecessary type
> clash.
> 
> --------------------------------
> In file included from /usr/lib/perl/5.8/CORE/perl.h:756,
>                  from Git.xs:15:
> /usr/lib/perl/5.8/CORE/embed.h:4193:1: warning: "die" redefined
> Git.xs:11:1: warning: this is the location of the previous definition
> Git.xs: In function 'boot_Git':
> Git.xs:57: warning: passing argument 1 of 'set_error_routine' from incompatible pointer type
> Git.xs:58: warning: passing argument 1 of 'set_die_routine' makes qualified function pointer from unqualified
> --------------------------------

Oh, I forgot to fix it in the .xs. :-(

> Other troubles I saw with the v4 series while compiling:
> 
> --------------------------------
> usage.c:35: warning: initialization makes qualified function pointer from unqualified
> usage.c:36: warning: initialization makes qualified function pointer from unqualified
> 
> I'd fix it with this
...

Ah, so THAT's where you put the NORETURN thing. ;-)

> --------------------------------
> 
> (cd perl && /usr/bin/perl Makefile.PL \
>                 PREFIX="/home/junio/git-test" \
>                 DEFINE="-O2 -Wall -Wdeclaration-after-statement
>                 -g -DSHA1_HEADER='<openssl/sha.h>'
>                 -DGIT_VERSION=\\\"1.4.1.rc1.gab0df\\\"" \
>                 LIBS="libgit.a xdiff/lib.a -lz  -lcrypto")
> Unrecognized argument in LIBS ignored: 'libgit.a'
> Unrecognized argument in LIBS ignored: 'xdiff/lib.a'
> 
> Do you need to pass LIBS, and if so maybe this is not a way
> Makefile.PL expects it to be passed perhaps?

It is harmless, but this should fix it:

Signed-off-by: Petr Baudis <pasky@suse.cz>

diff --git a/Makefile b/Makefile
index d614f18..91bef4e 100644
--- a/Makefile
+++ b/Makefile
@@ -230,7 +230,8 @@ BUILTIN_OBJS = \
 	builtin-update-ref.o
 
 GITLIBS = $(LIB_FILE) $(XDIFF_LIB)
-LIBS = $(GITLIBS) -lz
+
+EXTLIBS = -lz
 
 #
 # Platform specific tweaks
@@ -380,14 +381,14 @@ ifdef NEEDS_LIBICONV
 	else
 		ICONV_LINK =
 	endif
-	LIBS += $(ICONV_LINK) -liconv
+	EXTLIBS += $(ICONV_LINK) -liconv
 endif
 ifdef NEEDS_SOCKET
-	LIBS += -lsocket
+	EXTLIBS += -lsocket
 	SIMPLE_LIB += -lsocket
 endif
 ifdef NEEDS_NSL
-	LIBS += -lnsl
+	EXTLIBS += -lnsl
 	SIMPLE_LIB += -lnsl
 endif
 ifdef NO_D_TYPE_IN_DIRENT
@@ -446,7 +447,7 @@ ifdef MOZILLA_SHA1
 	LIB_OBJS += mozilla-sha1/sha1.o
 else
 	SHA1_HEADER = <openssl/sha.h>
-	LIBS += $(LIB_4_CRYPTO)
+	EXTLIBS += $(LIB_4_CRYPTO)
 endif
 endif
 endif
@@ -469,9 +470,13 @@ PERL_PATH_SQ = $(subst ','\'',$(PERL_PAT
 PYTHON_PATH_SQ = $(subst ','\'',$(PYTHON_PATH))
 GIT_PYTHON_DIR_SQ = $(subst ','\'',$(GIT_PYTHON_DIR))
 
+LIBS = $(GITLIBS) $(EXTLIBS)
+
 ALL_CFLAGS += -DSHA1_HEADER='$(SHA1_HEADER_SQ)' $(COMPAT_CFLAGS)
 LIB_OBJS += $(COMPAT_OBJS)
 export prefix TAR INSTALL DESTDIR SHELL_PATH template_dir
+
+
 ### Build rules
 
 all: $(ALL_PROGRAMS) $(BUILT_INS) git$X gitk
@@ -601,7 +606,7 @@ perl/Makefile:	perl/Git.pm perl/Makefile
 	(cd perl && $(PERL_PATH) Makefile.PL \
 		PREFIX="$(prefix)" \
 		DEFINE="$(ALL_CFLAGS) -DGIT_VERSION=\\\"$(GIT_VERSION)\\\"" \
-		LIBS="$(LIBS)")
+		LIBS="$(EXTLIBS)")
 
 doc:
 	$(MAKE) -C Documentation all

> --------------------------------
> Makefile out-of-date with respect to Makefile.PL
> Cleaning current config before rebuilding Makefile...
> make -f Makefile.old clean > /dev/null 2>&1
> /usr/bin/perl Makefile.PL "PREFIX=/home/junio/git-test" "DEFINE=-O2 -Wall -Wdeclaration-after-statement -g -DSHA1_HEADER='<openssl/sha.h>'  -DGIT_VERSION=\"1.4.1.rc1.gab0df\"" "LIBS=libgit.a xdiff/lib.a -lz  -lcrypto"
> Unrecognized argument in LIBS ignored: 'libgit.a'
> Unrecognized argument in LIBS ignored: 'xdiff/lib.a'
> Writing Makefile for Git
> ==> Your Makefile has been rebuilt. <==
> ==> Please rerun the make command.  <==
> false
> make[1]: *** [Makefile] Error 1
> --------------------------------
> 
> The latter is what Perl's build mechanism does so it is not
> strictly your fault, but it nevertheless is irritating that we
> have to say make clean twice.

What about just this?

Signed-off-by: Petr Baudis <pasky@suse.cz>

diff --git a/Makefile b/Makefile
index 91bef4e..55c07b6 100644
--- a/Makefile
+++ b/Makefile
@@ -731,7 +731,8 @@ clean:
 	rm -f $(GIT_TARNAME).tar.gz git-core_$(GIT_VERSION)-*.tar.gz
 	rm -f $(htmldocs).tar.gz $(manpages).tar.gz
 	$(MAKE) -C Documentation/ clean
-	[ ! -e perl/Makefile ] || $(MAKE) -C perl/ clean
+	# Try twice in case the Makefile has been rebuilt
+	[ ! -e perl/Makefile ] || $(MAKE) -C perl/ clean || $(MAKE) -C perl/ clean
 	$(MAKE) -C templates/ clean
 	$(MAKE) -C t/ clean
 	rm -f GIT-VERSION-FILE GIT-CFLAGS

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 07/12] Git.pm: Better error handling
  2006-06-24 13:17     ` Petr Baudis
@ 2006-06-25  1:13       ` Petr Baudis
  2006-06-25  1:30       ` Junio C Hamano
  1 sibling, 0 replies; 25+ messages in thread
From: Petr Baudis @ 2006-06-25  1:13 UTC (permalink / raw
  To: Junio C Hamano; +Cc: git

Dear diary, on Sat, Jun 24, 2006 at 03:17:31PM CEST, I got a letter
where Petr Baudis <pasky@suse.cz> said that...
> Dear diary, on Sat, Jun 24, 2006 at 10:37:25AM CEST, I got a letter
> where Junio C Hamano <junkio@cox.net> said that...
> > Petr Baudis <pasky@suse.cz> writes:
> > 
> > > +int
> > > +error_xs(const char *err, va_list params)
> > > +{
> > 
> > You said in git-compat-util.h that set_error_routine takes a
> > function that returns void, so this gives unnecessary type
> > clash.
> > 
> > --------------------------------
> > In file included from /usr/lib/perl/5.8/CORE/perl.h:756,
> >                  from Git.xs:15:
> > /usr/lib/perl/5.8/CORE/embed.h:4193:1: warning: "die" redefined
> > Git.xs:11:1: warning: this is the location of the previous definition
> > Git.xs: In function 'boot_Git':
> > Git.xs:57: warning: passing argument 1 of 'set_error_routine' from incompatible pointer type
> > Git.xs:58: warning: passing argument 1 of 'set_die_routine' makes qualified function pointer from unqualified
> > --------------------------------
> 
> Oh, I forgot to fix it in the .xs. :-(

---
[PATCH] Git.pm: Squash some annoying warnings in Git.xs

From: Petr Baudis <pasky@suse.cz>

Signed-off-by: Petr Baudis <pasky@suse.cz>
---

 perl/Git.xs |   11 ++++-------
 1 files changed, 4 insertions(+), 7 deletions(-)

diff --git a/perl/Git.xs b/perl/Git.xs
index e841e4a..d7a2b75 100644
--- a/perl/Git.xs
+++ b/perl/Git.xs
@@ -29,21 +29,18 @@ report_xs(const char *prefix, const char
 	return buf;
 }
 
-void
+void NORETURN
 die_xs(const char *err, va_list params)
 {
-	char *str;
-	str = report_xs("fatal: ", err, params);
+	char *str = report_xs("fatal: ", err, params);
 	croak(str);
 }
 
-int
+void
 error_xs(const char *err, va_list params)
 {
-	char *str;
-	str = report_xs("error: ", err, params);
+	char *str = report_xs("error: ", err, params);
 	warn(str);
-	return -1;
 }
 
 

-- 
				Petr "Pasky" Baudis
Stuff: http://pasky.or.cz/
A person is just about as big as the things that make them angry.

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 07/12] Git.pm: Better error handling
  2006-06-24 13:17     ` Petr Baudis
  2006-06-25  1:13       ` Petr Baudis
@ 2006-06-25  1:30       ` Junio C Hamano
  1 sibling, 0 replies; 25+ messages in thread
From: Junio C Hamano @ 2006-06-25  1:30 UTC (permalink / raw
  To: Petr Baudis; +Cc: git, Linus Torvalds

Petr Baudis <pasky@suse.cz> writes:

>> --------------------------------
>> 
>> (cd perl && /usr/bin/perl Makefile.PL \
>>                 PREFIX="/home/junio/git-test" \
>>                 DEFINE="-O2 -Wall -Wdeclaration-after-statement
>>                 -g -DSHA1_HEADER='<openssl/sha.h>'
>>                 -DGIT_VERSION=\\\"1.4.1.rc1.gab0df\\\"" \
>>                 LIBS="libgit.a xdiff/lib.a -lz  -lcrypto")
>> Unrecognized argument in LIBS ignored: 'libgit.a'
>> Unrecognized argument in LIBS ignored: 'xdiff/lib.a'
>> 
>> Do you need to pass LIBS, and if so maybe this is not a way
>> Makefile.PL expects it to be passed perhaps?
>
> It is harmless, but this should fix it:
>
> Signed-off-by: Petr Baudis <pasky@suse.cz>

Applied the "EXTLIBS" change in the message.  I did the same
"clean twice" change last night.  Also I will apply the
"PERL_DEFINES_SQ" change as well.  Hopefully this would make
things buildable for more people.

Thanks.

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 01/12] Introduce Git.pm (v4)
  2006-06-24 13:02         ` Petr Baudis
@ 2006-06-25  3:12           ` Junio C Hamano
  0 siblings, 0 replies; 25+ messages in thread
From: Junio C Hamano @ 2006-06-25  3:12 UTC (permalink / raw
  To: Petr Baudis; +Cc: git

ePetr Baudis <pasky@suse.cz> writes:

>> Is there a way from the environment to override this behaviour,
>> so that we can run the tests properly?  I think PERL5LIB and
>> PERLLIB are defeated by having -I there (that's why I said I
>> liked what Fredrik did with his Python script, which appends the
>> final installed location to the search path).  I think unshift
>> into @INC by hand (i.e. without even using use lib "$path")
>> would do what we want, but I feel that is a bit too ugly just 
>> for the testing X-<.
>
> PERL5LIB and use lib at the same time works for me. Anyway, with the
> second patch I've sent things should work well even if you don't have
> Git.pm installed anywhere yet.

Sorry, I am not sure it "works for me" -- which one take
precedence for this?

	$ head -n 2 script.perl
        #!/usr/bin/perl -w -I /path/a
        use lib "/path/b";
        $ ./script.perl ;# invocation #1
        $ PERL5LIB=/path/c ./script.perl ;# invocation #2

Precedence between the in-script -I and "use lib" are
irrelevant, but unless PERL5LIB takes precedence and the
invocation #2 takes Git.pm from /path/c my previous patch 
to make sure test uses freshly built one does not work.

>> diff --git a/perl/Makefile.PL b/perl/Makefile.PL
>> index 54e8b20..92c140d 100644
>> --- a/perl/Makefile.PL
>> +++ b/perl/Makefile.PL
>> @@ -3,7 +3,7 @@ use ExtUtils::MakeMaker;
>>  sub MY::postamble {
>>  	return <<'MAKE_FRAG';
>>  instlibdir:
>> -	@echo $(INSTALLSITELIB)
>> +	@echo $(INSTALLSITEARCH)
>>  
>>  MAKE_FRAG
>>  }
>
> Oh, yes; that line came from the time when we had no .xs yet. It is not
> visible here since both arch-specific and non-arch-specific libraries
> get installed to ~/lib.

OK.  Thanks.

^ permalink raw reply	[flat|nested] 25+ messages in thread

end of thread, other threads:[~2006-06-25  3:13 UTC | newest]

Thread overview: 25+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2006-06-24  2:34 [PATCH 01/12] Introduce Git.pm (v4) Petr Baudis
2006-06-24  2:34 ` [PATCH 02/12] Git.pm: Implement Git::exec_path() Petr Baudis
2006-06-24  2:34 ` [PATCH 03/12] Git.pm: Call external commands using execv_git_cmd() Petr Baudis
2006-06-24  2:34 ` [PATCH 04/12] Git.pm: Implement Git::version() Petr Baudis
2006-06-24  2:34 ` [PATCH 05/12] Customizable error handlers Petr Baudis
2006-06-24  2:34 ` [PATCH 06/12] Add Error.pm to the distribution Petr Baudis
2006-06-24  2:34 ` [PATCH 07/12] Git.pm: Better error handling Petr Baudis
2006-06-24  8:37   ` Junio C Hamano
2006-06-24 13:17     ` Petr Baudis
2006-06-25  1:13       ` Petr Baudis
2006-06-25  1:30       ` Junio C Hamano
2006-06-24  2:34 ` [PATCH 08/12] Git.pm: Handle failed commands' output Petr Baudis
2006-06-24  2:34 ` [PATCH 09/12] Git.pm: Enhance the command_pipe() mechanism Petr Baudis
2006-06-24  2:34 ` [PATCH 10/12] Git.pm: Implement options for the command interface Petr Baudis
2006-06-24  2:34 ` [PATCH 11/12] Git.pm: Add support for subdirectories inside of working copies Petr Baudis
2006-06-24  2:34 ` [PATCH 12/12] Convert git-mv to use Git.pm Petr Baudis
2006-06-24  2:39   ` Petr Baudis
2006-06-24  2:46 ` [PATCH 01/12] Introduce Git.pm (v4) Junio C Hamano
2006-06-24  3:14   ` Petr Baudis
2006-06-24  8:33   ` Junio C Hamano
2006-06-24 11:16     ` Petr Baudis
2006-06-24 11:52       ` Petr Baudis
2006-06-24 11:57       ` Junio C Hamano
2006-06-24 13:02         ` Petr Baudis
2006-06-25  3:12           ` Junio C Hamano

Code repositories for project(s) associated with this public inbox

	https://80x24.org/mirrors/git.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).