Merge branch 'ao/send-email-irt'
[git/kirr.git] / perl / Git.pm
blob205e48aa3a7b912005565ac9c296205a897a1476
1 =head1 NAME
3 Git - Perl interface to the Git version control system
5 =cut
8 package Git;
10 use 5.008;
11 use strict;
14 BEGIN {
16 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
18 # Totally unstable API.
19 $VERSION = '0.01';
22 =head1 SYNOPSIS
24 use Git;
26 my $version = Git::command_oneline('version');
28 git_cmd_try { Git::command_noisy('update-server-info') }
29 '%s failed w/ code %d';
31 my $repo = Git->repository (Directory => '/srv/git/cogito.git');
34 my @revs = $repo->command('rev-list', '--since=last monday', '--all');
36 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
37 my $lastrev = <$fh>; chomp $lastrev;
38 $repo->command_close_pipe($fh, $c);
40 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
41 STDERR => 0 );
43 my $sha1 = $repo->hash_and_insert_object('file.txt');
44 my $tempfile = tempfile();
45 my $size = $repo->cat_blob($sha1, $tempfile);
47 =cut
50 require Exporter;
52 @ISA = qw(Exporter);
54 @EXPORT = qw(git_cmd_try);
56 # Methods which can be called as standalone functions as well:
57 @EXPORT_OK = qw(command command_oneline command_noisy
58 command_output_pipe command_input_pipe command_close_pipe
59 command_bidi_pipe command_close_bidi_pipe
60 version exec_path html_path hash_object git_cmd_try
61 remote_refs
62 temp_acquire temp_release temp_reset temp_path);
65 =head1 DESCRIPTION
67 This module provides Perl scripts easy way to interface the Git version control
68 system. The modules have an easy and well-tested way to call arbitrary Git
69 commands; in the future, the interface will also provide specialized methods
70 for doing easily operations which are not totally trivial to do over
71 the generic command interface.
73 While some commands can be executed outside of any context (e.g. 'version'
74 or 'init'), most operations require a repository context, which in practice
75 means getting an instance of the Git object using the repository() constructor.
76 (In the future, we will also get a new_repository() constructor.) All commands
77 called as methods of the object are then executed in the context of the
78 repository.
80 Part of the "repository state" is also information about path to the attached
81 working copy (unless you work with a bare repository). You can also navigate
82 inside of the working copy using the C<wc_chdir()> method. (Note that
83 the repository object is self-contained and will not change working directory
84 of your process.)
86 TODO: In the future, we might also do
88 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
89 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
90 my @refs = $remoterepo->refs();
92 Currently, the module merely wraps calls to external Git tools. In the future,
93 it will provide a much faster way to interact with Git by linking directly
94 to libgit. This should be completely opaque to the user, though (performance
95 increase notwithstanding).
97 =cut
100 use Carp qw(carp croak); # but croak is bad - throw instead
101 use Error qw(:try);
102 use Cwd qw(abs_path);
103 use IPC::Open2 qw(open2);
104 use Fcntl qw(SEEK_SET SEEK_CUR);
108 =head1 CONSTRUCTORS
110 =over 4
112 =item repository ( OPTIONS )
114 =item repository ( DIRECTORY )
116 =item repository ()
118 Construct a new repository object.
119 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
120 Possible options are:
122 B<Repository> - Path to the Git repository.
124 B<WorkingCopy> - Path to the associated working copy; not strictly required
125 as many commands will happily crunch on a bare repository.
127 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
128 Just left undefined if you do not want to limit the scope of operations.
130 B<Directory> - Path to the Git working directory in its usual setup.
131 The C<.git> directory is searched in the directory and all the parent
132 directories; if found, C<WorkingCopy> is set to the directory containing
133 it and C<Repository> to the C<.git> directory itself. If no C<.git>
134 directory was found, the C<Directory> is assumed to be a bare repository,
135 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
136 If the C<$GIT_DIR> environment variable is set, things behave as expected
137 as well.
139 You should not use both C<Directory> and either of C<Repository> and
140 C<WorkingCopy> - the results of that are undefined.
142 Alternatively, a directory path may be passed as a single scalar argument
143 to the constructor; it is equivalent to setting only the C<Directory> option
144 field.
146 Calling the constructor with no options whatsoever is equivalent to
147 calling it with C<< Directory => '.' >>. In general, if you are building
148 a standard porcelain command, simply doing C<< Git->repository() >> should
149 do the right thing and setup the object to reflect exactly where the user
150 is right now.
152 =cut
154 sub repository {
155 my $class = shift;
156 my @args = @_;
157 my %opts = ();
158 my $self;
160 if (defined $args[0]) {
161 if ($#args % 2 != 1) {
162 # Not a hash.
163 $#args == 0 or throw Error::Simple("bad usage");
164 %opts = ( Directory => $args[0] );
165 } else {
166 %opts = @args;
170 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
171 and not defined $opts{Directory}) {
172 $opts{Directory} = '.';
175 if (defined $opts{Directory}) {
176 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
178 my $search = Git->repository(WorkingCopy => $opts{Directory});
179 my $dir;
180 try {
181 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
182 STDERR => 0);
183 } catch Git::Error::Command with {
184 $dir = undef;
187 if ($dir) {
188 $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
189 $opts{Repository} = abs_path($dir);
191 # If --git-dir went ok, this shouldn't die either.
192 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
193 $dir = abs_path($opts{Directory}) . '/';
194 if ($prefix) {
195 if (substr($dir, -length($prefix)) ne $prefix) {
196 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
198 substr($dir, -length($prefix)) = '';
200 $opts{WorkingCopy} = $dir;
201 $opts{WorkingSubdir} = $prefix;
203 } else {
204 # A bare repository? Let's see...
205 $dir = $opts{Directory};
207 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
208 # Mimic git-rev-parse --git-dir error message:
209 throw Error::Simple("fatal: Not a git repository: $dir");
211 my $search = Git->repository(Repository => $dir);
212 try {
213 $search->command('symbolic-ref', 'HEAD');
214 } catch Git::Error::Command with {
215 # Mimic git-rev-parse --git-dir error message:
216 throw Error::Simple("fatal: Not a git repository: $dir");
219 $opts{Repository} = abs_path($dir);
222 delete $opts{Directory};
225 $self = { opts => \%opts };
226 bless $self, $class;
229 =back
231 =head1 METHODS
233 =over 4
235 =item command ( COMMAND [, ARGUMENTS... ] )
237 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
239 Execute the given Git C<COMMAND> (specify it without the 'git-'
240 prefix), optionally with the specified extra C<ARGUMENTS>.
242 The second more elaborate form can be used if you want to further adjust
243 the command execution. Currently, only one option is supported:
245 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
246 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
247 it to be thrown away. If you want to process it, you can get it in a filehandle
248 you specify, but you must be extremely careful; if the error output is not
249 very short and you want to read it in the same process as where you called
250 C<command()>, you are set up for a nice deadlock!
252 The method can be called without any instance or on a specified Git repository
253 (in that case the command will be run in the repository context).
255 In scalar context, it returns all the command output in a single string
256 (verbatim).
258 In array context, it returns an array containing lines printed to the
259 command's stdout (without trailing newlines).
261 In both cases, the command's stdin and stderr are the same as the caller's.
263 =cut
265 sub command {
266 my ($fh, $ctx) = command_output_pipe(@_);
268 if (not defined wantarray) {
269 # Nothing to pepper the possible exception with.
270 _cmd_close($fh, $ctx);
272 } elsif (not wantarray) {
273 local $/;
274 my $text = <$fh>;
275 try {
276 _cmd_close($fh, $ctx);
277 } catch Git::Error::Command with {
278 # Pepper with the output:
279 my $E = shift;
280 $E->{'-outputref'} = \$text;
281 throw $E;
283 return $text;
285 } else {
286 my @lines = <$fh>;
287 defined and chomp for @lines;
288 try {
289 _cmd_close($fh, $ctx);
290 } catch Git::Error::Command with {
291 my $E = shift;
292 $E->{'-outputref'} = \@lines;
293 throw $E;
295 return @lines;
300 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
302 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
304 Execute the given C<COMMAND> in the same way as command()
305 does but always return a scalar string containing the first line
306 of the command's standard output.
308 =cut
310 sub command_oneline {
311 my ($fh, $ctx) = command_output_pipe(@_);
313 my $line = <$fh>;
314 defined $line and chomp $line;
315 try {
316 _cmd_close($fh, $ctx);
317 } catch Git::Error::Command with {
318 # Pepper with the output:
319 my $E = shift;
320 $E->{'-outputref'} = \$line;
321 throw $E;
323 return $line;
327 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
329 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
331 Execute the given C<COMMAND> in the same way as command()
332 does but return a pipe filehandle from which the command output can be
333 read.
335 The function can return C<($pipe, $ctx)> in array context.
336 See C<command_close_pipe()> for details.
338 =cut
340 sub command_output_pipe {
341 _command_common_pipe('-|', @_);
345 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
347 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
349 Execute the given C<COMMAND> in the same way as command_output_pipe()
350 does but return an input pipe filehandle instead; the command output
351 is not captured.
353 The function can return C<($pipe, $ctx)> in array context.
354 See C<command_close_pipe()> for details.
356 =cut
358 sub command_input_pipe {
359 _command_common_pipe('|-', @_);
363 =item command_close_pipe ( PIPE [, CTX ] )
365 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
366 whether the command finished successfully. The optional C<CTX> argument
367 is required if you want to see the command name in the error message,
368 and it is the second value returned by C<command_*_pipe()> when
369 called in array context. The call idiom is:
371 my ($fh, $ctx) = $r->command_output_pipe('status');
372 while (<$fh>) { ... }
373 $r->command_close_pipe($fh, $ctx);
375 Note that you should not rely on whatever actually is in C<CTX>;
376 currently it is simply the command name but in future the context might
377 have more complicated structure.
379 =cut
381 sub command_close_pipe {
382 my ($self, $fh, $ctx) = _maybe_self(@_);
383 $ctx ||= '<unknown>';
384 _cmd_close($fh, $ctx);
387 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
389 Execute the given C<COMMAND> in the same way as command_output_pipe()
390 does but return both an input pipe filehandle and an output pipe filehandle.
392 The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>.
393 See C<command_close_bidi_pipe()> for details.
395 =cut
397 sub command_bidi_pipe {
398 my ($pid, $in, $out);
399 $pid = open2($in, $out, 'git', @_);
400 return ($pid, $in, $out, join(' ', @_));
403 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
405 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
406 checking whether the command finished successfully. The optional C<CTX>
407 argument is required if you want to see the command name in the error message,
408 and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
411 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
412 print "000000000\n" $out;
413 while (<$in>) { ... }
414 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
416 Note that you should not rely on whatever actually is in C<CTX>;
417 currently it is simply the command name but in future the context might
418 have more complicated structure.
420 =cut
422 sub command_close_bidi_pipe {
423 local $?;
424 my ($pid, $in, $out, $ctx) = @_;
425 foreach my $fh ($in, $out) {
426 unless (close $fh) {
427 if ($!) {
428 carp "error closing pipe: $!";
429 } elsif ($? >> 8) {
430 throw Git::Error::Command($ctx, $? >>8);
435 waitpid $pid, 0;
437 if ($? >> 8) {
438 throw Git::Error::Command($ctx, $? >>8);
443 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
445 Execute the given C<COMMAND> in the same way as command() does but do not
446 capture the command output - the standard output is not redirected and goes
447 to the standard output of the caller application.
449 While the method is called command_noisy(), you might want to as well use
450 it for the most silent Git commands which you know will never pollute your
451 stdout but you want to avoid the overhead of the pipe setup when calling them.
453 The function returns only after the command has finished running.
455 =cut
457 sub command_noisy {
458 my ($self, $cmd, @args) = _maybe_self(@_);
459 _check_valid_cmd($cmd);
461 my $pid = fork;
462 if (not defined $pid) {
463 throw Error::Simple("fork failed: $!");
464 } elsif ($pid == 0) {
465 _cmd_exec($self, $cmd, @args);
467 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
468 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
473 =item version ()
475 Return the Git version in use.
477 =cut
479 sub version {
480 my $verstr = command_oneline('--version');
481 $verstr =~ s/^git version //;
482 $verstr;
486 =item exec_path ()
488 Return path to the Git sub-command executables (the same as
489 C<git --exec-path>). Useful mostly only internally.
491 =cut
493 sub exec_path { command_oneline('--exec-path') }
496 =item html_path ()
498 Return path to the Git html documentation (the same as
499 C<git --html-path>). Useful mostly only internally.
501 =cut
503 sub html_path { command_oneline('--html-path') }
506 =item repo_path ()
508 Return path to the git repository. Must be called on a repository instance.
510 =cut
512 sub repo_path { $_[0]->{opts}->{Repository} }
515 =item wc_path ()
517 Return path to the working copy. Must be called on a repository instance.
519 =cut
521 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
524 =item wc_subdir ()
526 Return path to the subdirectory inside of a working copy. Must be called
527 on a repository instance.
529 =cut
531 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
534 =item wc_chdir ( SUBDIR )
536 Change the working copy subdirectory to work within. The C<SUBDIR> is
537 relative to the working copy root directory (not the current subdirectory).
538 Must be called on a repository instance attached to a working copy
539 and the directory must exist.
541 =cut
543 sub wc_chdir {
544 my ($self, $subdir) = @_;
545 $self->wc_path()
546 or throw Error::Simple("bare repository");
548 -d $self->wc_path().'/'.$subdir
549 or throw Error::Simple("subdir not found: $subdir $!");
550 # Of course we will not "hold" the subdirectory so anyone
551 # can delete it now and we will never know. But at least we tried.
553 $self->{opts}->{WorkingSubdir} = $subdir;
557 =item config ( VARIABLE )
559 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
560 does. In scalar context requires the variable to be set only one time
561 (exception is thrown otherwise), in array context returns allows the
562 variable to be set multiple times and returns all the values.
564 This currently wraps command('config') so it is not so fast.
566 =cut
568 sub config {
569 my ($self, $var) = _maybe_self(@_);
571 try {
572 my @cmd = ('config');
573 unshift @cmd, $self if $self;
574 if (wantarray) {
575 return command(@cmd, '--get-all', $var);
576 } else {
577 return command_oneline(@cmd, '--get', $var);
579 } catch Git::Error::Command with {
580 my $E = shift;
581 if ($E->value() == 1) {
582 # Key not found.
583 return;
584 } else {
585 throw $E;
591 =item config_bool ( VARIABLE )
593 Retrieve the bool configuration C<VARIABLE>. The return value
594 is usable as a boolean in perl (and C<undef> if it's not defined,
595 of course).
597 This currently wraps command('config') so it is not so fast.
599 =cut
601 sub config_bool {
602 my ($self, $var) = _maybe_self(@_);
604 try {
605 my @cmd = ('config', '--bool', '--get', $var);
606 unshift @cmd, $self if $self;
607 my $val = command_oneline(@cmd);
608 return undef unless defined $val;
609 return $val eq 'true';
610 } catch Git::Error::Command with {
611 my $E = shift;
612 if ($E->value() == 1) {
613 # Key not found.
614 return undef;
615 } else {
616 throw $E;
621 =item config_int ( VARIABLE )
623 Retrieve the integer configuration C<VARIABLE>. The return value
624 is simple decimal number. An optional value suffix of 'k', 'm',
625 or 'g' in the config file will cause the value to be multiplied
626 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
627 It would return C<undef> if configuration variable is not defined,
629 This currently wraps command('config') so it is not so fast.
631 =cut
633 sub config_int {
634 my ($self, $var) = _maybe_self(@_);
636 try {
637 my @cmd = ('config', '--int', '--get', $var);
638 unshift @cmd, $self if $self;
639 return command_oneline(@cmd);
640 } catch Git::Error::Command with {
641 my $E = shift;
642 if ($E->value() == 1) {
643 # Key not found.
644 return undef;
645 } else {
646 throw $E;
651 =item get_colorbool ( NAME )
653 Finds if color should be used for NAMEd operation from the configuration,
654 and returns boolean (true for "use color", false for "do not use color").
656 =cut
658 sub get_colorbool {
659 my ($self, $var) = @_;
660 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
661 my $use_color = $self->command_oneline('config', '--get-colorbool',
662 $var, $stdout_to_tty);
663 return ($use_color eq 'true');
666 =item get_color ( SLOT, COLOR )
668 Finds color for SLOT from the configuration, while defaulting to COLOR,
669 and returns the ANSI color escape sequence:
671 print $repo->get_color("color.interactive.prompt", "underline blue white");
672 print "some text";
673 print $repo->get_color("", "normal");
675 =cut
677 sub get_color {
678 my ($self, $slot, $default) = @_;
679 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
680 if (!defined $color) {
681 $color = "";
683 return $color;
686 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
688 This function returns a hashref of refs stored in a given remote repository.
689 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
690 contains the tag object while a C<refname^{}> entry gives the tagged objects.
692 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
693 argument; either an URL or a remote name (if called on a repository instance).
694 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
695 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
696 of strings containing a shell-like glob to further limit the refs returned in
697 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
698 argument.
700 This function may or may not be called on a repository instance. In the former
701 case, remote names as defined in the repository are recognized as repository
702 specifiers.
704 =cut
706 sub remote_refs {
707 my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
708 my @args;
709 if (ref $groups eq 'ARRAY') {
710 foreach (@$groups) {
711 if ($_ eq 'heads') {
712 push (@args, '--heads');
713 } elsif ($_ eq 'tags') {
714 push (@args, '--tags');
715 } else {
716 # Ignore unknown groups for future
717 # compatibility
721 push (@args, $repo);
722 if (ref $refglobs eq 'ARRAY') {
723 push (@args, @$refglobs);
726 my @self = $self ? ($self) : (); # Ultra trickery
727 my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
728 my %refs;
729 while (<$fh>) {
730 chomp;
731 my ($hash, $ref) = split(/\t/, $_, 2);
732 $refs{$ref} = $hash;
734 Git::command_close_pipe(@self, $fh, $ctx);
735 return \%refs;
739 =item ident ( TYPE | IDENTSTR )
741 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
743 This suite of functions retrieves and parses ident information, as stored
744 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
745 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
747 The C<ident> method retrieves the ident information from C<git var>
748 and either returns it as a scalar string or as an array with the fields parsed.
749 Alternatively, it can take a prepared ident string (e.g. from the commit
750 object) and just parse it.
752 C<ident_person> returns the person part of the ident - name and email;
753 it can take the same arguments as C<ident> or the array returned by C<ident>.
755 The synopsis is like:
757 my ($name, $email, $time_tz) = ident('author');
758 "$name <$email>" eq ident_person('author');
759 "$name <$email>" eq ident_person($name);
760 $time_tz =~ /^\d+ [+-]\d{4}$/;
762 =cut
764 sub ident {
765 my ($self, $type) = _maybe_self(@_);
766 my $identstr;
767 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
768 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
769 unshift @cmd, $self if $self;
770 $identstr = command_oneline(@cmd);
771 } else {
772 $identstr = $type;
774 if (wantarray) {
775 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
776 } else {
777 return $identstr;
781 sub ident_person {
782 my ($self, @ident) = _maybe_self(@_);
783 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
784 return "$ident[0] <$ident[1]>";
788 =item hash_object ( TYPE, FILENAME )
790 Compute the SHA1 object id of the given C<FILENAME> considering it is
791 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
793 The method can be called without any instance or on a specified Git repository,
794 it makes zero difference.
796 The function returns the SHA1 hash.
798 =cut
800 # TODO: Support for passing FILEHANDLE instead of FILENAME
801 sub hash_object {
802 my ($self, $type, $file) = _maybe_self(@_);
803 command_oneline('hash-object', '-t', $type, $file);
807 =item hash_and_insert_object ( FILENAME )
809 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
810 object database.
812 The function returns the SHA1 hash.
814 =cut
816 # TODO: Support for passing FILEHANDLE instead of FILENAME
817 sub hash_and_insert_object {
818 my ($self, $filename) = @_;
820 carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
822 $self->_open_hash_and_insert_object_if_needed();
823 my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
825 unless (print $out $filename, "\n") {
826 $self->_close_hash_and_insert_object();
827 throw Error::Simple("out pipe went bad");
830 chomp(my $hash = <$in>);
831 unless (defined($hash)) {
832 $self->_close_hash_and_insert_object();
833 throw Error::Simple("in pipe went bad");
836 return $hash;
839 sub _open_hash_and_insert_object_if_needed {
840 my ($self) = @_;
842 return if defined($self->{hash_object_pid});
844 ($self->{hash_object_pid}, $self->{hash_object_in},
845 $self->{hash_object_out}, $self->{hash_object_ctx}) =
846 command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
849 sub _close_hash_and_insert_object {
850 my ($self) = @_;
852 return unless defined($self->{hash_object_pid});
854 my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
856 command_close_bidi_pipe(@$self{@vars});
857 delete @$self{@vars};
860 =item cat_blob ( SHA1, FILEHANDLE )
862 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
863 returns the number of bytes printed.
865 =cut
867 sub cat_blob {
868 my ($self, $sha1, $fh) = @_;
870 $self->_open_cat_blob_if_needed();
871 my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
873 unless (print $out $sha1, "\n") {
874 $self->_close_cat_blob();
875 throw Error::Simple("out pipe went bad");
878 my $description = <$in>;
879 if ($description =~ / missing$/) {
880 carp "$sha1 doesn't exist in the repository";
881 return -1;
884 if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
885 carp "Unexpected result returned from git cat-file";
886 return -1;
889 my $size = $1;
891 my $blob;
892 my $bytesRead = 0;
894 while (1) {
895 my $bytesLeft = $size - $bytesRead;
896 last unless $bytesLeft;
898 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
899 my $read = read($in, $blob, $bytesToRead, $bytesRead);
900 unless (defined($read)) {
901 $self->_close_cat_blob();
902 throw Error::Simple("in pipe went bad");
905 $bytesRead += $read;
908 # Skip past the trailing newline.
909 my $newline;
910 my $read = read($in, $newline, 1);
911 unless (defined($read)) {
912 $self->_close_cat_blob();
913 throw Error::Simple("in pipe went bad");
915 unless ($read == 1 && $newline eq "\n") {
916 $self->_close_cat_blob();
917 throw Error::Simple("didn't find newline after blob");
920 unless (print $fh $blob) {
921 $self->_close_cat_blob();
922 throw Error::Simple("couldn't write to passed in filehandle");
925 return $size;
928 sub _open_cat_blob_if_needed {
929 my ($self) = @_;
931 return if defined($self->{cat_blob_pid});
933 ($self->{cat_blob_pid}, $self->{cat_blob_in},
934 $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
935 command_bidi_pipe(qw(cat-file --batch));
938 sub _close_cat_blob {
939 my ($self) = @_;
941 return unless defined($self->{cat_blob_pid});
943 my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
945 command_close_bidi_pipe(@$self{@vars});
946 delete @$self{@vars};
950 { # %TEMP_* Lexical Context
952 my (%TEMP_FILEMAP, %TEMP_FILES);
954 =item temp_acquire ( NAME )
956 Attempts to retreive the temporary file mapped to the string C<NAME>. If an
957 associated temp file has not been created this session or was closed, it is
958 created, cached, and set for autoflush and binmode.
960 Internally locks the file mapped to C<NAME>. This lock must be released with
961 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
962 to retrieve temporary files mapped to the same C<NAME> while still locked will
963 cause an error. This locking mechanism provides a weak guarantee and is not
964 threadsafe. It does provide some error checking to help prevent temp file refs
965 writing over one another.
967 In general, the L<File::Handle> returned should not be closed by consumers as
968 it defeats the purpose of this caching mechanism. If you need to close the temp
969 file handle, then you should use L<File::Temp> or another temp file faculty
970 directly. If a handle is closed and then requested again, then a warning will
971 issue.
973 =cut
975 sub temp_acquire {
976 my $temp_fd = _temp_cache(@_);
978 $TEMP_FILES{$temp_fd}{locked} = 1;
979 $temp_fd;
982 =item temp_release ( NAME )
984 =item temp_release ( FILEHANDLE )
986 Releases a lock acquired through C<temp_acquire()>. Can be called either with
987 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
988 referencing a locked temp file.
990 Warns if an attempt is made to release a file that is not locked.
992 The temp file will be truncated before being released. This can help to reduce
993 disk I/O where the system is smart enough to detect the truncation while data
994 is in the output buffers. Beware that after the temp file is released and
995 truncated, any operations on that file may fail miserably until it is
996 re-acquired. All contents are lost between each release and acquire mapped to
997 the same string.
999 =cut
1001 sub temp_release {
1002 my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1004 if (exists $TEMP_FILEMAP{$temp_fd}) {
1005 $temp_fd = $TEMP_FILES{$temp_fd};
1007 unless ($TEMP_FILES{$temp_fd}{locked}) {
1008 carp "Attempt to release temp file '",
1009 $temp_fd, "' that has not been locked";
1011 temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1013 $TEMP_FILES{$temp_fd}{locked} = 0;
1014 undef;
1017 sub _temp_cache {
1018 my ($self, $name) = _maybe_self(@_);
1020 _verify_require();
1022 my $temp_fd = \$TEMP_FILEMAP{$name};
1023 if (defined $$temp_fd and $$temp_fd->opened) {
1024 if ($TEMP_FILES{$$temp_fd}{locked}) {
1025 throw Error::Simple("Temp file with moniker '" .
1026 $name . "' already in use");
1028 } else {
1029 if (defined $$temp_fd) {
1030 # then we're here because of a closed handle.
1031 carp "Temp file '", $name,
1032 "' was closed. Opening replacement.";
1034 my $fname;
1036 my $tmpdir;
1037 if (defined $self) {
1038 $tmpdir = $self->repo_path();
1041 ($$temp_fd, $fname) = File::Temp->tempfile(
1042 'Git_XXXXXX', UNLINK => 1, DIR => $tmpdir,
1043 ) or throw Error::Simple("couldn't open new temp file");
1045 $$temp_fd->autoflush;
1046 binmode $$temp_fd;
1047 $TEMP_FILES{$$temp_fd}{fname} = $fname;
1049 $$temp_fd;
1052 sub _verify_require {
1053 eval { require File::Temp; require File::Spec; };
1054 $@ and throw Error::Simple($@);
1057 =item temp_reset ( FILEHANDLE )
1059 Truncates and resets the position of the C<FILEHANDLE>.
1061 =cut
1063 sub temp_reset {
1064 my ($self, $temp_fd) = _maybe_self(@_);
1066 truncate $temp_fd, 0
1067 or throw Error::Simple("couldn't truncate file");
1068 sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1069 or throw Error::Simple("couldn't seek to beginning of file");
1070 sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1071 or throw Error::Simple("expected file position to be reset");
1074 =item temp_path ( NAME )
1076 =item temp_path ( FILEHANDLE )
1078 Returns the filename associated with the given tempfile.
1080 =cut
1082 sub temp_path {
1083 my ($self, $temp_fd) = _maybe_self(@_);
1085 if (exists $TEMP_FILEMAP{$temp_fd}) {
1086 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1088 $TEMP_FILES{$temp_fd}{fname};
1091 sub END {
1092 unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
1095 } # %TEMP_* Lexical Context
1097 =back
1099 =head1 ERROR HANDLING
1101 All functions are supposed to throw Perl exceptions in case of errors.
1102 See the L<Error> module on how to catch those. Most exceptions are mere
1103 L<Error::Simple> instances.
1105 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1106 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1107 thrown when the external command returns an error code and contain the error
1108 code as well as access to the captured command's output. The exception class
1109 provides the usual C<stringify> and C<value> (command's exit code) methods and
1110 in addition also a C<cmd_output> method that returns either an array or a
1111 string with the captured command output (depending on the original function
1112 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1113 returns the command and its arguments (but without proper quoting).
1115 Note that the C<command_*_pipe()> functions cannot throw this exception since
1116 it has no idea whether the command failed or not. You will only find out
1117 at the time you C<close> the pipe; if you want to have that automated,
1118 use C<command_close_pipe()>, which can throw the exception.
1120 =cut
1123 package Git::Error::Command;
1125 @Git::Error::Command::ISA = qw(Error);
1127 sub new {
1128 my $self = shift;
1129 my $cmdline = '' . shift;
1130 my $value = 0 + shift;
1131 my $outputref = shift;
1132 my(@args) = ();
1134 local $Error::Depth = $Error::Depth + 1;
1136 push(@args, '-cmdline', $cmdline);
1137 push(@args, '-value', $value);
1138 push(@args, '-outputref', $outputref);
1140 $self->SUPER::new(-text => 'command returned error', @args);
1143 sub stringify {
1144 my $self = shift;
1145 my $text = $self->SUPER::stringify;
1146 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1149 sub cmdline {
1150 my $self = shift;
1151 $self->{'-cmdline'};
1154 sub cmd_output {
1155 my $self = shift;
1156 my $ref = $self->{'-outputref'};
1157 defined $ref or undef;
1158 if (ref $ref eq 'ARRAY') {
1159 return @$ref;
1160 } else { # SCALAR
1161 return $$ref;
1166 =over 4
1168 =item git_cmd_try { CODE } ERRMSG
1170 This magical statement will automatically catch any C<Git::Error::Command>
1171 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1172 on its lips; the message will have %s substituted for the command line
1173 and %d for the exit status. This statement is useful mostly for producing
1174 more user-friendly error messages.
1176 In case of no exception caught the statement returns C<CODE>'s return value.
1178 Note that this is the only auto-exported function.
1180 =cut
1182 sub git_cmd_try(&$) {
1183 my ($code, $errmsg) = @_;
1184 my @result;
1185 my $err;
1186 my $array = wantarray;
1187 try {
1188 if ($array) {
1189 @result = &$code;
1190 } else {
1191 $result[0] = &$code;
1193 } catch Git::Error::Command with {
1194 my $E = shift;
1195 $err = $errmsg;
1196 $err =~ s/\%s/$E->cmdline()/ge;
1197 $err =~ s/\%d/$E->value()/ge;
1198 # We can't croak here since Error.pm would mangle
1199 # that to Error::Simple.
1201 $err and croak $err;
1202 return $array ? @result : $result[0];
1206 =back
1208 =head1 COPYRIGHT
1210 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1212 This module is free software; it may be used, copied, modified
1213 and distributed under the terms of the GNU General Public Licence,
1214 either version 2, or (at your option) any later version.
1216 =cut
1219 # Take raw method argument list and return ($obj, @args) in case
1220 # the method was called upon an instance and (undef, @args) if
1221 # it was called directly.
1222 sub _maybe_self {
1223 UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
1226 # Check if the command id is something reasonable.
1227 sub _check_valid_cmd {
1228 my ($cmd) = @_;
1229 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1232 # Common backend for the pipe creators.
1233 sub _command_common_pipe {
1234 my $direction = shift;
1235 my ($self, @p) = _maybe_self(@_);
1236 my (%opts, $cmd, @args);
1237 if (ref $p[0]) {
1238 ($cmd, @args) = @{shift @p};
1239 %opts = ref $p[0] ? %{$p[0]} : @p;
1240 } else {
1241 ($cmd, @args) = @p;
1243 _check_valid_cmd($cmd);
1245 my $fh;
1246 if ($^O eq 'MSWin32') {
1247 # ActiveState Perl
1248 #defined $opts{STDERR} and
1249 # warn 'ignoring STDERR option - running w/ ActiveState';
1250 $direction eq '-|' or
1251 die 'input pipe for ActiveState not implemented';
1252 # the strange construction with *ACPIPE is just to
1253 # explain the tie below that we want to bind to
1254 # a handle class, not scalar. It is not known if
1255 # it is something specific to ActiveState Perl or
1256 # just a Perl quirk.
1257 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1258 $fh = *ACPIPE;
1260 } else {
1261 my $pid = open($fh, $direction);
1262 if (not defined $pid) {
1263 throw Error::Simple("open failed: $!");
1264 } elsif ($pid == 0) {
1265 if (defined $opts{STDERR}) {
1266 close STDERR;
1268 if ($opts{STDERR}) {
1269 open (STDERR, '>&', $opts{STDERR})
1270 or die "dup failed: $!";
1272 _cmd_exec($self, $cmd, @args);
1275 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1278 # When already in the subprocess, set up the appropriate state
1279 # for the given repository and execute the git command.
1280 sub _cmd_exec {
1281 my ($self, @args) = @_;
1282 if ($self) {
1283 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1284 $self->repo_path() and $self->wc_path()
1285 and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
1286 $self->wc_path() and chdir($self->wc_path());
1287 $self->wc_subdir() and chdir($self->wc_subdir());
1289 _execv_git_cmd(@args);
1290 die qq[exec "@args" failed: $!];
1293 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1294 # by searching for it at proper places.
1295 sub _execv_git_cmd { exec('git', @_); }
1297 # Close pipe to a subprocess.
1298 sub _cmd_close {
1299 my ($fh, $ctx) = @_;
1300 if (not close $fh) {
1301 if ($!) {
1302 # It's just close, no point in fatalities
1303 carp "error closing pipe: $!";
1304 } elsif ($? >> 8) {
1305 # The caller should pepper this.
1306 throw Git::Error::Command($ctx, $? >> 8);
1308 # else we might e.g. closed a live stream; the command
1309 # dying of SIGPIPE would drive us here.
1314 sub DESTROY {
1315 my ($self) = @_;
1316 $self->_close_hash_and_insert_object();
1317 $self->_close_cat_blob();
1321 # Pipe implementation for ActiveState Perl.
1323 package Git::activestate_pipe;
1324 use strict;
1326 sub TIEHANDLE {
1327 my ($class, @params) = @_;
1328 # FIXME: This is probably horrible idea and the thing will explode
1329 # at the moment you give it arguments that require some quoting,
1330 # but I have no ActiveState clue... --pasky
1331 # Let's just hope ActiveState Perl does at least the quoting
1332 # correctly.
1333 my @data = qx{git @params};
1334 bless { i => 0, data => \@data }, $class;
1337 sub READLINE {
1338 my $self = shift;
1339 if ($self->{i} >= scalar @{$self->{data}}) {
1340 return undef;
1342 my $i = $self->{i};
1343 if (wantarray) {
1344 $self->{i} = $#{$self->{'data'}} + 1;
1345 return splice(@{$self->{'data'}}, $i);
1347 $self->{i} = $i + 1;
1348 return $self->{'data'}->[ $i ];
1351 sub CLOSE {
1352 my $self = shift;
1353 delete $self->{data};
1354 delete $self->{i};
1357 sub EOF {
1358 my $self = shift;
1359 return ($self->{i} >= scalar @{$self->{data}});
1363 1; # Famous last words