Sync with 'maint'
[git/gitster.git] / perl / Git.pm
blob667152c6c6de6ee3ea819ff90ea8db059216ae8d
1 =head1 NAME
3 Git - Perl interface to the Git version control system
5 =cut
8 package Git;
10 use 5.008001;
11 use strict;
12 use warnings $ENV{GIT_PERL_FATAL_WARNINGS} ? qw(FATAL all) : ();
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 prompt
62 get_tz_offset get_record
63 credential credential_read credential_write
64 temp_acquire temp_is_locked temp_release temp_reset temp_path
65 unquote_path);
68 =head1 DESCRIPTION
70 This module provides Perl scripts easy way to interface the Git version control
71 system. The modules have an easy and well-tested way to call arbitrary Git
72 commands; in the future, the interface will also provide specialized methods
73 for doing easily operations which are not totally trivial to do over
74 the generic command interface.
76 While some commands can be executed outside of any context (e.g. 'version'
77 or 'init'), most operations require a repository context, which in practice
78 means getting an instance of the Git object using the repository() constructor.
79 (In the future, we will also get a new_repository() constructor.) All commands
80 called as methods of the object are then executed in the context of the
81 repository.
83 Part of the "repository state" is also information about path to the attached
84 working copy (unless you work with a bare repository). You can also navigate
85 inside of the working copy using the C<wc_chdir()> method. (Note that
86 the repository object is self-contained and will not change working directory
87 of your process.)
89 TODO: In the future, we might also do
91 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
92 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
93 my @refs = $remoterepo->refs();
95 Currently, the module merely wraps calls to external Git tools. In the future,
96 it will provide a much faster way to interact with Git by linking directly
97 to libgit. This should be completely opaque to the user, though (performance
98 increase notwithstanding).
100 =cut
103 sub carp { require Carp; goto &Carp::carp }
104 sub croak { require Carp; goto &Carp::croak }
105 use Git::LoadCPAN::Error qw(:try);
109 =head1 CONSTRUCTORS
111 =over 4
113 =item repository ( OPTIONS )
115 =item repository ( DIRECTORY )
117 =item repository ()
119 Construct a new repository object.
120 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
121 Possible options are:
123 B<Repository> - Path to the Git repository.
125 B<WorkingCopy> - Path to the associated working copy; not strictly required
126 as many commands will happily crunch on a bare repository.
128 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
129 Just left undefined if you do not want to limit the scope of operations.
131 B<Directory> - Path to the Git working directory in its usual setup.
132 The C<.git> directory is searched in the directory and all the parent
133 directories; if found, C<WorkingCopy> is set to the directory containing
134 it and C<Repository> to the C<.git> directory itself. If no C<.git>
135 directory was found, the C<Directory> is assumed to be a bare repository,
136 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
137 If the C<$GIT_DIR> environment variable is set, things behave as expected
138 as well.
140 You should not use both C<Directory> and either of C<Repository> and
141 C<WorkingCopy> - the results of that are undefined.
143 Alternatively, a directory path may be passed as a single scalar argument
144 to the constructor; it is equivalent to setting only the C<Directory> option
145 field.
147 Calling the constructor with no options whatsoever is equivalent to
148 calling it with C<< Directory => '.' >>. In general, if you are building
149 a standard porcelain command, simply doing C<< Git->repository() >> should
150 do the right thing and setup the object to reflect exactly where the user
151 is right now.
153 =cut
155 sub repository {
156 my $class = shift;
157 my @args = @_;
158 my %opts = ();
159 my $self;
161 if (defined $args[0]) {
162 if ($#args % 2 != 1) {
163 # Not a hash.
164 $#args == 0 or throw Error::Simple("bad usage");
165 %opts = ( Directory => $args[0] );
166 } else {
167 %opts = @args;
171 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
172 and not defined $opts{Directory}) {
173 $opts{Directory} = '.';
176 if (defined $opts{Directory}) {
177 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
179 my $search = Git->repository(WorkingCopy => $opts{Directory});
181 # This rev-parse will throw an exception if we're not in a
182 # repository, which is what we want, but it's kind of noisy.
183 # Ideally we'd capture stderr and relay it, but doing so is
184 # awkward without depending on it fitting in a pipe buffer. So
185 # we just reproduce a plausible error message ourselves.
186 my $out;
187 try {
188 # Note that "--is-bare-repository" must come first, as
189 # --git-dir output could contain newlines.
190 $out = $search->command([qw(rev-parse --is-bare-repository --absolute-git-dir)],
191 STDERR => 0);
192 } catch Git::Error::Command with {
193 throw Error::Simple("fatal: not a git repository: $opts{Directory}");
196 chomp $out;
197 my ($bare, $dir) = split /\n/, $out, 2;
199 # We know this is an absolute path, because we used
200 # --absolute-git-dir above.
201 $opts{Repository} = $dir;
203 if ($bare ne 'true') {
204 require Cwd;
205 # If --git-dir went ok, this shouldn't die either.
206 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
207 $dir = Cwd::abs_path($opts{Directory}) . '/';
208 if ($prefix) {
209 if (substr($dir, -length($prefix)) ne $prefix) {
210 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
212 substr($dir, -length($prefix)) = '';
214 $opts{WorkingCopy} = $dir;
215 $opts{WorkingSubdir} = $prefix;
219 delete $opts{Directory};
222 $self = { opts => \%opts };
223 bless $self, $class;
226 =back
228 =head1 METHODS
230 =over 4
232 =item command ( COMMAND [, ARGUMENTS... ] )
234 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
236 Execute the given Git C<COMMAND> (specify it without the 'git-'
237 prefix), optionally with the specified extra C<ARGUMENTS>.
239 The second more elaborate form can be used if you want to further adjust
240 the command execution. Currently, only one option is supported:
242 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
243 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
244 it to be thrown away. If you want to process it, you can get it in a filehandle
245 you specify, but you must be extremely careful; if the error output is not
246 very short and you want to read it in the same process as where you called
247 C<command()>, you are set up for a nice deadlock!
249 The method can be called without any instance or on a specified Git repository
250 (in that case the command will be run in the repository context).
252 In scalar context, it returns all the command output in a single string
253 (verbatim).
255 In array context, it returns an array containing lines printed to the
256 command's stdout (without trailing newlines).
258 In both cases, the command's stdin and stderr are the same as the caller's.
260 =cut
262 sub command {
263 my ($fh, $ctx) = command_output_pipe(@_);
265 if (not defined wantarray) {
266 # Nothing to pepper the possible exception with.
267 _cmd_close($ctx, $fh);
269 } elsif (not wantarray) {
270 local $/;
271 my $text = <$fh>;
272 try {
273 _cmd_close($ctx, $fh);
274 } catch Git::Error::Command with {
275 # Pepper with the output:
276 my $E = shift;
277 $E->{'-outputref'} = \$text;
278 throw $E;
280 return $text;
282 } else {
283 my @lines = <$fh>;
284 defined and chomp for @lines;
285 try {
286 _cmd_close($ctx, $fh);
287 } catch Git::Error::Command with {
288 my $E = shift;
289 $E->{'-outputref'} = \@lines;
290 throw $E;
292 return @lines;
297 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
299 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
301 Execute the given C<COMMAND> in the same way as command()
302 does but always return a scalar string containing the first line
303 of the command's standard output.
305 =cut
307 sub command_oneline {
308 my ($fh, $ctx) = command_output_pipe(@_);
310 my $line = <$fh>;
311 defined $line and chomp $line;
312 try {
313 _cmd_close($ctx, $fh);
314 } catch Git::Error::Command with {
315 # Pepper with the output:
316 my $E = shift;
317 $E->{'-outputref'} = \$line;
318 throw $E;
320 return $line;
324 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
326 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
328 Execute the given C<COMMAND> in the same way as command()
329 does but return a pipe filehandle from which the command output can be
330 read.
332 The function can return C<($pipe, $ctx)> in array context.
333 See C<command_close_pipe()> for details.
335 =cut
337 sub command_output_pipe {
338 _command_common_pipe('-|', @_);
342 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
344 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
346 Execute the given C<COMMAND> in the same way as command_output_pipe()
347 does but return an input pipe filehandle instead; the command output
348 is not captured.
350 The function can return C<($pipe, $ctx)> in array context.
351 See C<command_close_pipe()> for details.
353 =cut
355 sub command_input_pipe {
356 _command_common_pipe('|-', @_);
360 =item command_close_pipe ( PIPE [, CTX ] )
362 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
363 whether the command finished successfully. The optional C<CTX> argument
364 is required if you want to see the command name in the error message,
365 and it is the second value returned by C<command_*_pipe()> when
366 called in array context. The call idiom is:
368 my ($fh, $ctx) = $r->command_output_pipe('status');
369 while (<$fh>) { ... }
370 $r->command_close_pipe($fh, $ctx);
372 Note that you should not rely on whatever actually is in C<CTX>;
373 currently it is simply the command name but in future the context might
374 have more complicated structure.
376 =cut
378 sub command_close_pipe {
379 my ($self, $fh, $ctx) = _maybe_self(@_);
380 $ctx ||= '<unknown>';
381 _cmd_close($ctx, $fh);
384 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
386 Execute the given C<COMMAND> in the same way as command_output_pipe()
387 does but return both an input pipe filehandle and an output pipe filehandle.
389 The function will return C<($pid, $pipe_in, $pipe_out, $ctx)>.
390 See C<command_close_bidi_pipe()> for details.
392 =cut
394 sub command_bidi_pipe {
395 my ($pid, $in, $out);
396 my ($self) = _maybe_self(@_);
397 local %ENV = %ENV;
398 my $cwd_save = undef;
399 if ($self) {
400 shift;
401 require Cwd;
402 $cwd_save = Cwd::getcwd();
403 _setup_git_cmd_env($self);
405 require IPC::Open2;
406 $pid = IPC::Open2::open2($in, $out, 'git', @_);
407 chdir($cwd_save) if $cwd_save;
408 return ($pid, $in, $out, join(' ', @_));
411 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
413 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
414 checking whether the command finished successfully. The optional C<CTX>
415 argument is required if you want to see the command name in the error message,
416 and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
419 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe(qw(cat-file --batch-check));
420 print $out "000000000\n";
421 while (<$in>) { ... }
422 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
424 Note that you should not rely on whatever actually is in C<CTX>;
425 currently it is simply the command name but in future the context might
426 have more complicated structure.
428 C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to
429 calling this function. This may be useful in a query-response type of
430 commands where caller first writes a query and later reads response, eg:
432 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe(qw(cat-file --batch-check));
433 print $out "000000000\n";
434 close $out;
435 while (<$in>) { ... }
436 $r->command_close_bidi_pipe($pid, $in, undef, $ctx);
438 This idiom may prevent potential dead locks caused by data sent to the output
439 pipe not being flushed and thus not reaching the executed command.
441 =cut
443 sub command_close_bidi_pipe {
444 local $?;
445 my ($self, $pid, $in, $out, $ctx) = _maybe_self(@_);
446 _cmd_close($ctx, (grep { defined } ($in, $out)));
447 waitpid $pid, 0;
448 if ($? >> 8) {
449 throw Git::Error::Command($ctx, $? >>8);
454 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
456 Execute the given C<COMMAND> in the same way as command() does but do not
457 capture the command output - the standard output is not redirected and goes
458 to the standard output of the caller application.
460 While the method is called command_noisy(), you might want to as well use
461 it for the most silent Git commands which you know will never pollute your
462 stdout but you want to avoid the overhead of the pipe setup when calling them.
464 The function returns only after the command has finished running.
466 =cut
468 sub command_noisy {
469 my ($self, $cmd, @args) = _maybe_self(@_);
470 _check_valid_cmd($cmd);
472 my $pid = fork;
473 if (not defined $pid) {
474 throw Error::Simple("fork failed: $!");
475 } elsif ($pid == 0) {
476 _cmd_exec($self, $cmd, @args);
478 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
479 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
484 =item version ()
486 Return the Git version in use.
488 =cut
490 sub version {
491 my $verstr = command_oneline('--version');
492 $verstr =~ s/^git version //;
493 $verstr;
497 =item exec_path ()
499 Return path to the Git sub-command executables (the same as
500 C<git --exec-path>). Useful mostly only internally.
502 =cut
504 sub exec_path { command_oneline('--exec-path') }
507 =item html_path ()
509 Return path to the Git html documentation (the same as
510 C<git --html-path>). Useful mostly only internally.
512 =cut
514 sub html_path { command_oneline('--html-path') }
517 =item get_tz_offset ( TIME )
519 Return the time zone offset from GMT in the form +/-HHMM where HH is
520 the number of hours from GMT and MM is the number of minutes. This is
521 the equivalent of what strftime("%z", ...) would provide on a GNU
522 platform.
524 If TIME is not supplied, the current local time is used.
526 =cut
528 sub get_tz_offset {
529 # some systems don't handle or mishandle %z, so be creative.
530 my $t = shift || time;
531 my @t = localtime($t);
532 $t[5] += 1900;
533 require Time::Local;
534 my $gm = Time::Local::timegm(@t);
535 my $sign = qw( + + - )[ $gm <=> $t ];
536 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
539 =item get_record ( FILEHANDLE, INPUT_RECORD_SEPARATOR )
541 Read one record from FILEHANDLE delimited by INPUT_RECORD_SEPARATOR,
542 removing any trailing INPUT_RECORD_SEPARATOR.
544 =cut
546 sub get_record {
547 my ($fh, $rs) = @_;
548 local $/ = $rs;
549 my $rec = <$fh>;
550 chomp $rec if defined $rec;
551 $rec;
554 =item prompt ( PROMPT , ISPASSWORD )
556 Query user C<PROMPT> and return answer from user.
558 Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying
559 the user. If no *_ASKPASS variable is set or an error occurred,
560 the terminal is tried as a fallback.
561 If C<ISPASSWORD> is set and true, the terminal disables echo.
563 =cut
565 sub prompt {
566 my ($prompt, $isPassword) = @_;
567 my $ret;
568 if (exists $ENV{'GIT_ASKPASS'}) {
569 $ret = _prompt($ENV{'GIT_ASKPASS'}, $prompt);
571 if (!defined $ret && exists $ENV{'SSH_ASKPASS'}) {
572 $ret = _prompt($ENV{'SSH_ASKPASS'}, $prompt);
574 if (!defined $ret) {
575 print STDERR $prompt;
576 STDERR->flush;
577 if (defined $isPassword && $isPassword) {
578 require Term::ReadKey;
579 Term::ReadKey::ReadMode('noecho');
580 $ret = '';
581 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
582 last if $key =~ /[\012\015]/; # \n\r
583 $ret .= $key;
585 Term::ReadKey::ReadMode('restore');
586 print STDERR "\n";
587 STDERR->flush;
588 } else {
589 chomp($ret = <STDIN>);
592 return $ret;
595 sub _prompt {
596 my ($askpass, $prompt) = @_;
597 return unless length $askpass;
598 $prompt =~ s/\n/ /g;
599 my $ret;
600 open my $fh, "-|", $askpass, $prompt or return;
601 $ret = <$fh>;
602 $ret =~ s/[\015\012]//g; # strip \r\n, chomp does not work on all systems (i.e. windows) as expected
603 close ($fh);
604 return $ret;
607 =item repo_path ()
609 Return path to the git repository. Must be called on a repository instance.
611 =cut
613 sub repo_path { $_[0]->{opts}->{Repository} }
616 =item wc_path ()
618 Return path to the working copy. Must be called on a repository instance.
620 =cut
622 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
625 =item wc_subdir ()
627 Return path to the subdirectory inside of a working copy. Must be called
628 on a repository instance.
630 =cut
632 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
635 =item wc_chdir ( SUBDIR )
637 Change the working copy subdirectory to work within. The C<SUBDIR> is
638 relative to the working copy root directory (not the current subdirectory).
639 Must be called on a repository instance attached to a working copy
640 and the directory must exist.
642 =cut
644 sub wc_chdir {
645 my ($self, $subdir) = @_;
646 $self->wc_path()
647 or throw Error::Simple("bare repository");
649 -d $self->wc_path().'/'.$subdir
650 or throw Error::Simple("subdir not found: $subdir $!");
651 # Of course we will not "hold" the subdirectory so anyone
652 # can delete it now and we will never know. But at least we tried.
654 $self->{opts}->{WorkingSubdir} = $subdir;
658 =item config ( VARIABLE )
660 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
661 does. In scalar context requires the variable to be set only one time
662 (exception is thrown otherwise), in array context returns allows the
663 variable to be set multiple times and returns all the values.
665 =cut
667 sub config {
668 return _config_common({}, @_);
672 =item config_bool ( VARIABLE )
674 Retrieve the bool configuration C<VARIABLE>. The return value
675 is usable as a boolean in perl (and C<undef> if it's not defined,
676 of course).
678 =cut
680 sub config_bool {
681 my $val = scalar _config_common({'kind' => '--bool'}, @_);
683 # Do not rewrite this as return (defined $val && $val eq 'true')
684 # as some callers do care what kind of falsehood they receive.
685 if (!defined $val) {
686 return undef;
687 } else {
688 return $val eq 'true';
693 =item config_path ( VARIABLE )
695 Retrieve the path configuration C<VARIABLE>. The return value
696 is an expanded path or C<undef> if it's not defined.
698 =cut
700 sub config_path {
701 return _config_common({'kind' => '--path'}, @_);
705 =item config_int ( VARIABLE )
707 Retrieve the integer configuration C<VARIABLE>. The return value
708 is simple decimal number. An optional value suffix of 'k', 'm',
709 or 'g' in the config file will cause the value to be multiplied
710 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
711 It would return C<undef> if configuration variable is not defined.
713 =cut
715 sub config_int {
716 return scalar _config_common({'kind' => '--int'}, @_);
719 =item config_regexp ( RE )
721 Retrieve the list of configuration key names matching the regular
722 expression C<RE>. The return value is a list of strings matching
723 this regex.
725 =cut
727 sub config_regexp {
728 my ($self, $regex) = _maybe_self(@_);
729 try {
730 my @cmd = ('config', '--name-only', '--get-regexp', $regex);
731 unshift @cmd, $self if $self;
732 my @matches = command(@cmd);
733 return @matches;
734 } catch Git::Error::Command with {
735 my $E = shift;
736 if ($E->value() == 1) {
737 my @matches = ();
738 return @matches;
739 } else {
740 throw $E;
745 # Common subroutine to implement bulk of what the config* family of methods
746 # do. This currently wraps command('config') so it is not so fast.
747 sub _config_common {
748 my ($opts) = shift @_;
749 my ($self, $var) = _maybe_self(@_);
751 try {
752 my @cmd = ('config', $opts->{'kind'} ? $opts->{'kind'} : ());
753 unshift @cmd, $self if $self;
754 if (wantarray) {
755 return command(@cmd, '--get-all', $var);
756 } else {
757 return command_oneline(@cmd, '--get', $var);
759 } catch Git::Error::Command with {
760 my $E = shift;
761 if ($E->value() == 1) {
762 # Key not found.
763 return;
764 } else {
765 throw $E;
770 =item get_colorbool ( NAME )
772 Finds if color should be used for NAMEd operation from the configuration,
773 and returns boolean (true for "use color", false for "do not use color").
775 =cut
777 sub get_colorbool {
778 my ($self, $var) = @_;
779 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
780 my $use_color = $self->command_oneline('config', '--get-colorbool',
781 $var, $stdout_to_tty);
782 return ($use_color eq 'true');
785 =item get_color ( SLOT, COLOR )
787 Finds color for SLOT from the configuration, while defaulting to COLOR,
788 and returns the ANSI color escape sequence:
790 print $repo->get_color("color.interactive.prompt", "underline blue white");
791 print "some text";
792 print $repo->get_color("", "normal");
794 =cut
796 sub get_color {
797 my ($self, $slot, $default) = @_;
798 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
799 if (!defined $color) {
800 $color = "";
802 return $color;
805 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
807 This function returns a hashref of refs stored in a given remote repository.
808 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
809 contains the tag object while a C<refname^{}> entry gives the tagged objects.
811 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
812 argument; either a URL or a remote name (if called on a repository instance).
813 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
814 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
815 of strings containing a shell-like glob to further limit the refs returned in
816 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
817 argument.
819 This function may or may not be called on a repository instance. In the former
820 case, remote names as defined in the repository are recognized as repository
821 specifiers.
823 =cut
825 sub remote_refs {
826 my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
827 my @args;
828 if (ref $groups eq 'ARRAY') {
829 foreach (@$groups) {
830 if ($_ eq 'heads') {
831 push (@args, '--heads');
832 } elsif ($_ eq 'tags') {
833 push (@args, '--tags');
834 } else {
835 # Ignore unknown groups for future
836 # compatibility
840 push (@args, $repo);
841 if (ref $refglobs eq 'ARRAY') {
842 push (@args, @$refglobs);
845 my @self = $self ? ($self) : (); # Ultra trickery
846 my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
847 my %refs;
848 while (<$fh>) {
849 chomp;
850 my ($hash, $ref) = split(/\t/, $_, 2);
851 $refs{$ref} = $hash;
853 Git::command_close_pipe(@self, $fh, $ctx);
854 return \%refs;
858 =item ident ( TYPE | IDENTSTR )
860 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
862 This suite of functions retrieves and parses ident information, as stored
863 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
864 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
866 The C<ident> method retrieves the ident information from C<git var>
867 and either returns it as a scalar string or as an array with the fields parsed.
868 Alternatively, it can take a prepared ident string (e.g. from the commit
869 object) and just parse it.
871 C<ident_person> returns the person part of the ident - name and email;
872 it can take the same arguments as C<ident> or the array returned by C<ident>.
874 The synopsis is like:
876 my ($name, $email, $time_tz) = ident('author');
877 "$name <$email>" eq ident_person('author');
878 "$name <$email>" eq ident_person($name);
879 $time_tz =~ /^\d+ [+-]\d{4}$/;
881 =cut
883 sub ident {
884 my ($self, $type) = _maybe_self(@_);
885 my $identstr;
886 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
887 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
888 unshift @cmd, $self if $self;
889 $identstr = command_oneline(@cmd);
890 } else {
891 $identstr = $type;
893 if (wantarray) {
894 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
895 } else {
896 return $identstr;
900 sub ident_person {
901 my ($self, @ident) = _maybe_self(@_);
902 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
903 return "$ident[0] <$ident[1]>";
906 =item hash_object ( TYPE, FILENAME )
908 Compute the SHA1 object id of the given C<FILENAME> considering it is
909 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
911 The method can be called without any instance or on a specified Git repository,
912 it makes zero difference.
914 The function returns the SHA1 hash.
916 =cut
918 # TODO: Support for passing FILEHANDLE instead of FILENAME
919 sub hash_object {
920 my ($self, $type, $file) = _maybe_self(@_);
921 command_oneline('hash-object', '-t', $type, $file);
925 =item hash_and_insert_object ( FILENAME )
927 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
928 object database.
930 The function returns the SHA1 hash.
932 =cut
934 # TODO: Support for passing FILEHANDLE instead of FILENAME
935 sub hash_and_insert_object {
936 my ($self, $filename) = @_;
938 carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
940 $self->_open_hash_and_insert_object_if_needed();
941 my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
943 unless (print $out $filename, "\n") {
944 $self->_close_hash_and_insert_object();
945 throw Error::Simple("out pipe went bad");
948 chomp(my $hash = <$in>);
949 unless (defined($hash)) {
950 $self->_close_hash_and_insert_object();
951 throw Error::Simple("in pipe went bad");
954 return $hash;
957 sub _open_hash_and_insert_object_if_needed {
958 my ($self) = @_;
960 return if defined($self->{hash_object_pid});
962 ($self->{hash_object_pid}, $self->{hash_object_in},
963 $self->{hash_object_out}, $self->{hash_object_ctx}) =
964 $self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
967 sub _close_hash_and_insert_object {
968 my ($self) = @_;
970 return unless defined($self->{hash_object_pid});
972 my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
974 command_close_bidi_pipe(@$self{@vars});
975 delete @$self{@vars};
978 =item cat_blob ( SHA1, FILEHANDLE )
980 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
981 returns the number of bytes printed.
983 =cut
985 sub cat_blob {
986 my ($self, $sha1, $fh) = @_;
988 $self->_open_cat_blob_if_needed();
989 my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
991 unless (print $out $sha1, "\n") {
992 $self->_close_cat_blob();
993 throw Error::Simple("out pipe went bad");
996 my $description = <$in>;
997 if ($description =~ / missing$/) {
998 carp "$sha1 doesn't exist in the repository";
999 return -1;
1002 if ($description !~ /^[0-9a-fA-F]{40}(?:[0-9a-fA-F]{24})? \S+ (\d+)$/) {
1003 carp "Unexpected result returned from git cat-file";
1004 return -1;
1007 my $size = $1;
1009 my $blob;
1010 my $bytesLeft = $size;
1012 while (1) {
1013 last unless $bytesLeft;
1015 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
1016 my $read = read($in, $blob, $bytesToRead);
1017 unless (defined($read)) {
1018 $self->_close_cat_blob();
1019 throw Error::Simple("in pipe went bad");
1021 unless (print $fh $blob) {
1022 $self->_close_cat_blob();
1023 throw Error::Simple("couldn't write to passed in filehandle");
1025 $bytesLeft -= $read;
1028 # Skip past the trailing newline.
1029 my $newline;
1030 my $read = read($in, $newline, 1);
1031 unless (defined($read)) {
1032 $self->_close_cat_blob();
1033 throw Error::Simple("in pipe went bad");
1035 unless ($read == 1 && $newline eq "\n") {
1036 $self->_close_cat_blob();
1037 throw Error::Simple("didn't find newline after blob");
1040 return $size;
1043 sub _open_cat_blob_if_needed {
1044 my ($self) = @_;
1046 return if defined($self->{cat_blob_pid});
1048 ($self->{cat_blob_pid}, $self->{cat_blob_in},
1049 $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
1050 $self->command_bidi_pipe(qw(cat-file --batch));
1053 sub _close_cat_blob {
1054 my ($self) = @_;
1056 return unless defined($self->{cat_blob_pid});
1058 my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
1060 command_close_bidi_pipe(@$self{@vars});
1061 delete @$self{@vars};
1065 =item credential_read( FILEHANDLE )
1067 Reads credential key-value pairs from C<FILEHANDLE>. Reading stops at EOF or
1068 when an empty line is encountered. Each line must be of the form C<key=value>
1069 with a non-empty key. Function returns hash with all read values. Any white
1070 space (other than new-line character) is preserved.
1072 =cut
1074 sub credential_read {
1075 my ($self, $reader) = _maybe_self(@_);
1076 my %credential;
1077 while (<$reader>) {
1078 chomp;
1079 if ($_ eq '') {
1080 last;
1081 } elsif (!/^([^=]+)=(.*)$/) {
1082 throw Error::Simple("unable to parse git credential data:\n$_");
1084 $credential{$1} = $2;
1086 return %credential;
1089 =item credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
1091 Writes credential key-value pairs from hash referenced by
1092 C<CREDENTIAL_HASHREF> to C<FILEHANDLE>. Keys and values cannot contain
1093 new-lines or NUL bytes characters, and key cannot contain equal signs nor be
1094 empty (if they do Error::Simple is thrown). Any white space is preserved. If
1095 value for a key is C<undef>, it will be skipped.
1097 If C<'url'> key exists it will be written first. (All the other key-value
1098 pairs are written in sorted order but you should not depend on that). Once
1099 all lines are written, an empty line is printed.
1101 =cut
1103 sub credential_write {
1104 my ($self, $writer, $credential) = _maybe_self(@_);
1105 my ($key, $value);
1107 # Check if $credential is valid prior to writing anything
1108 while (($key, $value) = each %$credential) {
1109 if (!defined $key || !length $key) {
1110 throw Error::Simple("credential key empty or undefined");
1111 } elsif ($key =~ /[=\n\0]/) {
1112 throw Error::Simple("credential key contains invalid characters: $key");
1113 } elsif (defined $value && $value =~ /[\n\0]/) {
1114 throw Error::Simple("credential value for key=$key contains invalid characters: $value");
1118 for $key (sort {
1119 # url overwrites other fields, so it must come first
1120 return -1 if $a eq 'url';
1121 return 1 if $b eq 'url';
1122 return $a cmp $b;
1123 } keys %$credential) {
1124 if (defined $credential->{$key}) {
1125 print $writer $key, '=', $credential->{$key}, "\n";
1128 print $writer "\n";
1131 sub _credential_run {
1132 my ($self, $credential, $op) = _maybe_self(@_);
1133 my ($pid, $reader, $writer, $ctx) = command_bidi_pipe('credential', $op);
1135 credential_write $writer, $credential;
1136 close $writer;
1138 if ($op eq "fill") {
1139 %$credential = credential_read $reader;
1141 if (<$reader>) {
1142 throw Error::Simple("unexpected output from git credential $op response:\n$_\n");
1145 command_close_bidi_pipe($pid, $reader, undef, $ctx);
1148 =item credential( CREDENTIAL_HASHREF [, OPERATION ] )
1150 =item credential( CREDENTIAL_HASHREF, CODE )
1152 Executes C<git credential> for a given set of credentials and specified
1153 operation. In both forms C<CREDENTIAL_HASHREF> needs to be a reference to
1154 a hash which stores credentials. Under certain conditions the hash can
1155 change.
1157 In the first form, C<OPERATION> can be C<'fill'>, C<'approve'> or C<'reject'>,
1158 and function will execute corresponding C<git credential> sub-command. If
1159 it's omitted C<'fill'> is assumed. In case of C<'fill'> the values stored in
1160 C<CREDENTIAL_HASHREF> will be changed to the ones returned by the C<git
1161 credential fill> command. The usual usage would look something like:
1163 my %cred = (
1164 'protocol' => 'https',
1165 'host' => 'example.com',
1166 'username' => 'bob'
1168 Git::credential \%cred;
1169 if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
1170 Git::credential \%cred, 'approve';
1171 ... do more stuff ...
1172 } else {
1173 Git::credential \%cred, 'reject';
1176 In the second form, C<CODE> needs to be a reference to a subroutine. The
1177 function will execute C<git credential fill> to fill the provided credential
1178 hash, then call C<CODE> with C<CREDENTIAL_HASHREF> as the sole argument. If
1179 C<CODE>'s return value is defined, the function will execute C<git credential
1180 approve> (if return value yields true) or C<git credential reject> (if return
1181 value is false). If the return value is undef, nothing at all is executed;
1182 this is useful, for example, if the credential could neither be verified nor
1183 rejected due to an unrelated network error. The return value is the same as
1184 what C<CODE> returns. With this form, the usage might look as follows:
1186 if (Git::credential {
1187 'protocol' => 'https',
1188 'host' => 'example.com',
1189 'username' => 'bob'
1190 }, sub {
1191 my $cred = shift;
1192 return !!try_to_authenticate($cred->{'username'},
1193 $cred->{'password'});
1194 }) {
1195 ... do more stuff ...
1198 =cut
1200 sub credential {
1201 my ($self, $credential, $op_or_code) = (_maybe_self(@_), 'fill');
1203 if ('CODE' eq ref $op_or_code) {
1204 _credential_run $credential, 'fill';
1205 my $ret = $op_or_code->($credential);
1206 if (defined $ret) {
1207 _credential_run $credential, $ret ? 'approve' : 'reject';
1209 return $ret;
1210 } else {
1211 _credential_run $credential, $op_or_code;
1215 { # %TEMP_* Lexical Context
1217 my (%TEMP_FILEMAP, %TEMP_FILES);
1219 =item temp_acquire ( NAME )
1221 Attempts to retrieve the temporary file mapped to the string C<NAME>. If an
1222 associated temp file has not been created this session or was closed, it is
1223 created, cached, and set for autoflush and binmode.
1225 Internally locks the file mapped to C<NAME>. This lock must be released with
1226 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
1227 to retrieve temporary files mapped to the same C<NAME> while still locked will
1228 cause an error. This locking mechanism provides a weak guarantee and is not
1229 threadsafe. It does provide some error checking to help prevent temp file refs
1230 writing over one another.
1232 In general, the L<File::Handle> returned should not be closed by consumers as
1233 it defeats the purpose of this caching mechanism. If you need to close the temp
1234 file handle, then you should use L<File::Temp> or another temp file faculty
1235 directly. If a handle is closed and then requested again, then a warning will
1236 issue.
1238 =cut
1240 sub temp_acquire {
1241 my $temp_fd = _temp_cache(@_);
1243 $TEMP_FILES{$temp_fd}{locked} = 1;
1244 $temp_fd;
1247 =item temp_is_locked ( NAME )
1249 Returns true if the internal lock created by a previous C<temp_acquire()>
1250 call with C<NAME> is still in effect.
1252 When temp_acquire is called on a C<NAME>, it internally locks the temporary
1253 file mapped to C<NAME>. That lock will not be released until C<temp_release()>
1254 is called with either the original C<NAME> or the L<File::Handle> that was
1255 returned from the original call to temp_acquire.
1257 Subsequent attempts to call C<temp_acquire()> with the same C<NAME> will fail
1258 unless there has been an intervening C<temp_release()> call for that C<NAME>
1259 (or its corresponding L<File::Handle> that was returned by the original
1260 C<temp_acquire()> call).
1262 If true is returned by C<temp_is_locked()> for a C<NAME>, an attempt to
1263 C<temp_acquire()> the same C<NAME> will cause an error unless
1264 C<temp_release> is first called on that C<NAME> (or its corresponding
1265 L<File::Handle> that was returned by the original C<temp_acquire()> call).
1267 =cut
1269 sub temp_is_locked {
1270 my ($self, $name) = _maybe_self(@_);
1271 my $temp_fd = \$TEMP_FILEMAP{$name};
1273 defined $$temp_fd && $$temp_fd->opened && $TEMP_FILES{$$temp_fd}{locked};
1276 =item temp_release ( NAME )
1278 =item temp_release ( FILEHANDLE )
1280 Releases a lock acquired through C<temp_acquire()>. Can be called either with
1281 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
1282 referencing a locked temp file.
1284 Warns if an attempt is made to release a file that is not locked.
1286 The temp file will be truncated before being released. This can help to reduce
1287 disk I/O where the system is smart enough to detect the truncation while data
1288 is in the output buffers. Beware that after the temp file is released and
1289 truncated, any operations on that file may fail miserably until it is
1290 re-acquired. All contents are lost between each release and acquire mapped to
1291 the same string.
1293 =cut
1295 sub temp_release {
1296 my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1298 if (exists $TEMP_FILEMAP{$temp_fd}) {
1299 $temp_fd = $TEMP_FILES{$temp_fd};
1301 unless ($TEMP_FILES{$temp_fd}{locked}) {
1302 carp "Attempt to release temp file '",
1303 $temp_fd, "' that has not been locked";
1305 temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1307 $TEMP_FILES{$temp_fd}{locked} = 0;
1308 undef;
1311 sub _temp_cache {
1312 my ($self, $name) = _maybe_self(@_);
1314 my $temp_fd = \$TEMP_FILEMAP{$name};
1315 if (defined $$temp_fd and $$temp_fd->opened) {
1316 if ($TEMP_FILES{$$temp_fd}{locked}) {
1317 throw Error::Simple("Temp file with moniker '" .
1318 $name . "' already in use");
1320 } else {
1321 if (defined $$temp_fd) {
1322 # then we're here because of a closed handle.
1323 carp "Temp file '", $name,
1324 "' was closed. Opening replacement.";
1326 my $fname;
1328 my $tmpdir;
1329 if (defined $self) {
1330 $tmpdir = $self->repo_path();
1333 my $n = $name;
1334 $n =~ s/\W/_/g; # no strange chars
1336 require File::Temp;
1337 ($$temp_fd, $fname) = File::Temp::tempfile(
1338 "Git_${n}_XXXXXX", UNLINK => 1, DIR => $tmpdir,
1339 ) or throw Error::Simple("couldn't open new temp file");
1341 $$temp_fd->autoflush;
1342 binmode $$temp_fd;
1343 $TEMP_FILES{$$temp_fd}{fname} = $fname;
1345 $$temp_fd;
1348 =item temp_reset ( FILEHANDLE )
1350 Truncates and resets the position of the C<FILEHANDLE>.
1352 =cut
1354 sub temp_reset {
1355 my ($self, $temp_fd) = _maybe_self(@_);
1357 truncate $temp_fd, 0
1358 or throw Error::Simple("couldn't truncate file");
1359 sysseek($temp_fd, 0, Fcntl::SEEK_SET()) and seek($temp_fd, 0, Fcntl::SEEK_SET())
1360 or throw Error::Simple("couldn't seek to beginning of file");
1361 sysseek($temp_fd, 0, Fcntl::SEEK_CUR()) == 0 and tell($temp_fd) == 0
1362 or throw Error::Simple("expected file position to be reset");
1365 =item temp_path ( NAME )
1367 =item temp_path ( FILEHANDLE )
1369 Returns the filename associated with the given tempfile.
1371 =cut
1373 sub temp_path {
1374 my ($self, $temp_fd) = _maybe_self(@_);
1376 if (exists $TEMP_FILEMAP{$temp_fd}) {
1377 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1379 $TEMP_FILES{$temp_fd}{fname};
1382 sub END {
1383 unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
1386 } # %TEMP_* Lexical Context
1388 =item prefix_lines ( PREFIX, STRING [, STRING... ])
1390 Prefixes lines in C<STRING> with C<PREFIX>.
1392 =cut
1394 sub prefix_lines {
1395 my $prefix = shift;
1396 my $string = join("\n", @_);
1397 $string =~ s/^/$prefix/mg;
1398 return $string;
1401 =item unquote_path ( PATH )
1403 Unquote a quoted path containing c-escapes as returned by ls-files etc.
1404 when not using -z or when parsing the output of diff -u.
1406 =cut
1409 my %cquote_map = (
1410 "a" => chr(7),
1411 "b" => chr(8),
1412 "t" => chr(9),
1413 "n" => chr(10),
1414 "v" => chr(11),
1415 "f" => chr(12),
1416 "r" => chr(13),
1417 "\\" => "\\",
1418 "\042" => "\042",
1421 sub unquote_path {
1422 local ($_) = @_;
1423 my ($retval, $remainder);
1424 if (!/^\042(.*)\042$/) {
1425 return $_;
1427 ($_, $retval) = ($1, "");
1428 while (/^([^\\]*)\\(.*)$/) {
1429 $remainder = $2;
1430 $retval .= $1;
1431 for ($remainder) {
1432 if (/^([0-3][0-7][0-7])(.*)$/) {
1433 $retval .= chr(oct($1));
1434 $_ = $2;
1435 last;
1437 if (/^([\\\042abtnvfr])(.*)$/) {
1438 $retval .= $cquote_map{$1};
1439 $_ = $2;
1440 last;
1442 # This is malformed
1443 throw Error::Simple("invalid quoted path $_[0]");
1445 $_ = $remainder;
1447 $retval .= $_;
1448 return $retval;
1452 =item get_comment_line_char ( )
1454 Gets the core.commentchar configuration value.
1455 The value falls-back to '#' if core.commentchar is set to 'auto'.
1457 =cut
1459 sub get_comment_line_char {
1460 my $comment_line_char = config("core.commentchar") || '#';
1461 $comment_line_char = '#' if ($comment_line_char eq 'auto');
1462 $comment_line_char = '#' if (length($comment_line_char) != 1);
1463 return $comment_line_char;
1466 =item comment_lines ( STRING [, STRING... ])
1468 Comments lines following core.commentchar configuration.
1470 =cut
1472 sub comment_lines {
1473 my $comment_line_char = get_comment_line_char;
1474 return prefix_lines("$comment_line_char ", @_);
1477 =back
1479 =head1 ERROR HANDLING
1481 All functions are supposed to throw Perl exceptions in case of errors.
1482 See the L<Error> module on how to catch those. Most exceptions are mere
1483 L<Error::Simple> instances.
1485 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1486 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1487 thrown when the external command returns an error code and contain the error
1488 code as well as access to the captured command's output. The exception class
1489 provides the usual C<stringify> and C<value> (command's exit code) methods and
1490 in addition also a C<cmd_output> method that returns either an array or a
1491 string with the captured command output (depending on the original function
1492 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1493 returns the command and its arguments (but without proper quoting).
1495 Note that the C<command_*_pipe()> functions cannot throw this exception since
1496 it has no idea whether the command failed or not. You will only find out
1497 at the time you C<close> the pipe; if you want to have that automated,
1498 use C<command_close_pipe()>, which can throw the exception.
1500 =cut
1503 package Git::Error::Command;
1505 @Git::Error::Command::ISA = qw(Error);
1507 sub new {
1508 my $self = shift;
1509 my $cmdline = '' . shift;
1510 my $value = 0 + shift;
1511 my $outputref = shift;
1512 my(@args) = ();
1514 local $Error::Depth = $Error::Depth + 1;
1516 push(@args, '-cmdline', $cmdline);
1517 push(@args, '-value', $value);
1518 push(@args, '-outputref', $outputref);
1520 $self->SUPER::new(-text => 'command returned error', @args);
1523 sub stringify {
1524 my $self = shift;
1525 my $text = $self->SUPER::stringify;
1526 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1529 sub cmdline {
1530 my $self = shift;
1531 $self->{'-cmdline'};
1534 sub cmd_output {
1535 my $self = shift;
1536 my $ref = $self->{'-outputref'};
1537 defined $ref or undef;
1538 if (ref $ref eq 'ARRAY') {
1539 return @$ref;
1540 } else { # SCALAR
1541 return $$ref;
1546 =over 4
1548 =item git_cmd_try { CODE } ERRMSG
1550 This magical statement will automatically catch any C<Git::Error::Command>
1551 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1552 on its lips; the message will have %s substituted for the command line
1553 and %d for the exit status. This statement is useful mostly for producing
1554 more user-friendly error messages.
1556 In case of no exception caught the statement returns C<CODE>'s return value.
1558 Note that this is the only auto-exported function.
1560 =cut
1562 sub git_cmd_try(&$) {
1563 my ($code, $errmsg) = @_;
1564 my @result;
1565 my $err;
1566 my $array = wantarray;
1567 try {
1568 if ($array) {
1569 @result = &$code;
1570 } else {
1571 $result[0] = &$code;
1573 } catch Git::Error::Command with {
1574 my $E = shift;
1575 $err = $errmsg;
1576 $err =~ s/\%s/$E->cmdline()/ge;
1577 $err =~ s/\%d/$E->value()/ge;
1578 # We can't croak here since Error.pm would mangle
1579 # that to Error::Simple.
1581 $err and croak $err;
1582 return $array ? @result : $result[0];
1586 =back
1588 =head1 COPYRIGHT
1590 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1592 This module is free software; it may be used, copied, modified
1593 and distributed under the terms of the GNU General Public Licence,
1594 either version 2, or (at your option) any later version.
1596 =cut
1599 # Take raw method argument list and return ($obj, @args) in case
1600 # the method was called upon an instance and (undef, @args) if
1601 # it was called directly.
1602 sub _maybe_self {
1603 UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
1606 # Check if the command id is something reasonable.
1607 sub _check_valid_cmd {
1608 my ($cmd) = @_;
1609 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1612 # Common backend for the pipe creators.
1613 sub _command_common_pipe {
1614 my $direction = shift;
1615 my ($self, @p) = _maybe_self(@_);
1616 my (%opts, $cmd, @args);
1617 if (ref $p[0]) {
1618 ($cmd, @args) = @{shift @p};
1619 %opts = ref $p[0] ? %{$p[0]} : @p;
1620 } else {
1621 ($cmd, @args) = @p;
1623 _check_valid_cmd($cmd);
1625 my $fh;
1626 if ($^O eq 'MSWin32') {
1627 # ActiveState Perl
1628 #defined $opts{STDERR} and
1629 # warn 'ignoring STDERR option - running w/ ActiveState';
1630 $direction eq '-|' or
1631 die 'input pipe for ActiveState not implemented';
1632 # the strange construction with *ACPIPE is just to
1633 # explain the tie below that we want to bind to
1634 # a handle class, not scalar. It is not known if
1635 # it is something specific to ActiveState Perl or
1636 # just a Perl quirk.
1637 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1638 $fh = *ACPIPE;
1640 } else {
1641 my $pid = open($fh, $direction);
1642 if (not defined $pid) {
1643 throw Error::Simple("open failed: $!");
1644 } elsif ($pid == 0) {
1645 if ($opts{STDERR}) {
1646 open (STDERR, '>&', $opts{STDERR})
1647 or die "dup failed: $!";
1648 } elsif (defined $opts{STDERR}) {
1649 open (STDERR, '>', '/dev/null')
1650 or die "opening /dev/null failed: $!";
1652 _cmd_exec($self, $cmd, @args);
1655 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1658 # When already in the subprocess, set up the appropriate state
1659 # for the given repository and execute the git command.
1660 sub _cmd_exec {
1661 my ($self, @args) = @_;
1662 _setup_git_cmd_env($self);
1663 _execv_git_cmd(@args);
1664 die qq[exec "@args" failed: $!];
1667 # set up the appropriate state for git command
1668 sub _setup_git_cmd_env {
1669 my $self = shift;
1670 if ($self) {
1671 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1672 $self->repo_path() and $self->wc_path()
1673 and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
1674 $self->wc_path() and chdir($self->wc_path());
1675 $self->wc_subdir() and chdir($self->wc_subdir());
1679 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1680 # by searching for it at proper places.
1681 sub _execv_git_cmd { exec('git', @_); }
1683 sub _is_sig {
1684 my ($v, $n) = @_;
1686 # We are avoiding a "use POSIX qw(SIGPIPE SIGABRT)" in the hot
1687 # Git.pm codepath.
1688 require POSIX;
1689 no strict 'refs';
1690 $v == *{"POSIX::$n"}->();
1693 # Close pipe to a subprocess.
1694 sub _cmd_close {
1695 my $ctx = shift @_;
1696 foreach my $fh (@_) {
1697 if (close $fh) {
1698 # nop
1699 } elsif ($!) {
1700 # It's just close, no point in fatalities
1701 carp "error closing pipe: $!";
1702 } elsif ($? >> 8) {
1703 # The caller should pepper this.
1704 throw Git::Error::Command($ctx, $? >> 8);
1705 } elsif ($? & 127 && _is_sig($? & 127, "SIGPIPE")) {
1706 # we might e.g. closed a live stream; the command
1707 # dying of SIGPIPE would drive us here.
1708 } elsif ($? & 127 && _is_sig($? & 127, "SIGABRT")) {
1709 die sprintf('BUG?: got SIGABRT ($? = %d, $? & 127 = %d) when closing pipe',
1710 $?, $? & 127);
1711 } elsif ($? & 127) {
1712 die sprintf('got signal ($? = %d, $? & 127 = %d) when closing pipe',
1713 $?, $? & 127);
1719 sub DESTROY {
1720 my ($self) = @_;
1721 $self->_close_hash_and_insert_object();
1722 $self->_close_cat_blob();
1726 # Pipe implementation for ActiveState Perl.
1728 package Git::activestate_pipe;
1730 sub TIEHANDLE {
1731 my ($class, @params) = @_;
1732 # FIXME: This is probably horrible idea and the thing will explode
1733 # at the moment you give it arguments that require some quoting,
1734 # but I have no ActiveState clue... --pasky
1735 # Let's just hope ActiveState Perl does at least the quoting
1736 # correctly.
1737 my @data = qx{git @params};
1738 bless { i => 0, data => \@data }, $class;
1741 sub READLINE {
1742 my $self = shift;
1743 if ($self->{i} >= scalar @{$self->{data}}) {
1744 return undef;
1746 my $i = $self->{i};
1747 if (wantarray) {
1748 $self->{i} = $#{$self->{'data'}} + 1;
1749 return splice(@{$self->{'data'}}, $i);
1751 $self->{i} = $i + 1;
1752 return $self->{'data'}->[ $i ];
1755 sub CLOSE {
1756 my $self = shift;
1757 delete $self->{data};
1758 delete $self->{i};
1761 sub EOF {
1762 my $self = shift;
1763 return ($self->{i} >= scalar @{$self->{data}});
1767 1; # Famous last words