perl: call timegm and timelocal with 4-digit year
[git] / perl / Git.pm
1 =head1 NAME
2
3 Git - Perl interface to the Git version control system
4
5 =cut
6
7
8 package Git;
9
10 use 5.008;
11 use strict;
12
13
14 BEGIN {
15
16 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
17
18 # Totally unstable API.
19 $VERSION = '0.01';
20
21
22 =head1 SYNOPSIS
23
24   use Git;
25
26   my $version = Git::command_oneline('version');
27
28   git_cmd_try { Git::command_noisy('update-server-info') }
29               '%s failed w/ code %d';
30
31   my $repo = Git->repository (Directory => '/srv/git/cogito.git');
32
33
34   my @revs = $repo->command('rev-list', '--since=last monday', '--all');
35
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);
39
40   my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
41                                         STDERR => 0 );
42
43   my $sha1 = $repo->hash_and_insert_object('file.txt');
44   my $tempfile = tempfile();
45   my $size = $repo->cat_blob($sha1, $tempfile);
46
47 =cut
48
49
50 require Exporter;
51
52 @ISA = qw(Exporter);
53
54 @EXPORT = qw(git_cmd_try);
55
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);
66
67
68 =head1 DESCRIPTION
69
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.
75
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.
82
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.)
88
89 TODO: In the future, we might also do
90
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();
94
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).
99
100 =cut
101
102
103 use Carp qw(carp croak); # but croak is bad - throw instead
104 use Error qw(:try);
105 use Cwd qw(abs_path cwd);
106 use IPC::Open2 qw(open2);
107 use Fcntl qw(SEEK_SET SEEK_CUR);
108 use Time::Local qw(timegm);
109 }
110
111
112 =head1 CONSTRUCTORS
113
114 =over 4
115
116 =item repository ( OPTIONS )
117
118 =item repository ( DIRECTORY )
119
120 =item repository ()
121
122 Construct a new repository object.
123 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
124 Possible options are:
125
126 B<Repository> - Path to the Git repository.
127
128 B<WorkingCopy> - Path to the associated working copy; not strictly required
129 as many commands will happily crunch on a bare repository.
130
131 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
132 Just left undefined if you do not want to limit the scope of operations.
133
134 B<Directory> - Path to the Git working directory in its usual setup.
135 The C<.git> directory is searched in the directory and all the parent
136 directories; if found, C<WorkingCopy> is set to the directory containing
137 it and C<Repository> to the C<.git> directory itself. If no C<.git>
138 directory was found, the C<Directory> is assumed to be a bare repository,
139 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
140 If the C<$GIT_DIR> environment variable is set, things behave as expected
141 as well.
142
143 You should not use both C<Directory> and either of C<Repository> and
144 C<WorkingCopy> - the results of that are undefined.
145
146 Alternatively, a directory path may be passed as a single scalar argument
147 to the constructor; it is equivalent to setting only the C<Directory> option
148 field.
149
150 Calling the constructor with no options whatsoever is equivalent to
151 calling it with C<< Directory => '.' >>. In general, if you are building
152 a standard porcelain command, simply doing C<< Git->repository() >> should
153 do the right thing and setup the object to reflect exactly where the user
154 is right now.
155
156 =cut
157
158 sub repository {
159         my $class = shift;
160         my @args = @_;
161         my %opts = ();
162         my $self;
163
164         if (defined $args[0]) {
165                 if ($#args % 2 != 1) {
166                         # Not a hash.
167                         $#args == 0 or throw Error::Simple("bad usage");
168                         %opts = ( Directory => $args[0] );
169                 } else {
170                         %opts = @args;
171                 }
172         }
173
174         if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
175                 and not defined $opts{Directory}) {
176                 $opts{Directory} = '.';
177         }
178
179         if (defined $opts{Directory}) {
180                 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
181
182                 my $search = Git->repository(WorkingCopy => $opts{Directory});
183                 my $dir;
184                 try {
185                         $dir = $search->command_oneline(['rev-parse', '--git-dir'],
186                                                         STDERR => 0);
187                 } catch Git::Error::Command with {
188                         $dir = undef;
189                 };
190
191                 if ($dir) {
192                         _verify_require();
193                         File::Spec->file_name_is_absolute($dir) or $dir = $opts{Directory} . '/' . $dir;
194                         $opts{Repository} = abs_path($dir);
195
196                         # If --git-dir went ok, this shouldn't die either.
197                         my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
198                         $dir = abs_path($opts{Directory}) . '/';
199                         if ($prefix) {
200                                 if (substr($dir, -length($prefix)) ne $prefix) {
201                                         throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
202                                 }
203                                 substr($dir, -length($prefix)) = '';
204                         }
205                         $opts{WorkingCopy} = $dir;
206                         $opts{WorkingSubdir} = $prefix;
207
208                 } else {
209                         # A bare repository? Let's see...
210                         $dir = $opts{Directory};
211
212                         unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
213                                 # Mimic git-rev-parse --git-dir error message:
214                                 throw Error::Simple("fatal: Not a git repository: $dir");
215                         }
216                         my $search = Git->repository(Repository => $dir);
217                         try {
218                                 $search->command('symbolic-ref', 'HEAD');
219                         } catch Git::Error::Command with {
220                                 # Mimic git-rev-parse --git-dir error message:
221                                 throw Error::Simple("fatal: Not a git repository: $dir");
222                         }
223
224                         $opts{Repository} = abs_path($dir);
225                 }
226
227                 delete $opts{Directory};
228         }
229
230         $self = { opts => \%opts };
231         bless $self, $class;
232 }
233
234 =back
235
236 =head1 METHODS
237
238 =over 4
239
240 =item command ( COMMAND [, ARGUMENTS... ] )
241
242 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
243
244 Execute the given Git C<COMMAND> (specify it without the 'git-'
245 prefix), optionally with the specified extra C<ARGUMENTS>.
246
247 The second more elaborate form can be used if you want to further adjust
248 the command execution. Currently, only one option is supported:
249
250 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
251 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
252 it to be thrown away. If you want to process it, you can get it in a filehandle
253 you specify, but you must be extremely careful; if the error output is not
254 very short and you want to read it in the same process as where you called
255 C<command()>, you are set up for a nice deadlock!
256
257 The method can be called without any instance or on a specified Git repository
258 (in that case the command will be run in the repository context).
259
260 In scalar context, it returns all the command output in a single string
261 (verbatim).
262
263 In array context, it returns an array containing lines printed to the
264 command's stdout (without trailing newlines).
265
266 In both cases, the command's stdin and stderr are the same as the caller's.
267
268 =cut
269
270 sub command {
271         my ($fh, $ctx) = command_output_pipe(@_);
272
273         if (not defined wantarray) {
274                 # Nothing to pepper the possible exception with.
275                 _cmd_close($ctx, $fh);
276
277         } elsif (not wantarray) {
278                 local $/;
279                 my $text = <$fh>;
280                 try {
281                         _cmd_close($ctx, $fh);
282                 } catch Git::Error::Command with {
283                         # Pepper with the output:
284                         my $E = shift;
285                         $E->{'-outputref'} = \$text;
286                         throw $E;
287                 };
288                 return $text;
289
290         } else {
291                 my @lines = <$fh>;
292                 defined and chomp for @lines;
293                 try {
294                         _cmd_close($ctx, $fh);
295                 } catch Git::Error::Command with {
296                         my $E = shift;
297                         $E->{'-outputref'} = \@lines;
298                         throw $E;
299                 };
300                 return @lines;
301         }
302 }
303
304
305 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
306
307 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
308
309 Execute the given C<COMMAND> in the same way as command()
310 does but always return a scalar string containing the first line
311 of the command's standard output.
312
313 =cut
314
315 sub command_oneline {
316         my ($fh, $ctx) = command_output_pipe(@_);
317
318         my $line = <$fh>;
319         defined $line and chomp $line;
320         try {
321                 _cmd_close($ctx, $fh);
322         } catch Git::Error::Command with {
323                 # Pepper with the output:
324                 my $E = shift;
325                 $E->{'-outputref'} = \$line;
326                 throw $E;
327         };
328         return $line;
329 }
330
331
332 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
333
334 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
335
336 Execute the given C<COMMAND> in the same way as command()
337 does but return a pipe filehandle from which the command output can be
338 read.
339
340 The function can return C<($pipe, $ctx)> in array context.
341 See C<command_close_pipe()> for details.
342
343 =cut
344
345 sub command_output_pipe {
346         _command_common_pipe('-|', @_);
347 }
348
349
350 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
351
352 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
353
354 Execute the given C<COMMAND> in the same way as command_output_pipe()
355 does but return an input pipe filehandle instead; the command output
356 is not captured.
357
358 The function can return C<($pipe, $ctx)> in array context.
359 See C<command_close_pipe()> for details.
360
361 =cut
362
363 sub command_input_pipe {
364         _command_common_pipe('|-', @_);
365 }
366
367
368 =item command_close_pipe ( PIPE [, CTX ] )
369
370 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
371 whether the command finished successfully. The optional C<CTX> argument
372 is required if you want to see the command name in the error message,
373 and it is the second value returned by C<command_*_pipe()> when
374 called in array context. The call idiom is:
375
376         my ($fh, $ctx) = $r->command_output_pipe('status');
377         while (<$fh>) { ... }
378         $r->command_close_pipe($fh, $ctx);
379
380 Note that you should not rely on whatever actually is in C<CTX>;
381 currently it is simply the command name but in future the context might
382 have more complicated structure.
383
384 =cut
385
386 sub command_close_pipe {
387         my ($self, $fh, $ctx) = _maybe_self(@_);
388         $ctx ||= '<unknown>';
389         _cmd_close($ctx, $fh);
390 }
391
392 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
393
394 Execute the given C<COMMAND> in the same way as command_output_pipe()
395 does but return both an input pipe filehandle and an output pipe filehandle.
396
397 The function will return C<($pid, $pipe_in, $pipe_out, $ctx)>.
398 See C<command_close_bidi_pipe()> for details.
399
400 =cut
401
402 sub command_bidi_pipe {
403         my ($pid, $in, $out);
404         my ($self) = _maybe_self(@_);
405         local %ENV = %ENV;
406         my $cwd_save = undef;
407         if ($self) {
408                 shift;
409                 $cwd_save = cwd();
410                 _setup_git_cmd_env($self);
411         }
412         $pid = open2($in, $out, 'git', @_);
413         chdir($cwd_save) if $cwd_save;
414         return ($pid, $in, $out, join(' ', @_));
415 }
416
417 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
418
419 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
420 checking whether the command finished successfully. The optional C<CTX>
421 argument is required if you want to see the command name in the error message,
422 and it is the fourth value returned by C<command_bidi_pipe()>.  The call idiom
423 is:
424
425         my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
426         print $out "000000000\n";
427         while (<$in>) { ... }
428         $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
429
430 Note that you should not rely on whatever actually is in C<CTX>;
431 currently it is simply the command name but in future the context might
432 have more complicated structure.
433
434 C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to
435 calling this function.  This may be useful in a query-response type of
436 commands where caller first writes a query and later reads response, eg:
437
438         my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
439         print $out "000000000\n";
440         close $out;
441         while (<$in>) { ... }
442         $r->command_close_bidi_pipe($pid, $in, undef, $ctx);
443
444 This idiom may prevent potential dead locks caused by data sent to the output
445 pipe not being flushed and thus not reaching the executed command.
446
447 =cut
448
449 sub command_close_bidi_pipe {
450         local $?;
451         my ($self, $pid, $in, $out, $ctx) = _maybe_self(@_);
452         _cmd_close($ctx, (grep { defined } ($in, $out)));
453         waitpid $pid, 0;
454         if ($? >> 8) {
455                 throw Git::Error::Command($ctx, $? >>8);
456         }
457 }
458
459
460 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
461
462 Execute the given C<COMMAND> in the same way as command() does but do not
463 capture the command output - the standard output is not redirected and goes
464 to the standard output of the caller application.
465
466 While the method is called command_noisy(), you might want to as well use
467 it for the most silent Git commands which you know will never pollute your
468 stdout but you want to avoid the overhead of the pipe setup when calling them.
469
470 The function returns only after the command has finished running.
471
472 =cut
473
474 sub command_noisy {
475         my ($self, $cmd, @args) = _maybe_self(@_);
476         _check_valid_cmd($cmd);
477
478         my $pid = fork;
479         if (not defined $pid) {
480                 throw Error::Simple("fork failed: $!");
481         } elsif ($pid == 0) {
482                 _cmd_exec($self, $cmd, @args);
483         }
484         if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
485                 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
486         }
487 }
488
489
490 =item version ()
491
492 Return the Git version in use.
493
494 =cut
495
496 sub version {
497         my $verstr = command_oneline('--version');
498         $verstr =~ s/^git version //;
499         $verstr;
500 }
501
502
503 =item exec_path ()
504
505 Return path to the Git sub-command executables (the same as
506 C<git --exec-path>). Useful mostly only internally.
507
508 =cut
509
510 sub exec_path { command_oneline('--exec-path') }
511
512
513 =item html_path ()
514
515 Return path to the Git html documentation (the same as
516 C<git --html-path>). Useful mostly only internally.
517
518 =cut
519
520 sub html_path { command_oneline('--html-path') }
521
522
523 =item get_tz_offset ( TIME )
524
525 Return the time zone offset from GMT in the form +/-HHMM where HH is
526 the number of hours from GMT and MM is the number of minutes.  This is
527 the equivalent of what strftime("%z", ...) would provide on a GNU
528 platform.
529
530 If TIME is not supplied, the current local time is used.
531
532 =cut
533
534 sub get_tz_offset {
535         # some systems don't handle or mishandle %z, so be creative.
536         my $t = shift || time;
537         my @t = localtime($t);
538         $t[5] += 1900;
539         my $gm = timegm(@t);
540         my $sign = qw( + + - )[ $gm <=> $t ];
541         return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
542 }
543
544 =item get_record ( FILEHANDLE, INPUT_RECORD_SEPARATOR )
545
546 Read one record from FILEHANDLE delimited by INPUT_RECORD_SEPARATOR,
547 removing any trailing INPUT_RECORD_SEPARATOR.
548
549 =cut
550
551 sub get_record {
552         my ($fh, $rs) = @_;
553         local $/ = $rs;
554         my $rec = <$fh>;
555         chomp $rec if defined $rs;
556         $rec;
557 }
558
559 =item prompt ( PROMPT , ISPASSWORD  )
560
561 Query user C<PROMPT> and return answer from user.
562
563 Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying
564 the user. If no *_ASKPASS variable is set or an error occoured,
565 the terminal is tried as a fallback.
566 If C<ISPASSWORD> is set and true, the terminal disables echo.
567
568 =cut
569
570 sub prompt {
571         my ($prompt, $isPassword) = @_;
572         my $ret;
573         if (exists $ENV{'GIT_ASKPASS'}) {
574                 $ret = _prompt($ENV{'GIT_ASKPASS'}, $prompt);
575         }
576         if (!defined $ret && exists $ENV{'SSH_ASKPASS'}) {
577                 $ret = _prompt($ENV{'SSH_ASKPASS'}, $prompt);
578         }
579         if (!defined $ret) {
580                 print STDERR $prompt;
581                 STDERR->flush;
582                 if (defined $isPassword && $isPassword) {
583                         require Term::ReadKey;
584                         Term::ReadKey::ReadMode('noecho');
585                         $ret = '';
586                         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
587                                 last if $key =~ /[\012\015]/; # \n\r
588                                 $ret .= $key;
589                         }
590                         Term::ReadKey::ReadMode('restore');
591                         print STDERR "\n";
592                         STDERR->flush;
593                 } else {
594                         chomp($ret = <STDIN>);
595                 }
596         }
597         return $ret;
598 }
599
600 sub _prompt {
601         my ($askpass, $prompt) = @_;
602         return unless length $askpass;
603         $prompt =~ s/\n/ /g;
604         my $ret;
605         open my $fh, "-|", $askpass, $prompt or return;
606         $ret = <$fh>;
607         $ret =~ s/[\015\012]//g; # strip \r\n, chomp does not work on all systems (i.e. windows) as expected
608         close ($fh);
609         return $ret;
610 }
611
612 =item repo_path ()
613
614 Return path to the git repository. Must be called on a repository instance.
615
616 =cut
617
618 sub repo_path { $_[0]->{opts}->{Repository} }
619
620
621 =item wc_path ()
622
623 Return path to the working copy. Must be called on a repository instance.
624
625 =cut
626
627 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
628
629
630 =item wc_subdir ()
631
632 Return path to the subdirectory inside of a working copy. Must be called
633 on a repository instance.
634
635 =cut
636
637 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
638
639
640 =item wc_chdir ( SUBDIR )
641
642 Change the working copy subdirectory to work within. The C<SUBDIR> is
643 relative to the working copy root directory (not the current subdirectory).
644 Must be called on a repository instance attached to a working copy
645 and the directory must exist.
646
647 =cut
648
649 sub wc_chdir {
650         my ($self, $subdir) = @_;
651         $self->wc_path()
652                 or throw Error::Simple("bare repository");
653
654         -d $self->wc_path().'/'.$subdir
655                 or throw Error::Simple("subdir not found: $subdir $!");
656         # Of course we will not "hold" the subdirectory so anyone
657         # can delete it now and we will never know. But at least we tried.
658
659         $self->{opts}->{WorkingSubdir} = $subdir;
660 }
661
662
663 =item config ( VARIABLE )
664
665 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
666 does. In scalar context requires the variable to be set only one time
667 (exception is thrown otherwise), in array context returns allows the
668 variable to be set multiple times and returns all the values.
669
670 =cut
671
672 sub config {
673         return _config_common({}, @_);
674 }
675
676
677 =item config_bool ( VARIABLE )
678
679 Retrieve the bool configuration C<VARIABLE>. The return value
680 is usable as a boolean in perl (and C<undef> if it's not defined,
681 of course).
682
683 =cut
684
685 sub config_bool {
686         my $val = scalar _config_common({'kind' => '--bool'}, @_);
687
688         # Do not rewrite this as return (defined $val && $val eq 'true')
689         # as some callers do care what kind of falsehood they receive.
690         if (!defined $val) {
691                 return undef;
692         } else {
693                 return $val eq 'true';
694         }
695 }
696
697
698 =item config_path ( VARIABLE )
699
700 Retrieve the path configuration C<VARIABLE>. The return value
701 is an expanded path or C<undef> if it's not defined.
702
703 =cut
704
705 sub config_path {
706         return _config_common({'kind' => '--path'}, @_);
707 }
708
709
710 =item config_int ( VARIABLE )
711
712 Retrieve the integer configuration C<VARIABLE>. The return value
713 is simple decimal number.  An optional value suffix of 'k', 'm',
714 or 'g' in the config file will cause the value to be multiplied
715 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
716 It would return C<undef> if configuration variable is not defined.
717
718 =cut
719
720 sub config_int {
721         return scalar _config_common({'kind' => '--int'}, @_);
722 }
723
724 # Common subroutine to implement bulk of what the config* family of methods
725 # do. This currently wraps command('config') so it is not so fast.
726 sub _config_common {
727         my ($opts) = shift @_;
728         my ($self, $var) = _maybe_self(@_);
729
730         try {
731                 my @cmd = ('config', $opts->{'kind'} ? $opts->{'kind'} : ());
732                 unshift @cmd, $self if $self;
733                 if (wantarray) {
734                         return command(@cmd, '--get-all', $var);
735                 } else {
736                         return command_oneline(@cmd, '--get', $var);
737                 }
738         } catch Git::Error::Command with {
739                 my $E = shift;
740                 if ($E->value() == 1) {
741                         # Key not found.
742                         return;
743                 } else {
744                         throw $E;
745                 }
746         };
747 }
748
749 =item get_colorbool ( NAME )
750
751 Finds if color should be used for NAMEd operation from the configuration,
752 and returns boolean (true for "use color", false for "do not use color").
753
754 =cut
755
756 sub get_colorbool {
757         my ($self, $var) = @_;
758         my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
759         my $use_color = $self->command_oneline('config', '--get-colorbool',
760                                                $var, $stdout_to_tty);
761         return ($use_color eq 'true');
762 }
763
764 =item get_color ( SLOT, COLOR )
765
766 Finds color for SLOT from the configuration, while defaulting to COLOR,
767 and returns the ANSI color escape sequence:
768
769         print $repo->get_color("color.interactive.prompt", "underline blue white");
770         print "some text";
771         print $repo->get_color("", "normal");
772
773 =cut
774
775 sub get_color {
776         my ($self, $slot, $default) = @_;
777         my $color = $self->command_oneline('config', '--get-color', $slot, $default);
778         if (!defined $color) {
779                 $color = "";
780         }
781         return $color;
782 }
783
784 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
785
786 This function returns a hashref of refs stored in a given remote repository.
787 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
788 contains the tag object while a C<refname^{}> entry gives the tagged objects.
789
790 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
791 argument; either a URL or a remote name (if called on a repository instance).
792 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
793 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
794 of strings containing a shell-like glob to further limit the refs returned in
795 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
796 argument.
797
798 This function may or may not be called on a repository instance. In the former
799 case, remote names as defined in the repository are recognized as repository
800 specifiers.
801
802 =cut
803
804 sub remote_refs {
805         my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
806         my @args;
807         if (ref $groups eq 'ARRAY') {
808                 foreach (@$groups) {
809                         if ($_ eq 'heads') {
810                                 push (@args, '--heads');
811                         } elsif ($_ eq 'tags') {
812                                 push (@args, '--tags');
813                         } else {
814                                 # Ignore unknown groups for future
815                                 # compatibility
816                         }
817                 }
818         }
819         push (@args, $repo);
820         if (ref $refglobs eq 'ARRAY') {
821                 push (@args, @$refglobs);
822         }
823
824         my @self = $self ? ($self) : (); # Ultra trickery
825         my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
826         my %refs;
827         while (<$fh>) {
828                 chomp;
829                 my ($hash, $ref) = split(/\t/, $_, 2);
830                 $refs{$ref} = $hash;
831         }
832         Git::command_close_pipe(@self, $fh, $ctx);
833         return \%refs;
834 }
835
836
837 =item ident ( TYPE | IDENTSTR )
838
839 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
840
841 This suite of functions retrieves and parses ident information, as stored
842 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
843 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
844
845 The C<ident> method retrieves the ident information from C<git var>
846 and either returns it as a scalar string or as an array with the fields parsed.
847 Alternatively, it can take a prepared ident string (e.g. from the commit
848 object) and just parse it.
849
850 C<ident_person> returns the person part of the ident - name and email;
851 it can take the same arguments as C<ident> or the array returned by C<ident>.
852
853 The synopsis is like:
854
855         my ($name, $email, $time_tz) = ident('author');
856         "$name <$email>" eq ident_person('author');
857         "$name <$email>" eq ident_person($name);
858         $time_tz =~ /^\d+ [+-]\d{4}$/;
859
860 =cut
861
862 sub ident {
863         my ($self, $type) = _maybe_self(@_);
864         my $identstr;
865         if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
866                 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
867                 unshift @cmd, $self if $self;
868                 $identstr = command_oneline(@cmd);
869         } else {
870                 $identstr = $type;
871         }
872         if (wantarray) {
873                 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
874         } else {
875                 return $identstr;
876         }
877 }
878
879 sub ident_person {
880         my ($self, @ident) = _maybe_self(@_);
881         $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
882         return "$ident[0] <$ident[1]>";
883 }
884
885 =item parse_mailboxes
886
887 Return an array of mailboxes extracted from a string.
888
889 =cut
890
891 # Very close to Mail::Address's parser, but we still have minor
892 # differences in some cases (see t9000 for examples).
893 sub parse_mailboxes {
894         my $re_comment = qr/\((?:[^)]*)\)/;
895         my $re_quote = qr/"(?:[^\"\\]|\\.)*"/;
896         my $re_word = qr/(?:[^]["\s()<>:;@\\,.]|\\.)+/;
897
898         # divide the string in tokens of the above form
899         my $re_token = qr/(?:$re_quote|$re_word|$re_comment|\S)/;
900         my @tokens = map { $_ =~ /\s*($re_token)\s*/g } @_;
901         my $end_of_addr_seen = 0;
902
903         # add a delimiter to simplify treatment for the last mailbox
904         push @tokens, ",";
905
906         my (@addr_list, @phrase, @address, @comment, @buffer) = ();
907         foreach my $token (@tokens) {
908                 if ($token =~ /^[,;]$/) {
909                         # if buffer still contains undeterminated strings
910                         # append it at the end of @address or @phrase
911                         if ($end_of_addr_seen) {
912                                 push @phrase, @buffer;
913                         } else {
914                                 push @address, @buffer;
915                         }
916
917                         my $str_phrase = join ' ', @phrase;
918                         my $str_address = join '', @address;
919                         my $str_comment = join ' ', @comment;
920
921                         # quote are necessary if phrase contains
922                         # special characters
923                         if ($str_phrase =~ /[][()<>:;@\\,.\000-\037\177]/) {
924                                 $str_phrase =~ s/(^|[^\\])"/$1/g;
925                                 $str_phrase = qq["$str_phrase"];
926                         }
927
928                         # add "<>" around the address if necessary
929                         if ($str_address ne "" && $str_phrase ne "") {
930                                 $str_address = qq[<$str_address>];
931                         }
932
933                         my $str_mailbox = "$str_phrase $str_address $str_comment";
934                         $str_mailbox =~ s/^\s*|\s*$//g;
935                         push @addr_list, $str_mailbox if ($str_mailbox);
936
937                         @phrase = @address = @comment = @buffer = ();
938                         $end_of_addr_seen = 0;
939                 } elsif ($token =~ /^\(/) {
940                         push @comment, $token;
941                 } elsif ($token eq "<") {
942                         push @phrase, (splice @address), (splice @buffer);
943                 } elsif ($token eq ">") {
944                         $end_of_addr_seen = 1;
945                         push @address, (splice @buffer);
946                 } elsif ($token eq "@" && !$end_of_addr_seen) {
947                         push @address, (splice @buffer), "@";
948                 } else {
949                         push @buffer, $token;
950                 }
951         }
952
953         return @addr_list;
954 }
955
956 =item hash_object ( TYPE, FILENAME )
957
958 Compute the SHA1 object id of the given C<FILENAME> considering it is
959 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
960
961 The method can be called without any instance or on a specified Git repository,
962 it makes zero difference.
963
964 The function returns the SHA1 hash.
965
966 =cut
967
968 # TODO: Support for passing FILEHANDLE instead of FILENAME
969 sub hash_object {
970         my ($self, $type, $file) = _maybe_self(@_);
971         command_oneline('hash-object', '-t', $type, $file);
972 }
973
974
975 =item hash_and_insert_object ( FILENAME )
976
977 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
978 object database.
979
980 The function returns the SHA1 hash.
981
982 =cut
983
984 # TODO: Support for passing FILEHANDLE instead of FILENAME
985 sub hash_and_insert_object {
986         my ($self, $filename) = @_;
987
988         carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
989
990         $self->_open_hash_and_insert_object_if_needed();
991         my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
992
993         unless (print $out $filename, "\n") {
994                 $self->_close_hash_and_insert_object();
995                 throw Error::Simple("out pipe went bad");
996         }
997
998         chomp(my $hash = <$in>);
999         unless (defined($hash)) {
1000                 $self->_close_hash_and_insert_object();
1001                 throw Error::Simple("in pipe went bad");
1002         }
1003
1004         return $hash;
1005 }
1006
1007 sub _open_hash_and_insert_object_if_needed {
1008         my ($self) = @_;
1009
1010         return if defined($self->{hash_object_pid});
1011
1012         ($self->{hash_object_pid}, $self->{hash_object_in},
1013          $self->{hash_object_out}, $self->{hash_object_ctx}) =
1014                 $self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
1015 }
1016
1017 sub _close_hash_and_insert_object {
1018         my ($self) = @_;
1019
1020         return unless defined($self->{hash_object_pid});
1021
1022         my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
1023
1024         command_close_bidi_pipe(@$self{@vars});
1025         delete @$self{@vars};
1026 }
1027
1028 =item cat_blob ( SHA1, FILEHANDLE )
1029
1030 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
1031 returns the number of bytes printed.
1032
1033 =cut
1034
1035 sub cat_blob {
1036         my ($self, $sha1, $fh) = @_;
1037
1038         $self->_open_cat_blob_if_needed();
1039         my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
1040
1041         unless (print $out $sha1, "\n") {
1042                 $self->_close_cat_blob();
1043                 throw Error::Simple("out pipe went bad");
1044         }
1045
1046         my $description = <$in>;
1047         if ($description =~ / missing$/) {
1048                 carp "$sha1 doesn't exist in the repository";
1049                 return -1;
1050         }
1051
1052         if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
1053                 carp "Unexpected result returned from git cat-file";
1054                 return -1;
1055         }
1056
1057         my $size = $1;
1058
1059         my $blob;
1060         my $bytesLeft = $size;
1061
1062         while (1) {
1063                 last unless $bytesLeft;
1064
1065                 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
1066                 my $read = read($in, $blob, $bytesToRead);
1067                 unless (defined($read)) {
1068                         $self->_close_cat_blob();
1069                         throw Error::Simple("in pipe went bad");
1070                 }
1071                 unless (print $fh $blob) {
1072                         $self->_close_cat_blob();
1073                         throw Error::Simple("couldn't write to passed in filehandle");
1074                 }
1075                 $bytesLeft -= $read;
1076         }
1077
1078         # Skip past the trailing newline.
1079         my $newline;
1080         my $read = read($in, $newline, 1);
1081         unless (defined($read)) {
1082                 $self->_close_cat_blob();
1083                 throw Error::Simple("in pipe went bad");
1084         }
1085         unless ($read == 1 && $newline eq "\n") {
1086                 $self->_close_cat_blob();
1087                 throw Error::Simple("didn't find newline after blob");
1088         }
1089
1090         return $size;
1091 }
1092
1093 sub _open_cat_blob_if_needed {
1094         my ($self) = @_;
1095
1096         return if defined($self->{cat_blob_pid});
1097
1098         ($self->{cat_blob_pid}, $self->{cat_blob_in},
1099          $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
1100                 $self->command_bidi_pipe(qw(cat-file --batch));
1101 }
1102
1103 sub _close_cat_blob {
1104         my ($self) = @_;
1105
1106         return unless defined($self->{cat_blob_pid});
1107
1108         my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
1109
1110         command_close_bidi_pipe(@$self{@vars});
1111         delete @$self{@vars};
1112 }
1113
1114
1115 =item credential_read( FILEHANDLE )
1116
1117 Reads credential key-value pairs from C<FILEHANDLE>.  Reading stops at EOF or
1118 when an empty line is encountered.  Each line must be of the form C<key=value>
1119 with a non-empty key.  Function returns hash with all read values.  Any white
1120 space (other than new-line character) is preserved.
1121
1122 =cut
1123
1124 sub credential_read {
1125         my ($self, $reader) = _maybe_self(@_);
1126         my %credential;
1127         while (<$reader>) {
1128                 chomp;
1129                 if ($_ eq '') {
1130                         last;
1131                 } elsif (!/^([^=]+)=(.*)$/) {
1132                         throw Error::Simple("unable to parse git credential data:\n$_");
1133                 }
1134                 $credential{$1} = $2;
1135         }
1136         return %credential;
1137 }
1138
1139 =item credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
1140
1141 Writes credential key-value pairs from hash referenced by
1142 C<CREDENTIAL_HASHREF> to C<FILEHANDLE>.  Keys and values cannot contain
1143 new-lines or NUL bytes characters, and key cannot contain equal signs nor be
1144 empty (if they do Error::Simple is thrown).  Any white space is preserved.  If
1145 value for a key is C<undef>, it will be skipped.
1146
1147 If C<'url'> key exists it will be written first.  (All the other key-value
1148 pairs are written in sorted order but you should not depend on that).  Once
1149 all lines are written, an empty line is printed.
1150
1151 =cut
1152
1153 sub credential_write {
1154         my ($self, $writer, $credential) = _maybe_self(@_);
1155         my ($key, $value);
1156
1157         # Check if $credential is valid prior to writing anything
1158         while (($key, $value) = each %$credential) {
1159                 if (!defined $key || !length $key) {
1160                         throw Error::Simple("credential key empty or undefined");
1161                 } elsif ($key =~ /[=\n\0]/) {
1162                         throw Error::Simple("credential key contains invalid characters: $key");
1163                 } elsif (defined $value && $value =~ /[\n\0]/) {
1164                         throw Error::Simple("credential value for key=$key contains invalid characters: $value");
1165                 }
1166         }
1167
1168         for $key (sort {
1169                 # url overwrites other fields, so it must come first
1170                 return -1 if $a eq 'url';
1171                 return  1 if $b eq 'url';
1172                 return $a cmp $b;
1173         } keys %$credential) {
1174                 if (defined $credential->{$key}) {
1175                         print $writer $key, '=', $credential->{$key}, "\n";
1176                 }
1177         }
1178         print $writer "\n";
1179 }
1180
1181 sub _credential_run {
1182         my ($self, $credential, $op) = _maybe_self(@_);
1183         my ($pid, $reader, $writer, $ctx) = command_bidi_pipe('credential', $op);
1184
1185         credential_write $writer, $credential;
1186         close $writer;
1187
1188         if ($op eq "fill") {
1189                 %$credential = credential_read $reader;
1190         }
1191         if (<$reader>) {
1192                 throw Error::Simple("unexpected output from git credential $op response:\n$_\n");
1193         }
1194
1195         command_close_bidi_pipe($pid, $reader, undef, $ctx);
1196 }
1197
1198 =item credential( CREDENTIAL_HASHREF [, OPERATION ] )
1199
1200 =item credential( CREDENTIAL_HASHREF, CODE )
1201
1202 Executes C<git credential> for a given set of credentials and specified
1203 operation.  In both forms C<CREDENTIAL_HASHREF> needs to be a reference to
1204 a hash which stores credentials.  Under certain conditions the hash can
1205 change.
1206
1207 In the first form, C<OPERATION> can be C<'fill'>, C<'approve'> or C<'reject'>,
1208 and function will execute corresponding C<git credential> sub-command.  If
1209 it's omitted C<'fill'> is assumed.  In case of C<'fill'> the values stored in
1210 C<CREDENTIAL_HASHREF> will be changed to the ones returned by the C<git
1211 credential fill> command.  The usual usage would look something like:
1212
1213         my %cred = (
1214                 'protocol' => 'https',
1215                 'host' => 'example.com',
1216                 'username' => 'bob'
1217         );
1218         Git::credential \%cred;
1219         if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
1220                 Git::credential \%cred, 'approve';
1221                 ... do more stuff ...
1222         } else {
1223                 Git::credential \%cred, 'reject';
1224         }
1225
1226 In the second form, C<CODE> needs to be a reference to a subroutine.  The
1227 function will execute C<git credential fill> to fill the provided credential
1228 hash, then call C<CODE> with C<CREDENTIAL_HASHREF> as the sole argument.  If
1229 C<CODE>'s return value is defined, the function will execute C<git credential
1230 approve> (if return value yields true) or C<git credential reject> (if return
1231 value is false).  If the return value is undef, nothing at all is executed;
1232 this is useful, for example, if the credential could neither be verified nor
1233 rejected due to an unrelated network error.  The return value is the same as
1234 what C<CODE> returns.  With this form, the usage might look as follows:
1235
1236         if (Git::credential {
1237                 'protocol' => 'https',
1238                 'host' => 'example.com',
1239                 'username' => 'bob'
1240         }, sub {
1241                 my $cred = shift;
1242                 return !!try_to_authenticate($cred->{'username'},
1243                                              $cred->{'password'});
1244         }) {
1245                 ... do more stuff ...
1246         }
1247
1248 =cut
1249
1250 sub credential {
1251         my ($self, $credential, $op_or_code) = (_maybe_self(@_), 'fill');
1252
1253         if ('CODE' eq ref $op_or_code) {
1254                 _credential_run $credential, 'fill';
1255                 my $ret = $op_or_code->($credential);
1256                 if (defined $ret) {
1257                         _credential_run $credential, $ret ? 'approve' : 'reject';
1258                 }
1259                 return $ret;
1260         } else {
1261                 _credential_run $credential, $op_or_code;
1262         }
1263 }
1264
1265 { # %TEMP_* Lexical Context
1266
1267 my (%TEMP_FILEMAP, %TEMP_FILES);
1268
1269 =item temp_acquire ( NAME )
1270
1271 Attempts to retrieve the temporary file mapped to the string C<NAME>. If an
1272 associated temp file has not been created this session or was closed, it is
1273 created, cached, and set for autoflush and binmode.
1274
1275 Internally locks the file mapped to C<NAME>. This lock must be released with
1276 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
1277 to retrieve temporary files mapped to the same C<NAME> while still locked will
1278 cause an error. This locking mechanism provides a weak guarantee and is not
1279 threadsafe. It does provide some error checking to help prevent temp file refs
1280 writing over one another.
1281
1282 In general, the L<File::Handle> returned should not be closed by consumers as
1283 it defeats the purpose of this caching mechanism. If you need to close the temp
1284 file handle, then you should use L<File::Temp> or another temp file faculty
1285 directly. If a handle is closed and then requested again, then a warning will
1286 issue.
1287
1288 =cut
1289
1290 sub temp_acquire {
1291         my $temp_fd = _temp_cache(@_);
1292
1293         $TEMP_FILES{$temp_fd}{locked} = 1;
1294         $temp_fd;
1295 }
1296
1297 =item temp_is_locked ( NAME )
1298
1299 Returns true if the internal lock created by a previous C<temp_acquire()>
1300 call with C<NAME> is still in effect.
1301
1302 When temp_acquire is called on a C<NAME>, it internally locks the temporary
1303 file mapped to C<NAME>.  That lock will not be released until C<temp_release()>
1304 is called with either the original C<NAME> or the L<File::Handle> that was
1305 returned from the original call to temp_acquire.
1306
1307 Subsequent attempts to call C<temp_acquire()> with the same C<NAME> will fail
1308 unless there has been an intervening C<temp_release()> call for that C<NAME>
1309 (or its corresponding L<File::Handle> that was returned by the original
1310 C<temp_acquire()> call).
1311
1312 If true is returned by C<temp_is_locked()> for a C<NAME>, an attempt to
1313 C<temp_acquire()> the same C<NAME> will cause an error unless
1314 C<temp_release> is first called on that C<NAME> (or its corresponding
1315 L<File::Handle> that was returned by the original C<temp_acquire()> call).
1316
1317 =cut
1318
1319 sub temp_is_locked {
1320         my ($self, $name) = _maybe_self(@_);
1321         my $temp_fd = \$TEMP_FILEMAP{$name};
1322
1323         defined $$temp_fd && $$temp_fd->opened && $TEMP_FILES{$$temp_fd}{locked};
1324 }
1325
1326 =item temp_release ( NAME )
1327
1328 =item temp_release ( FILEHANDLE )
1329
1330 Releases a lock acquired through C<temp_acquire()>. Can be called either with
1331 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
1332 referencing a locked temp file.
1333
1334 Warns if an attempt is made to release a file that is not locked.
1335
1336 The temp file will be truncated before being released. This can help to reduce
1337 disk I/O where the system is smart enough to detect the truncation while data
1338 is in the output buffers. Beware that after the temp file is released and
1339 truncated, any operations on that file may fail miserably until it is
1340 re-acquired. All contents are lost between each release and acquire mapped to
1341 the same string.
1342
1343 =cut
1344
1345 sub temp_release {
1346         my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1347
1348         if (exists $TEMP_FILEMAP{$temp_fd}) {
1349                 $temp_fd = $TEMP_FILES{$temp_fd};
1350         }
1351         unless ($TEMP_FILES{$temp_fd}{locked}) {
1352                 carp "Attempt to release temp file '",
1353                         $temp_fd, "' that has not been locked";
1354         }
1355         temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1356
1357         $TEMP_FILES{$temp_fd}{locked} = 0;
1358         undef;
1359 }
1360
1361 sub _temp_cache {
1362         my ($self, $name) = _maybe_self(@_);
1363
1364         _verify_require();
1365
1366         my $temp_fd = \$TEMP_FILEMAP{$name};
1367         if (defined $$temp_fd and $$temp_fd->opened) {
1368                 if ($TEMP_FILES{$$temp_fd}{locked}) {
1369                         throw Error::Simple("Temp file with moniker '" .
1370                                 $name . "' already in use");
1371                 }
1372         } else {
1373                 if (defined $$temp_fd) {
1374                         # then we're here because of a closed handle.
1375                         carp "Temp file '", $name,
1376                                 "' was closed. Opening replacement.";
1377                 }
1378                 my $fname;
1379
1380                 my $tmpdir;
1381                 if (defined $self) {
1382                         $tmpdir = $self->repo_path();
1383                 }
1384
1385                 my $n = $name;
1386                 $n =~ s/\W/_/g; # no strange chars
1387
1388                 ($$temp_fd, $fname) = File::Temp::tempfile(
1389                         "Git_${n}_XXXXXX", UNLINK => 1, DIR => $tmpdir,
1390                         ) or throw Error::Simple("couldn't open new temp file");
1391
1392                 $$temp_fd->autoflush;
1393                 binmode $$temp_fd;
1394                 $TEMP_FILES{$$temp_fd}{fname} = $fname;
1395         }
1396         $$temp_fd;
1397 }
1398
1399 sub _verify_require {
1400         eval { require File::Temp; require File::Spec; };
1401         $@ and throw Error::Simple($@);
1402 }
1403
1404 =item temp_reset ( FILEHANDLE )
1405
1406 Truncates and resets the position of the C<FILEHANDLE>.
1407
1408 =cut
1409
1410 sub temp_reset {
1411         my ($self, $temp_fd) = _maybe_self(@_);
1412
1413         truncate $temp_fd, 0
1414                 or throw Error::Simple("couldn't truncate file");
1415         sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1416                 or throw Error::Simple("couldn't seek to beginning of file");
1417         sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1418                 or throw Error::Simple("expected file position to be reset");
1419 }
1420
1421 =item temp_path ( NAME )
1422
1423 =item temp_path ( FILEHANDLE )
1424
1425 Returns the filename associated with the given tempfile.
1426
1427 =cut
1428
1429 sub temp_path {
1430         my ($self, $temp_fd) = _maybe_self(@_);
1431
1432         if (exists $TEMP_FILEMAP{$temp_fd}) {
1433                 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1434         }
1435         $TEMP_FILES{$temp_fd}{fname};
1436 }
1437
1438 sub END {
1439         unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
1440 }
1441
1442 } # %TEMP_* Lexical Context
1443
1444 =item prefix_lines ( PREFIX, STRING [, STRING... ])
1445
1446 Prefixes lines in C<STRING> with C<PREFIX>.
1447
1448 =cut
1449
1450 sub prefix_lines {
1451         my $prefix = shift;
1452         my $string = join("\n", @_);
1453         $string =~ s/^/$prefix/mg;
1454         return $string;
1455 }
1456
1457 =item unquote_path ( PATH )
1458
1459 Unquote a quoted path containing c-escapes as returned by ls-files etc.
1460 when not using -z or when parsing the output of diff -u.
1461
1462 =cut
1463
1464 {
1465         my %cquote_map = (
1466                 "a" => chr(7),
1467                 "b" => chr(8),
1468                 "t" => chr(9),
1469                 "n" => chr(10),
1470                 "v" => chr(11),
1471                 "f" => chr(12),
1472                 "r" => chr(13),
1473                 "\\" => "\\",
1474                 "\042" => "\042",
1475         );
1476
1477         sub unquote_path {
1478                 local ($_) = @_;
1479                 my ($retval, $remainder);
1480                 if (!/^\042(.*)\042$/) {
1481                         return $_;
1482                 }
1483                 ($_, $retval) = ($1, "");
1484                 while (/^([^\\]*)\\(.*)$/) {
1485                         $remainder = $2;
1486                         $retval .= $1;
1487                         for ($remainder) {
1488                                 if (/^([0-3][0-7][0-7])(.*)$/) {
1489                                         $retval .= chr(oct($1));
1490                                         $_ = $2;
1491                                         last;
1492                                 }
1493                                 if (/^([\\\042abtnvfr])(.*)$/) {
1494                                         $retval .= $cquote_map{$1};
1495                                         $_ = $2;
1496                                         last;
1497                                 }
1498                                 # This is malformed
1499                                 throw Error::Simple("invalid quoted path $_[0]");
1500                         }
1501                         $_ = $remainder;
1502                 }
1503                 $retval .= $_;
1504                 return $retval;
1505         }
1506 }
1507
1508 =item get_comment_line_char ( )
1509
1510 Gets the core.commentchar configuration value.
1511 The value falls-back to '#' if core.commentchar is set to 'auto'.
1512
1513 =cut
1514
1515 sub get_comment_line_char {
1516         my $comment_line_char = config("core.commentchar") || '#';
1517         $comment_line_char = '#' if ($comment_line_char eq 'auto');
1518         $comment_line_char = '#' if (length($comment_line_char) != 1);
1519         return $comment_line_char;
1520 }
1521
1522 =item comment_lines ( STRING [, STRING... ])
1523
1524 Comments lines following core.commentchar configuration.
1525
1526 =cut
1527
1528 sub comment_lines {
1529         my $comment_line_char = get_comment_line_char;
1530         return prefix_lines("$comment_line_char ", @_);
1531 }
1532
1533 =back
1534
1535 =head1 ERROR HANDLING
1536
1537 All functions are supposed to throw Perl exceptions in case of errors.
1538 See the L<Error> module on how to catch those. Most exceptions are mere
1539 L<Error::Simple> instances.
1540
1541 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1542 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1543 thrown when the external command returns an error code and contain the error
1544 code as well as access to the captured command's output. The exception class
1545 provides the usual C<stringify> and C<value> (command's exit code) methods and
1546 in addition also a C<cmd_output> method that returns either an array or a
1547 string with the captured command output (depending on the original function
1548 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1549 returns the command and its arguments (but without proper quoting).
1550
1551 Note that the C<command_*_pipe()> functions cannot throw this exception since
1552 it has no idea whether the command failed or not. You will only find out
1553 at the time you C<close> the pipe; if you want to have that automated,
1554 use C<command_close_pipe()>, which can throw the exception.
1555
1556 =cut
1557
1558 {
1559         package Git::Error::Command;
1560
1561         @Git::Error::Command::ISA = qw(Error);
1562
1563         sub new {
1564                 my $self = shift;
1565                 my $cmdline = '' . shift;
1566                 my $value = 0 + shift;
1567                 my $outputref = shift;
1568                 my(@args) = ();
1569
1570                 local $Error::Depth = $Error::Depth + 1;
1571
1572                 push(@args, '-cmdline', $cmdline);
1573                 push(@args, '-value', $value);
1574                 push(@args, '-outputref', $outputref);
1575
1576                 $self->SUPER::new(-text => 'command returned error', @args);
1577         }
1578
1579         sub stringify {
1580                 my $self = shift;
1581                 my $text = $self->SUPER::stringify;
1582                 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1583         }
1584
1585         sub cmdline {
1586                 my $self = shift;
1587                 $self->{'-cmdline'};
1588         }
1589
1590         sub cmd_output {
1591                 my $self = shift;
1592                 my $ref = $self->{'-outputref'};
1593                 defined $ref or undef;
1594                 if (ref $ref eq 'ARRAY') {
1595                         return @$ref;
1596                 } else { # SCALAR
1597                         return $$ref;
1598                 }
1599         }
1600 }
1601
1602 =over 4
1603
1604 =item git_cmd_try { CODE } ERRMSG
1605
1606 This magical statement will automatically catch any C<Git::Error::Command>
1607 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1608 on its lips; the message will have %s substituted for the command line
1609 and %d for the exit status. This statement is useful mostly for producing
1610 more user-friendly error messages.
1611
1612 In case of no exception caught the statement returns C<CODE>'s return value.
1613
1614 Note that this is the only auto-exported function.
1615
1616 =cut
1617
1618 sub git_cmd_try(&$) {
1619         my ($code, $errmsg) = @_;
1620         my @result;
1621         my $err;
1622         my $array = wantarray;
1623         try {
1624                 if ($array) {
1625                         @result = &$code;
1626                 } else {
1627                         $result[0] = &$code;
1628                 }
1629         } catch Git::Error::Command with {
1630                 my $E = shift;
1631                 $err = $errmsg;
1632                 $err =~ s/\%s/$E->cmdline()/ge;
1633                 $err =~ s/\%d/$E->value()/ge;
1634                 # We can't croak here since Error.pm would mangle
1635                 # that to Error::Simple.
1636         };
1637         $err and croak $err;
1638         return $array ? @result : $result[0];
1639 }
1640
1641
1642 =back
1643
1644 =head1 COPYRIGHT
1645
1646 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1647
1648 This module is free software; it may be used, copied, modified
1649 and distributed under the terms of the GNU General Public Licence,
1650 either version 2, or (at your option) any later version.
1651
1652 =cut
1653
1654
1655 # Take raw method argument list and return ($obj, @args) in case
1656 # the method was called upon an instance and (undef, @args) if
1657 # it was called directly.
1658 sub _maybe_self {
1659         UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
1660 }
1661
1662 # Check if the command id is something reasonable.
1663 sub _check_valid_cmd {
1664         my ($cmd) = @_;
1665         $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1666 }
1667
1668 # Common backend for the pipe creators.
1669 sub _command_common_pipe {
1670         my $direction = shift;
1671         my ($self, @p) = _maybe_self(@_);
1672         my (%opts, $cmd, @args);
1673         if (ref $p[0]) {
1674                 ($cmd, @args) = @{shift @p};
1675                 %opts = ref $p[0] ? %{$p[0]} : @p;
1676         } else {
1677                 ($cmd, @args) = @p;
1678         }
1679         _check_valid_cmd($cmd);
1680
1681         my $fh;
1682         if ($^O eq 'MSWin32') {
1683                 # ActiveState Perl
1684                 #defined $opts{STDERR} and
1685                 #       warn 'ignoring STDERR option - running w/ ActiveState';
1686                 $direction eq '-|' or
1687                         die 'input pipe for ActiveState not implemented';
1688                 # the strange construction with *ACPIPE is just to
1689                 # explain the tie below that we want to bind to
1690                 # a handle class, not scalar. It is not known if
1691                 # it is something specific to ActiveState Perl or
1692                 # just a Perl quirk.
1693                 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1694                 $fh = *ACPIPE;
1695
1696         } else {
1697                 my $pid = open($fh, $direction);
1698                 if (not defined $pid) {
1699                         throw Error::Simple("open failed: $!");
1700                 } elsif ($pid == 0) {
1701                         if ($opts{STDERR}) {
1702                                 open (STDERR, '>&', $opts{STDERR})
1703                                         or die "dup failed: $!";
1704                         } elsif (defined $opts{STDERR}) {
1705                                 open (STDERR, '>', '/dev/null')
1706                                         or die "opening /dev/null failed: $!";
1707                         }
1708                         _cmd_exec($self, $cmd, @args);
1709                 }
1710         }
1711         return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1712 }
1713
1714 # When already in the subprocess, set up the appropriate state
1715 # for the given repository and execute the git command.
1716 sub _cmd_exec {
1717         my ($self, @args) = @_;
1718         _setup_git_cmd_env($self);
1719         _execv_git_cmd(@args);
1720         die qq[exec "@args" failed: $!];
1721 }
1722
1723 # set up the appropriate state for git command
1724 sub _setup_git_cmd_env {
1725         my $self = shift;
1726         if ($self) {
1727                 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1728                 $self->repo_path() and $self->wc_path()
1729                         and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
1730                 $self->wc_path() and chdir($self->wc_path());
1731                 $self->wc_subdir() and chdir($self->wc_subdir());
1732         }
1733 }
1734
1735 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1736 # by searching for it at proper places.
1737 sub _execv_git_cmd { exec('git', @_); }
1738
1739 # Close pipe to a subprocess.
1740 sub _cmd_close {
1741         my $ctx = shift @_;
1742         foreach my $fh (@_) {
1743                 if (close $fh) {
1744                         # nop
1745                 } elsif ($!) {
1746                         # It's just close, no point in fatalities
1747                         carp "error closing pipe: $!";
1748                 } elsif ($? >> 8) {
1749                         # The caller should pepper this.
1750                         throw Git::Error::Command($ctx, $? >> 8);
1751                 }
1752                 # else we might e.g. closed a live stream; the command
1753                 # dying of SIGPIPE would drive us here.
1754         }
1755 }
1756
1757
1758 sub DESTROY {
1759         my ($self) = @_;
1760         $self->_close_hash_and_insert_object();
1761         $self->_close_cat_blob();
1762 }
1763
1764
1765 # Pipe implementation for ActiveState Perl.
1766
1767 package Git::activestate_pipe;
1768 use strict;
1769
1770 sub TIEHANDLE {
1771         my ($class, @params) = @_;
1772         # FIXME: This is probably horrible idea and the thing will explode
1773         # at the moment you give it arguments that require some quoting,
1774         # but I have no ActiveState clue... --pasky
1775         # Let's just hope ActiveState Perl does at least the quoting
1776         # correctly.
1777         my @data = qx{git @params};
1778         bless { i => 0, data => \@data }, $class;
1779 }
1780
1781 sub READLINE {
1782         my $self = shift;
1783         if ($self->{i} >= scalar @{$self->{data}}) {
1784                 return undef;
1785         }
1786         my $i = $self->{i};
1787         if (wantarray) {
1788                 $self->{i} = $#{$self->{'data'}} + 1;
1789                 return splice(@{$self->{'data'}}, $i);
1790         }
1791         $self->{i} = $i + 1;
1792         return $self->{'data'}->[ $i ];
1793 }
1794
1795 sub CLOSE {
1796         my $self = shift;
1797         delete $self->{data};
1798         delete $self->{i};
1799 }
1800
1801 sub EOF {
1802         my $self = shift;
1803         return ($self->{i} >= scalar @{$self->{data}});
1804 }
1805
1806
1807 1; # Famous last words