Fix sizeof usage in get_permutations
[git/git.git] / perl / Git.pm
CommitLineData
b1edc53d
PB
1=head1 NAME
2
3Git - Perl interface to the Git version control system
4
5=cut
6
7
8package Git;
9
d48b2841 10use 5.008;
b1edc53d
PB
11use strict;
12
13
14BEGIN {
15
16our ($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
8b9150e3
PB
28 git_cmd_try { Git::command_noisy('update-server-info') }
29 '%s failed w/ code %d';
b1edc53d
PB
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
d79850e1 36 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
b1edc53d 37 my $lastrev = <$fh>; chomp $lastrev;
8b9150e3 38 $repo->command_close_pipe($fh, $c);
b1edc53d 39
d43ba468
PB
40 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
41 STDERR => 0 );
b1edc53d 42
7182530d
AR
43 my $sha1 = $repo->hash_and_insert_object('file.txt');
44 my $tempfile = tempfile();
45 my $size = $repo->cat_blob($sha1, $tempfile);
46
b1edc53d
PB
47=cut
48
49
50require Exporter;
51
52@ISA = qw(Exporter);
53
8b9150e3 54@EXPORT = qw(git_cmd_try);
b1edc53d
PB
55
56# Methods which can be called as standalone functions as well:
d79850e1
PB
57@EXPORT_OK = qw(command command_oneline command_noisy
58 command_output_pipe command_input_pipe command_close_pipe
d1a29af9 59 command_bidi_pipe command_close_bidi_pipe
89a56bfb 60 version exec_path html_path hash_object git_cmd_try
e41352b2 61 remote_refs
836ff95d 62 temp_acquire temp_release temp_reset temp_path);
b1edc53d
PB
63
64
65=head1 DESCRIPTION
66
67This module provides Perl scripts easy way to interface the Git version control
68system. The modules have an easy and well-tested way to call arbitrary Git
69commands; in the future, the interface will also provide specialized methods
70for doing easily operations which are not totally trivial to do over
71the generic command interface.
72
73While some commands can be executed outside of any context (e.g. 'version'
5c94f87e 74or 'init'), most operations require a repository context, which in practice
b1edc53d
PB
75means getting an instance of the Git object using the repository() constructor.
76(In the future, we will also get a new_repository() constructor.) All commands
77called as methods of the object are then executed in the context of the
78repository.
79
d5c7721d
PB
80Part of the "repository state" is also information about path to the attached
81working copy (unless you work with a bare repository). You can also navigate
82inside of the working copy using the C<wc_chdir()> method. (Note that
83the repository object is self-contained and will not change working directory
84of your process.)
b1edc53d 85
d5c7721d 86TODO: In the future, we might also do
b1edc53d
PB
87
88 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
89 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
90 my @refs = $remoterepo->refs();
91
b1edc53d
PB
92Currently, the module merely wraps calls to external Git tools. In the future,
93it will provide a much faster way to interact with Git by linking directly
94to libgit. This should be completely opaque to the user, though (performance
9751a32a 95increase notwithstanding).
b1edc53d
PB
96
97=cut
98
99
8b9150e3 100use Carp qw(carp croak); # but croak is bad - throw instead
97b16c06 101use Error qw(:try);
48d9e6ae 102use Cwd qw(abs_path cwd);
d1a29af9 103use IPC::Open2 qw(open2);
e41352b2 104use Fcntl qw(SEEK_SET SEEK_CUR);
b1edc53d
PB
105}
106
107
108=head1 CONSTRUCTORS
109
110=over 4
111
112=item repository ( OPTIONS )
113
114=item repository ( DIRECTORY )
115
116=item repository ()
117
118Construct a new repository object.
119C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
120Possible options are:
121
122B<Repository> - Path to the Git repository.
123
124B<WorkingCopy> - Path to the associated working copy; not strictly required
125as many commands will happily crunch on a bare repository.
126
d5c7721d
PB
127B<WorkingSubdir> - Subdirectory in the working copy to work inside.
128Just left undefined if you do not want to limit the scope of operations.
129
130B<Directory> - Path to the Git working directory in its usual setup.
131The C<.git> directory is searched in the directory and all the parent
132directories; if found, C<WorkingCopy> is set to the directory containing
133it and C<Repository> to the C<.git> directory itself. If no C<.git>
134directory was found, the C<Directory> is assumed to be a bare repository,
135C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
136If the C<$GIT_DIR> environment variable is set, things behave as expected
137as well.
b1edc53d 138
b1edc53d
PB
139You should not use both C<Directory> and either of C<Repository> and
140C<WorkingCopy> - the results of that are undefined.
141
142Alternatively, a directory path may be passed as a single scalar argument
143to the constructor; it is equivalent to setting only the C<Directory> option
144field.
145
146Calling the constructor with no options whatsoever is equivalent to
d5c7721d
PB
147calling it with C<< Directory => '.' >>. In general, if you are building
148a standard porcelain command, simply doing C<< Git->repository() >> should
149do the right thing and setup the object to reflect exactly where the user
150is right now.
b1edc53d
PB
151
152=cut
153
154sub repository {
155 my $class = shift;
156 my @args = @_;
157 my %opts = ();
158 my $self;
159
160 if (defined $args[0]) {
161 if ($#args % 2 != 1) {
162 # Not a hash.
97b16c06
PB
163 $#args == 0 or throw Error::Simple("bad usage");
164 %opts = ( Directory => $args[0] );
b1edc53d
PB
165 } else {
166 %opts = @args;
167 }
d5c7721d
PB
168 }
169
11b8a41c
PB
170 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
171 and not defined $opts{Directory}) {
172 $opts{Directory} = '.';
d5c7721d
PB
173 }
174
11b8a41c 175 if (defined $opts{Directory}) {
64abcc48 176 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
d5c7721d
PB
177
178 my $search = Git->repository(WorkingCopy => $opts{Directory});
179 my $dir;
180 try {
181 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
182 STDERR => 0);
183 } catch Git::Error::Command with {
184 $dir = undef;
185 };
b1edc53d 186
d5c7721d 187 if ($dir) {
71efe0ca 188 $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
fe53bbc9 189 $opts{Repository} = abs_path($dir);
d5c7721d
PB
190
191 # If --git-dir went ok, this shouldn't die either.
192 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
193 $dir = abs_path($opts{Directory}) . '/';
194 if ($prefix) {
195 if (substr($dir, -length($prefix)) ne $prefix) {
196 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
197 }
198 substr($dir, -length($prefix)) = '';
b1edc53d 199 }
d5c7721d
PB
200 $opts{WorkingCopy} = $dir;
201 $opts{WorkingSubdir} = $prefix;
202
203 } else {
204 # A bare repository? Let's see...
205 $dir = $opts{Directory};
206
207 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
9517e6b8 208 # Mimic git-rev-parse --git-dir error message:
f66bc5f9 209 throw Error::Simple("fatal: Not a git repository: $dir");
d5c7721d
PB
210 }
211 my $search = Git->repository(Repository => $dir);
212 try {
213 $search->command('symbolic-ref', 'HEAD');
214 } catch Git::Error::Command with {
9517e6b8 215 # Mimic git-rev-parse --git-dir error message:
f66bc5f9 216 throw Error::Simple("fatal: Not a git repository: $dir");
d5c7721d
PB
217 }
218
219 $opts{Repository} = abs_path($dir);
b1edc53d 220 }
d5c7721d
PB
221
222 delete $opts{Directory};
b1edc53d
PB
223 }
224
81a71734 225 $self = { opts => \%opts };
b1edc53d
PB
226 bless $self, $class;
227}
228
b1edc53d
PB
229=back
230
231=head1 METHODS
232
233=over 4
234
235=item command ( COMMAND [, ARGUMENTS... ] )
236
d43ba468
PB
237=item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
238
b1edc53d
PB
239Execute the given Git C<COMMAND> (specify it without the 'git-'
240prefix), optionally with the specified extra C<ARGUMENTS>.
241
d43ba468
PB
242The second more elaborate form can be used if you want to further adjust
243the command execution. Currently, only one option is supported:
244
245B<STDERR> - How to deal with the command's error output. By default (C<undef>)
246it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
247it to be thrown away. If you want to process it, you can get it in a filehandle
248you specify, but you must be extremely careful; if the error output is not
249very short and you want to read it in the same process as where you called
250C<command()>, you are set up for a nice deadlock!
251
b1edc53d
PB
252The method can be called without any instance or on a specified Git repository
253(in that case the command will be run in the repository context).
254
255In scalar context, it returns all the command output in a single string
256(verbatim).
257
258In array context, it returns an array containing lines printed to the
259command's stdout (without trailing newlines).
260
261In both cases, the command's stdin and stderr are the same as the caller's.
262
263=cut
264
265sub command {
d79850e1 266 my ($fh, $ctx) = command_output_pipe(@_);
b1edc53d
PB
267
268 if (not defined wantarray) {
8b9150e3
PB
269 # Nothing to pepper the possible exception with.
270 _cmd_close($fh, $ctx);
b1edc53d
PB
271
272 } elsif (not wantarray) {
273 local $/;
274 my $text = <$fh>;
8b9150e3
PB
275 try {
276 _cmd_close($fh, $ctx);
277 } catch Git::Error::Command with {
278 # Pepper with the output:
279 my $E = shift;
280 $E->{'-outputref'} = \$text;
281 throw $E;
282 };
b1edc53d
PB
283 return $text;
284
285 } else {
286 my @lines = <$fh>;
67e4baf8 287 defined and chomp for @lines;
8b9150e3
PB
288 try {
289 _cmd_close($fh, $ctx);
290 } catch Git::Error::Command with {
291 my $E = shift;
292 $E->{'-outputref'} = \@lines;
293 throw $E;
294 };
b1edc53d
PB
295 return @lines;
296 }
297}
298
299
300=item command_oneline ( COMMAND [, ARGUMENTS... ] )
301
d43ba468
PB
302=item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
303
b1edc53d
PB
304Execute the given C<COMMAND> in the same way as command()
305does but always return a scalar string containing the first line
306of the command's standard output.
307
308=cut
309
310sub command_oneline {
d79850e1 311 my ($fh, $ctx) = command_output_pipe(@_);
b1edc53d
PB
312
313 my $line = <$fh>;
d5c7721d 314 defined $line and chomp $line;
8b9150e3
PB
315 try {
316 _cmd_close($fh, $ctx);
317 } catch Git::Error::Command with {
318 # Pepper with the output:
319 my $E = shift;
320 $E->{'-outputref'} = \$line;
321 throw $E;
322 };
b1edc53d
PB
323 return $line;
324}
325
326
d79850e1 327=item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
b1edc53d 328
d43ba468
PB
329=item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
330
b1edc53d
PB
331Execute the given C<COMMAND> in the same way as command()
332does but return a pipe filehandle from which the command output can be
333read.
334
d79850e1
PB
335The function can return C<($pipe, $ctx)> in array context.
336See C<command_close_pipe()> for details.
337
b1edc53d
PB
338=cut
339
d79850e1
PB
340sub command_output_pipe {
341 _command_common_pipe('-|', @_);
342}
b1edc53d 343
b1edc53d 344
d79850e1
PB
345=item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
346
d43ba468
PB
347=item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
348
d79850e1
PB
349Execute the given C<COMMAND> in the same way as command_output_pipe()
350does but return an input pipe filehandle instead; the command output
351is not captured.
352
353The function can return C<($pipe, $ctx)> in array context.
354See C<command_close_pipe()> for details.
355
356=cut
357
358sub command_input_pipe {
359 _command_common_pipe('|-', @_);
8b9150e3
PB
360}
361
362
363=item command_close_pipe ( PIPE [, CTX ] )
364
d79850e1 365Close the C<PIPE> as returned from C<command_*_pipe()>, checking
3dff5379 366whether the command finished successfully. The optional C<CTX> argument
8b9150e3 367is required if you want to see the command name in the error message,
d79850e1 368and it is the second value returned by C<command_*_pipe()> when
8b9150e3
PB
369called in array context. The call idiom is:
370
d79850e1
PB
371 my ($fh, $ctx) = $r->command_output_pipe('status');
372 while (<$fh>) { ... }
373 $r->command_close_pipe($fh, $ctx);
8b9150e3
PB
374
375Note that you should not rely on whatever actually is in C<CTX>;
376currently it is simply the command name but in future the context might
377have more complicated structure.
378
379=cut
380
381sub command_close_pipe {
382 my ($self, $fh, $ctx) = _maybe_self(@_);
383 $ctx ||= '<unknown>';
384 _cmd_close($fh, $ctx);
b1edc53d
PB
385}
386
d1a29af9
AR
387=item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
388
389Execute the given C<COMMAND> in the same way as command_output_pipe()
390does but return both an input pipe filehandle and an output pipe filehandle.
391
392The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>.
393See C<command_close_bidi_pipe()> for details.
394
395=cut
396
397sub command_bidi_pipe {
398 my ($pid, $in, $out);
48d9e6ae
MO
399 my ($self) = _maybe_self(@_);
400 local %ENV = %ENV;
401 my $cwd_save = undef;
402 if ($self) {
403 shift;
404 $cwd_save = cwd();
405 _setup_git_cmd_env($self);
406 }
d1a29af9 407 $pid = open2($in, $out, 'git', @_);
48d9e6ae 408 chdir($cwd_save) if $cwd_save;
d1a29af9
AR
409 return ($pid, $in, $out, join(' ', @_));
410}
411
412=item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
413
414Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
415checking whether the command finished successfully. The optional C<CTX>
416argument is required if you want to see the command name in the error message,
417and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
418is:
419
420 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
421 print "000000000\n" $out;
422 while (<$in>) { ... }
423 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
424
425Note that you should not rely on whatever actually is in C<CTX>;
426currently it is simply the command name but in future the context might
427have more complicated structure.
428
429=cut
430
431sub command_close_bidi_pipe {
108c2aaf 432 local $?;
d1a29af9
AR
433 my ($pid, $in, $out, $ctx) = @_;
434 foreach my $fh ($in, $out) {
435 unless (close $fh) {
436 if ($!) {
437 carp "error closing pipe: $!";
438 } elsif ($? >> 8) {
439 throw Git::Error::Command($ctx, $? >>8);
440 }
441 }
442 }
443
444 waitpid $pid, 0;
445
446 if ($? >> 8) {
447 throw Git::Error::Command($ctx, $? >>8);
448 }
449}
450
b1edc53d
PB
451
452=item command_noisy ( COMMAND [, ARGUMENTS... ] )
453
454Execute the given C<COMMAND> in the same way as command() does but do not
455capture the command output - the standard output is not redirected and goes
456to the standard output of the caller application.
457
458While the method is called command_noisy(), you might want to as well use
459it for the most silent Git commands which you know will never pollute your
460stdout but you want to avoid the overhead of the pipe setup when calling them.
461
462The function returns only after the command has finished running.
463
464=cut
465
466sub command_noisy {
467 my ($self, $cmd, @args) = _maybe_self(@_);
d79850e1 468 _check_valid_cmd($cmd);
b1edc53d
PB
469
470 my $pid = fork;
471 if (not defined $pid) {
97b16c06 472 throw Error::Simple("fork failed: $!");
b1edc53d
PB
473 } elsif ($pid == 0) {
474 _cmd_exec($self, $cmd, @args);
475 }
8b9150e3
PB
476 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
477 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
b1edc53d
PB
478 }
479}
480
481
63df97ae
PB
482=item version ()
483
484Return the Git version in use.
485
63df97ae
PB
486=cut
487
18b0fc1c
PB
488sub version {
489 my $verstr = command_oneline('--version');
490 $verstr =~ s/^git version //;
491 $verstr;
492}
63df97ae
PB
493
494
eca1f6fd
PB
495=item exec_path ()
496
d5c7721d 497Return path to the Git sub-command executables (the same as
eca1f6fd
PB
498C<git --exec-path>). Useful mostly only internally.
499
eca1f6fd
PB
500=cut
501
18b0fc1c 502sub exec_path { command_oneline('--exec-path') }
eca1f6fd
PB
503
504
89a56bfb
MH
505=item html_path ()
506
507Return path to the Git html documentation (the same as
508C<git --html-path>). Useful mostly only internally.
509
510=cut
511
512sub html_path { command_oneline('--html-path') }
513
514
d5c7721d
PB
515=item repo_path ()
516
517Return path to the git repository. Must be called on a repository instance.
518
519=cut
520
521sub repo_path { $_[0]->{opts}->{Repository} }
522
523
524=item wc_path ()
525
526Return path to the working copy. Must be called on a repository instance.
527
528=cut
529
530sub wc_path { $_[0]->{opts}->{WorkingCopy} }
531
532
533=item wc_subdir ()
534
535Return path to the subdirectory inside of a working copy. Must be called
536on a repository instance.
537
538=cut
539
540sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
541
542
543=item wc_chdir ( SUBDIR )
544
545Change the working copy subdirectory to work within. The C<SUBDIR> is
546relative to the working copy root directory (not the current subdirectory).
547Must be called on a repository instance attached to a working copy
548and the directory must exist.
549
550=cut
551
552sub wc_chdir {
553 my ($self, $subdir) = @_;
d5c7721d
PB
554 $self->wc_path()
555 or throw Error::Simple("bare repository");
556
557 -d $self->wc_path().'/'.$subdir
64abcc48 558 or throw Error::Simple("subdir not found: $subdir $!");
d5c7721d
PB
559 # Of course we will not "hold" the subdirectory so anyone
560 # can delete it now and we will never know. But at least we tried.
561
562 $self->{opts}->{WorkingSubdir} = $subdir;
563}
564
565
dc2613de
PB
566=item config ( VARIABLE )
567
e0d10e1c 568Retrieve the configuration C<VARIABLE> in the same manner as C<config>
dc2613de
PB
569does. In scalar context requires the variable to be set only one time
570(exception is thrown otherwise), in array context returns allows the
571variable to be set multiple times and returns all the values.
572
dc2613de
PB
573=cut
574
575sub config {
6942a3d7 576 return _config_common({}, @_);
dc2613de
PB
577}
578
579
35c49eea 580=item config_bool ( VARIABLE )
7b9a13ec 581
35c49eea
PB
582Retrieve the bool configuration C<VARIABLE>. The return value
583is usable as a boolean in perl (and C<undef> if it's not defined,
584of course).
7b9a13ec 585
7b9a13ec
TT
586=cut
587
35c49eea 588sub config_bool {
6942a3d7 589 my $val = scalar _config_common({'kind' => '--bool'}, @_);
7b9a13ec 590
6942a3d7
JH
591 # Do not rewrite this as return (defined $val && $val eq 'true')
592 # as some callers do care what kind of falsehood they receive.
593 if (!defined $val) {
594 return undef;
595 } else {
35c49eea 596 return $val eq 'true';
6942a3d7 597 }
7b9a13ec
TT
598}
599
9fef9e27
CS
600
601=item config_path ( VARIABLE )
602
603Retrieve the path configuration C<VARIABLE>. The return value
604is an expanded path or C<undef> if it's not defined.
605
9fef9e27
CS
606=cut
607
608sub config_path {
6942a3d7 609 return _config_common({'kind' => '--path'}, @_);
9fef9e27
CS
610}
611
6942a3d7 612
346d203b
JN
613=item config_int ( VARIABLE )
614
615Retrieve the integer configuration C<VARIABLE>. The return value
616is simple decimal number. An optional value suffix of 'k', 'm',
617or 'g' in the config file will cause the value to be multiplied
618by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
619It would return C<undef> if configuration variable is not defined,
620
346d203b
JN
621=cut
622
623sub config_int {
6942a3d7
JH
624 return scalar _config_common({'kind' => '--int'}, @_);
625}
626
627# Common subroutine to implement bulk of what the config* family of methods
628# do. This curently wraps command('config') so it is not so fast.
629sub _config_common {
630 my ($opts) = shift @_;
c2e357c2 631 my ($self, $var) = _maybe_self(@_);
346d203b
JN
632
633 try {
6942a3d7 634 my @cmd = ('config', $opts->{'kind'} ? $opts->{'kind'} : ());
c2e357c2 635 unshift @cmd, $self if $self;
6942a3d7
JH
636 if (wantarray) {
637 return command(@cmd, '--get-all', $var);
638 } else {
639 return command_oneline(@cmd, '--get', $var);
640 }
346d203b
JN
641 } catch Git::Error::Command with {
642 my $E = shift;
643 if ($E->value() == 1) {
644 # Key not found.
6942a3d7 645 return;
346d203b
JN
646 } else {
647 throw $E;
648 }
649 };
650}
7b9a13ec 651
b4c61ed6
JH
652=item get_colorbool ( NAME )
653
654Finds if color should be used for NAMEd operation from the configuration,
655and returns boolean (true for "use color", false for "do not use color").
656
657=cut
658
659sub get_colorbool {
660 my ($self, $var) = @_;
661 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
662 my $use_color = $self->command_oneline('config', '--get-colorbool',
663 $var, $stdout_to_tty);
664 return ($use_color eq 'true');
665}
666
667=item get_color ( SLOT, COLOR )
668
669Finds color for SLOT from the configuration, while defaulting to COLOR,
670and returns the ANSI color escape sequence:
671
672 print $repo->get_color("color.interactive.prompt", "underline blue white");
673 print "some text";
674 print $repo->get_color("", "normal");
675
676=cut
677
678sub get_color {
679 my ($self, $slot, $default) = @_;
680 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
681 if (!defined $color) {
682 $color = "";
683 }
684 return $color;
685}
686
31a92f6a
PB
687=item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
688
689This function returns a hashref of refs stored in a given remote repository.
690The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
691contains the tag object while a C<refname^{}> entry gives the tagged objects.
692
693C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
a7793a74 694argument; either a URL or a remote name (if called on a repository instance).
31a92f6a
PB
695C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
696tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
697of strings containing a shell-like glob to further limit the refs returned in
698the hash; the meaning is again the same as the appropriate C<git-ls-remote>
699argument.
700
701This function may or may not be called on a repository instance. In the former
702case, remote names as defined in the repository are recognized as repository
703specifiers.
704
705=cut
706
707sub remote_refs {
708 my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
709 my @args;
710 if (ref $groups eq 'ARRAY') {
711 foreach (@$groups) {
712 if ($_ eq 'heads') {
713 push (@args, '--heads');
714 } elsif ($_ eq 'tags') {
715 push (@args, '--tags');
716 } else {
717 # Ignore unknown groups for future
718 # compatibility
719 }
720 }
721 }
722 push (@args, $repo);
723 if (ref $refglobs eq 'ARRAY') {
724 push (@args, @$refglobs);
725 }
726
727 my @self = $self ? ($self) : (); # Ultra trickery
728 my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
729 my %refs;
730 while (<$fh>) {
731 chomp;
732 my ($hash, $ref) = split(/\t/, $_, 2);
733 $refs{$ref} = $hash;
734 }
735 Git::command_close_pipe(@self, $fh, $ctx);
736 return \%refs;
737}
738
739
c7a30e56
PB
740=item ident ( TYPE | IDENTSTR )
741
742=item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
743
744This suite of functions retrieves and parses ident information, as stored
745in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
746C<TYPE> can be either I<author> or I<committer>; case is insignificant).
747
5354a56f 748The C<ident> method retrieves the ident information from C<git var>
c7a30e56
PB
749and either returns it as a scalar string or as an array with the fields parsed.
750Alternatively, it can take a prepared ident string (e.g. from the commit
751object) and just parse it.
752
753C<ident_person> returns the person part of the ident - name and email;
754it can take the same arguments as C<ident> or the array returned by C<ident>.
755
756The synopsis is like:
757
758 my ($name, $email, $time_tz) = ident('author');
759 "$name <$email>" eq ident_person('author');
760 "$name <$email>" eq ident_person($name);
761 $time_tz =~ /^\d+ [+-]\d{4}$/;
762
c7a30e56
PB
763=cut
764
765sub ident {
44617928 766 my ($self, $type) = _maybe_self(@_);
c7a30e56
PB
767 my $identstr;
768 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
44617928
FL
769 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
770 unshift @cmd, $self if $self;
771 $identstr = command_oneline(@cmd);
c7a30e56
PB
772 } else {
773 $identstr = $type;
774 }
775 if (wantarray) {
776 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
777 } else {
778 return $identstr;
779 }
780}
781
782sub ident_person {
44617928
FL
783 my ($self, @ident) = _maybe_self(@_);
784 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
c7a30e56
PB
785 return "$ident[0] <$ident[1]>";
786}
787
788
24c4b714 789=item hash_object ( TYPE, FILENAME )
b1edc53d 790
58c8dd21
LW
791Compute the SHA1 object id of the given C<FILENAME> considering it is
792of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
b1edc53d 793
b1edc53d
PB
794The method can be called without any instance or on a specified Git repository,
795it makes zero difference.
796
797The function returns the SHA1 hash.
798
b1edc53d
PB
799=cut
800
18b0fc1c 801# TODO: Support for passing FILEHANDLE instead of FILENAME
e6634ac9
PB
802sub hash_object {
803 my ($self, $type, $file) = _maybe_self(@_);
18b0fc1c 804 command_oneline('hash-object', '-t', $type, $file);
e6634ac9 805}
b1edc53d
PB
806
807
7182530d
AR
808=item hash_and_insert_object ( FILENAME )
809
810Compute the SHA1 object id of the given C<FILENAME> and add the object to the
811object database.
812
813The function returns the SHA1 hash.
814
815=cut
816
817# TODO: Support for passing FILEHANDLE instead of FILENAME
818sub hash_and_insert_object {
819 my ($self, $filename) = @_;
820
821 carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
822
823 $self->_open_hash_and_insert_object_if_needed();
824 my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
825
826 unless (print $out $filename, "\n") {
827 $self->_close_hash_and_insert_object();
828 throw Error::Simple("out pipe went bad");
829 }
830
831 chomp(my $hash = <$in>);
832 unless (defined($hash)) {
833 $self->_close_hash_and_insert_object();
834 throw Error::Simple("in pipe went bad");
835 }
836
837 return $hash;
838}
839
840sub _open_hash_and_insert_object_if_needed {
841 my ($self) = @_;
842
843 return if defined($self->{hash_object_pid});
844
845 ($self->{hash_object_pid}, $self->{hash_object_in},
846 $self->{hash_object_out}, $self->{hash_object_ctx}) =
48d9e6ae 847 $self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
7182530d
AR
848}
849
850sub _close_hash_and_insert_object {
851 my ($self) = @_;
852
853 return unless defined($self->{hash_object_pid});
854
855 my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
856
452d36b1
AMS
857 command_close_bidi_pipe(@$self{@vars});
858 delete @$self{@vars};
7182530d
AR
859}
860
861=item cat_blob ( SHA1, FILEHANDLE )
862
863Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
864returns the number of bytes printed.
865
866=cut
867
868sub cat_blob {
869 my ($self, $sha1, $fh) = @_;
870
871 $self->_open_cat_blob_if_needed();
872 my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
873
874 unless (print $out $sha1, "\n") {
875 $self->_close_cat_blob();
876 throw Error::Simple("out pipe went bad");
877 }
878
879 my $description = <$in>;
880 if ($description =~ / missing$/) {
881 carp "$sha1 doesn't exist in the repository";
d683a0e0 882 return -1;
7182530d
AR
883 }
884
885 if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
886 carp "Unexpected result returned from git cat-file";
d683a0e0 887 return -1;
7182530d
AR
888 }
889
890 my $size = $1;
891
892 my $blob;
893 my $bytesRead = 0;
894
895 while (1) {
896 my $bytesLeft = $size - $bytesRead;
897 last unless $bytesLeft;
898
899 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
900 my $read = read($in, $blob, $bytesToRead, $bytesRead);
901 unless (defined($read)) {
902 $self->_close_cat_blob();
903 throw Error::Simple("in pipe went bad");
904 }
905
906 $bytesRead += $read;
907 }
908
909 # Skip past the trailing newline.
910 my $newline;
911 my $read = read($in, $newline, 1);
912 unless (defined($read)) {
913 $self->_close_cat_blob();
914 throw Error::Simple("in pipe went bad");
915 }
916 unless ($read == 1 && $newline eq "\n") {
917 $self->_close_cat_blob();
918 throw Error::Simple("didn't find newline after blob");
919 }
920
921 unless (print $fh $blob) {
922 $self->_close_cat_blob();
923 throw Error::Simple("couldn't write to passed in filehandle");
924 }
925
926 return $size;
927}
928
929sub _open_cat_blob_if_needed {
930 my ($self) = @_;
931
932 return if defined($self->{cat_blob_pid});
933
934 ($self->{cat_blob_pid}, $self->{cat_blob_in},
935 $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
48d9e6ae 936 $self->command_bidi_pipe(qw(cat-file --batch));
7182530d
AR
937}
938
939sub _close_cat_blob {
940 my ($self) = @_;
941
942 return unless defined($self->{cat_blob_pid});
943
944 my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
945
452d36b1
AMS
946 command_close_bidi_pipe(@$self{@vars});
947 delete @$self{@vars};
7182530d 948}
8b9150e3 949
e41352b2
MG
950
951{ # %TEMP_* Lexical Context
952
836ff95d 953my (%TEMP_FILEMAP, %TEMP_FILES);
e41352b2
MG
954
955=item temp_acquire ( NAME )
956
957Attempts to retreive the temporary file mapped to the string C<NAME>. If an
958associated temp file has not been created this session or was closed, it is
959created, cached, and set for autoflush and binmode.
960
961Internally locks the file mapped to C<NAME>. This lock must be released with
962C<temp_release()> when the temp file is no longer needed. Subsequent attempts
963to retrieve temporary files mapped to the same C<NAME> while still locked will
964cause an error. This locking mechanism provides a weak guarantee and is not
965threadsafe. It does provide some error checking to help prevent temp file refs
966writing over one another.
967
968In general, the L<File::Handle> returned should not be closed by consumers as
969it defeats the purpose of this caching mechanism. If you need to close the temp
970file handle, then you should use L<File::Temp> or another temp file faculty
971directly. If a handle is closed and then requested again, then a warning will
972issue.
973
974=cut
975
976sub temp_acquire {
bcdd1b44 977 my $temp_fd = _temp_cache(@_);
e41352b2 978
836ff95d 979 $TEMP_FILES{$temp_fd}{locked} = 1;
e41352b2
MG
980 $temp_fd;
981}
982
983=item temp_release ( NAME )
984
985=item temp_release ( FILEHANDLE )
986
987Releases a lock acquired through C<temp_acquire()>. Can be called either with
988the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
989referencing a locked temp file.
990
991Warns if an attempt is made to release a file that is not locked.
992
993The temp file will be truncated before being released. This can help to reduce
994disk I/O where the system is smart enough to detect the truncation while data
995is in the output buffers. Beware that after the temp file is released and
996truncated, any operations on that file may fail miserably until it is
997re-acquired. All contents are lost between each release and acquire mapped to
998the same string.
999
1000=cut
1001
1002sub temp_release {
1003 my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1004
836ff95d 1005 if (exists $TEMP_FILEMAP{$temp_fd}) {
e41352b2
MG
1006 $temp_fd = $TEMP_FILES{$temp_fd};
1007 }
836ff95d 1008 unless ($TEMP_FILES{$temp_fd}{locked}) {
e41352b2
MG
1009 carp "Attempt to release temp file '",
1010 $temp_fd, "' that has not been locked";
1011 }
1012 temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1013
836ff95d 1014 $TEMP_FILES{$temp_fd}{locked} = 0;
e41352b2
MG
1015 undef;
1016}
1017
1018sub _temp_cache {
bcdd1b44 1019 my ($self, $name) = _maybe_self(@_);
e41352b2 1020
c14c8ceb
MG
1021 _verify_require();
1022
836ff95d 1023 my $temp_fd = \$TEMP_FILEMAP{$name};
e41352b2 1024 if (defined $$temp_fd and $$temp_fd->opened) {
836ff95d 1025 if ($TEMP_FILES{$$temp_fd}{locked}) {
8faea4f3
JS
1026 throw Error::Simple("Temp file with moniker '" .
1027 $name . "' already in use");
e41352b2
MG
1028 }
1029 } else {
1030 if (defined $$temp_fd) {
1031 # then we're here because of a closed handle.
1032 carp "Temp file '", $name,
1033 "' was closed. Opening replacement.";
1034 }
836ff95d 1035 my $fname;
bcdd1b44
MS
1036
1037 my $tmpdir;
1038 if (defined $self) {
1039 $tmpdir = $self->repo_path();
1040 }
1041
836ff95d 1042 ($$temp_fd, $fname) = File::Temp->tempfile(
bcdd1b44 1043 'Git_XXXXXX', UNLINK => 1, DIR => $tmpdir,
e41352b2 1044 ) or throw Error::Simple("couldn't open new temp file");
bcdd1b44 1045
e41352b2
MG
1046 $$temp_fd->autoflush;
1047 binmode $$temp_fd;
836ff95d 1048 $TEMP_FILES{$$temp_fd}{fname} = $fname;
e41352b2
MG
1049 }
1050 $$temp_fd;
1051}
1052
c14c8ceb
MG
1053sub _verify_require {
1054 eval { require File::Temp; require File::Spec; };
1055 $@ and throw Error::Simple($@);
1056}
1057
e41352b2
MG
1058=item temp_reset ( FILEHANDLE )
1059
1060Truncates and resets the position of the C<FILEHANDLE>.
1061
1062=cut
1063
1064sub temp_reset {
1065 my ($self, $temp_fd) = _maybe_self(@_);
1066
1067 truncate $temp_fd, 0
1068 or throw Error::Simple("couldn't truncate file");
1069 sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1070 or throw Error::Simple("couldn't seek to beginning of file");
1071 sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1072 or throw Error::Simple("expected file position to be reset");
1073}
1074
836ff95d
MG
1075=item temp_path ( NAME )
1076
1077=item temp_path ( FILEHANDLE )
1078
1079Returns the filename associated with the given tempfile.
1080
1081=cut
1082
1083sub temp_path {
1084 my ($self, $temp_fd) = _maybe_self(@_);
1085
1086 if (exists $TEMP_FILEMAP{$temp_fd}) {
1087 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1088 }
1089 $TEMP_FILES{$temp_fd}{fname};
1090}
1091
e41352b2 1092sub END {
836ff95d 1093 unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
e41352b2
MG
1094}
1095
1096} # %TEMP_* Lexical Context
1097
b1edc53d
PB
1098=back
1099
97b16c06 1100=head1 ERROR HANDLING
b1edc53d 1101
97b16c06 1102All functions are supposed to throw Perl exceptions in case of errors.
8b9150e3
PB
1103See the L<Error> module on how to catch those. Most exceptions are mere
1104L<Error::Simple> instances.
1105
1106However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1107functions suite can throw C<Git::Error::Command> exceptions as well: those are
1108thrown when the external command returns an error code and contain the error
1109code as well as access to the captured command's output. The exception class
1110provides the usual C<stringify> and C<value> (command's exit code) methods and
1111in addition also a C<cmd_output> method that returns either an array or a
1112string with the captured command output (depending on the original function
1113call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1114returns the command and its arguments (but without proper quoting).
1115
d79850e1 1116Note that the C<command_*_pipe()> functions cannot throw this exception since
8b9150e3
PB
1117it has no idea whether the command failed or not. You will only find out
1118at the time you C<close> the pipe; if you want to have that automated,
1119use C<command_close_pipe()>, which can throw the exception.
1120
1121=cut
1122
1123{
1124 package Git::Error::Command;
1125
1126 @Git::Error::Command::ISA = qw(Error);
1127
1128 sub new {
1129 my $self = shift;
1130 my $cmdline = '' . shift;
1131 my $value = 0 + shift;
1132 my $outputref = shift;
1133 my(@args) = ();
1134
1135 local $Error::Depth = $Error::Depth + 1;
1136
1137 push(@args, '-cmdline', $cmdline);
1138 push(@args, '-value', $value);
1139 push(@args, '-outputref', $outputref);
1140
1141 $self->SUPER::new(-text => 'command returned error', @args);
1142 }
1143
1144 sub stringify {
1145 my $self = shift;
1146 my $text = $self->SUPER::stringify;
1147 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1148 }
1149
1150 sub cmdline {
1151 my $self = shift;
1152 $self->{'-cmdline'};
1153 }
1154
1155 sub cmd_output {
1156 my $self = shift;
1157 my $ref = $self->{'-outputref'};
1158 defined $ref or undef;
1159 if (ref $ref eq 'ARRAY') {
1160 return @$ref;
1161 } else { # SCALAR
1162 return $$ref;
1163 }
1164 }
1165}
1166
1167=over 4
1168
1169=item git_cmd_try { CODE } ERRMSG
1170
1171This magical statement will automatically catch any C<Git::Error::Command>
1172exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1173on its lips; the message will have %s substituted for the command line
1174and %d for the exit status. This statement is useful mostly for producing
1175more user-friendly error messages.
1176
1177In case of no exception caught the statement returns C<CODE>'s return value.
1178
1179Note that this is the only auto-exported function.
1180
1181=cut
1182
1183sub git_cmd_try(&$) {
1184 my ($code, $errmsg) = @_;
1185 my @result;
1186 my $err;
1187 my $array = wantarray;
1188 try {
1189 if ($array) {
1190 @result = &$code;
1191 } else {
1192 $result[0] = &$code;
1193 }
1194 } catch Git::Error::Command with {
1195 my $E = shift;
1196 $err = $errmsg;
1197 $err =~ s/\%s/$E->cmdline()/ge;
1198 $err =~ s/\%d/$E->value()/ge;
1199 # We can't croak here since Error.pm would mangle
1200 # that to Error::Simple.
1201 };
1202 $err and croak $err;
1203 return $array ? @result : $result[0];
1204}
1205
1206
1207=back
b1edc53d
PB
1208
1209=head1 COPYRIGHT
1210
1211Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1212
1213This module is free software; it may be used, copied, modified
1214and distributed under the terms of the GNU General Public Licence,
1215either version 2, or (at your option) any later version.
1216
1217=cut
1218
1219
1220# Take raw method argument list and return ($obj, @args) in case
1221# the method was called upon an instance and (undef, @args) if
1222# it was called directly.
1223sub _maybe_self {
d8b24b93 1224 UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
b1edc53d
PB
1225}
1226
d79850e1
PB
1227# Check if the command id is something reasonable.
1228sub _check_valid_cmd {
1229 my ($cmd) = @_;
1230 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1231}
1232
1233# Common backend for the pipe creators.
1234sub _command_common_pipe {
1235 my $direction = shift;
d43ba468
PB
1236 my ($self, @p) = _maybe_self(@_);
1237 my (%opts, $cmd, @args);
1238 if (ref $p[0]) {
1239 ($cmd, @args) = @{shift @p};
1240 %opts = ref $p[0] ? %{$p[0]} : @p;
1241 } else {
1242 ($cmd, @args) = @p;
1243 }
d79850e1
PB
1244 _check_valid_cmd($cmd);
1245
a6065b54 1246 my $fh;
d3b1785f 1247 if ($^O eq 'MSWin32') {
a6065b54
PB
1248 # ActiveState Perl
1249 #defined $opts{STDERR} and
1250 # warn 'ignoring STDERR option - running w/ ActiveState';
1251 $direction eq '-|' or
1252 die 'input pipe for ActiveState not implemented';
bed118d6
AR
1253 # the strange construction with *ACPIPE is just to
1254 # explain the tie below that we want to bind to
1255 # a handle class, not scalar. It is not known if
1256 # it is something specific to ActiveState Perl or
1257 # just a Perl quirk.
1258 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1259 $fh = *ACPIPE;
a6065b54
PB
1260
1261 } else {
1262 my $pid = open($fh, $direction);
1263 if (not defined $pid) {
1264 throw Error::Simple("open failed: $!");
1265 } elsif ($pid == 0) {
1266 if (defined $opts{STDERR}) {
1267 close STDERR;
1268 }
1269 if ($opts{STDERR}) {
1270 open (STDERR, '>&', $opts{STDERR})
1271 or die "dup failed: $!";
1272 }
1273 _cmd_exec($self, $cmd, @args);
d43ba468 1274 }
d79850e1
PB
1275 }
1276 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1277}
1278
b1edc53d
PB
1279# When already in the subprocess, set up the appropriate state
1280# for the given repository and execute the git command.
1281sub _cmd_exec {
1282 my ($self, @args) = @_;
48d9e6ae
MO
1283 _setup_git_cmd_env($self);
1284 _execv_git_cmd(@args);
1285 die qq[exec "@args" failed: $!];
1286}
1287
1288# set up the appropriate state for git command
1289sub _setup_git_cmd_env {
1290 my $self = shift;
b1edc53d 1291 if ($self) {
d5c7721d 1292 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
da159c77
FL
1293 $self->repo_path() and $self->wc_path()
1294 and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
d5c7721d
PB
1295 $self->wc_path() and chdir($self->wc_path());
1296 $self->wc_subdir() and chdir($self->wc_subdir());
b1edc53d 1297 }
b1edc53d
PB
1298}
1299
8062f81c
PB
1300# Execute the given Git command ($_[0]) with arguments ($_[1..])
1301# by searching for it at proper places.
18b0fc1c 1302sub _execv_git_cmd { exec('git', @_); }
8062f81c 1303
b1edc53d
PB
1304# Close pipe to a subprocess.
1305sub _cmd_close {
8b9150e3 1306 my ($fh, $ctx) = @_;
b1edc53d
PB
1307 if (not close $fh) {
1308 if ($!) {
1309 # It's just close, no point in fatalities
1310 carp "error closing pipe: $!";
1311 } elsif ($? >> 8) {
8b9150e3
PB
1312 # The caller should pepper this.
1313 throw Git::Error::Command($ctx, $? >> 8);
b1edc53d
PB
1314 }
1315 # else we might e.g. closed a live stream; the command
1316 # dying of SIGPIPE would drive us here.
1317 }
1318}
1319
1320
7182530d
AR
1321sub DESTROY {
1322 my ($self) = @_;
1323 $self->_close_hash_and_insert_object();
1324 $self->_close_cat_blob();
1325}
b1edc53d
PB
1326
1327
a6065b54
PB
1328# Pipe implementation for ActiveState Perl.
1329
1330package Git::activestate_pipe;
1331use strict;
1332
1333sub TIEHANDLE {
1334 my ($class, @params) = @_;
1335 # FIXME: This is probably horrible idea and the thing will explode
1336 # at the moment you give it arguments that require some quoting,
1337 # but I have no ActiveState clue... --pasky
d3b1785f
AR
1338 # Let's just hope ActiveState Perl does at least the quoting
1339 # correctly.
1340 my @data = qx{git @params};
a6065b54
PB
1341 bless { i => 0, data => \@data }, $class;
1342}
1343
1344sub READLINE {
1345 my $self = shift;
1346 if ($self->{i} >= scalar @{$self->{data}}) {
1347 return undef;
1348 }
2f5b3980
AR
1349 my $i = $self->{i};
1350 if (wantarray) {
1351 $self->{i} = $#{$self->{'data'}} + 1;
1352 return splice(@{$self->{'data'}}, $i);
1353 }
1354 $self->{i} = $i + 1;
1355 return $self->{'data'}->[ $i ];
a6065b54
PB
1356}
1357
1358sub CLOSE {
1359 my $self = shift;
1360 delete $self->{data};
1361 delete $self->{i};
1362}
1363
1364sub EOF {
1365 my $self = shift;
1366 return ($self->{i} >= scalar @{$self->{data}});
1367}
1368
1369
b1edc53d 13701; # Famous last words