blob: a2812ea612b997c1a76d89075dd1263a3af4fd37 [file] [log] [blame]
Petr Baudisb1edc532006-06-24 04:34:29 +02001=head1 NAME
2
3Git - Perl interface to the Git version control system
4
5=cut
6
7
8package Git;
9
10use strict;
11
12
13BEGIN {
14
15our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
16
17# Totally unstable API.
18$VERSION = '0.01';
19
20
21=head1 SYNOPSIS
22
23 use Git;
24
25 my $version = Git::command_oneline('version');
26
Petr Baudis8b9150e2006-06-24 04:34:44 +020027 git_cmd_try { Git::command_noisy('update-server-info') }
28 '%s failed w/ code %d';
Petr Baudisb1edc532006-06-24 04:34:29 +020029
30 my $repo = Git->repository (Directory => '/srv/git/cogito.git');
31
32
33 my @revs = $repo->command('rev-list', '--since=last monday', '--all');
34
Petr Baudisd79850e2006-06-24 04:34:47 +020035 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
Petr Baudisb1edc532006-06-24 04:34:29 +020036 my $lastrev = <$fh>; chomp $lastrev;
Petr Baudis8b9150e2006-06-24 04:34:44 +020037 $repo->command_close_pipe($fh, $c);
Petr Baudisb1edc532006-06-24 04:34:29 +020038
Petr Baudisd43ba462006-06-24 04:34:49 +020039 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
40 STDERR => 0 );
Petr Baudisb1edc532006-06-24 04:34:29 +020041
42=cut
43
44
45require Exporter;
46
47@ISA = qw(Exporter);
48
Petr Baudis8b9150e2006-06-24 04:34:44 +020049@EXPORT = qw(git_cmd_try);
Petr Baudisb1edc532006-06-24 04:34:29 +020050
51# Methods which can be called as standalone functions as well:
Petr Baudisd79850e2006-06-24 04:34:47 +020052@EXPORT_OK = qw(command command_oneline command_noisy
53 command_output_pipe command_input_pipe command_close_pipe
Petr Baudis8b9150e2006-06-24 04:34:44 +020054 version exec_path hash_object git_cmd_try);
Petr Baudisb1edc532006-06-24 04:34:29 +020055
56
57=head1 DESCRIPTION
58
59This module provides Perl scripts easy way to interface the Git version control
60system. The modules have an easy and well-tested way to call arbitrary Git
61commands; in the future, the interface will also provide specialized methods
62for doing easily operations which are not totally trivial to do over
63the generic command interface.
64
65While some commands can be executed outside of any context (e.g. 'version'
Nicolas Pitre5c94f872007-01-12 16:01:46 -050066or 'init'), most operations require a repository context, which in practice
Petr Baudisb1edc532006-06-24 04:34:29 +020067means getting an instance of the Git object using the repository() constructor.
68(In the future, we will also get a new_repository() constructor.) All commands
69called as methods of the object are then executed in the context of the
70repository.
71
Petr Baudisd5c77212006-06-24 04:34:51 +020072Part of the "repository state" is also information about path to the attached
73working copy (unless you work with a bare repository). You can also navigate
74inside of the working copy using the C<wc_chdir()> method. (Note that
75the repository object is self-contained and will not change working directory
76of your process.)
Petr Baudisb1edc532006-06-24 04:34:29 +020077
Petr Baudisd5c77212006-06-24 04:34:51 +020078TODO: In the future, we might also do
Petr Baudisb1edc532006-06-24 04:34:29 +020079
80 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
81 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
82 my @refs = $remoterepo->refs();
83
Petr Baudisb1edc532006-06-24 04:34:29 +020084Currently, the module merely wraps calls to external Git tools. In the future,
85it will provide a much faster way to interact with Git by linking directly
86to libgit. This should be completely opaque to the user, though (performance
87increate nonwithstanding).
88
89=cut
90
91
Petr Baudis8b9150e2006-06-24 04:34:44 +020092use Carp qw(carp croak); # but croak is bad - throw instead
Petr Baudis97b16c02006-06-24 04:34:42 +020093use Error qw(:try);
Petr Baudisd5c77212006-06-24 04:34:51 +020094use Cwd qw(abs_path);
Petr Baudisb1edc532006-06-24 04:34:29 +020095
Petr Baudisb1edc532006-06-24 04:34:29 +020096}
97
98
99=head1 CONSTRUCTORS
100
101=over 4
102
103=item repository ( OPTIONS )
104
105=item repository ( DIRECTORY )
106
107=item repository ()
108
109Construct a new repository object.
110C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
111Possible options are:
112
113B<Repository> - Path to the Git repository.
114
115B<WorkingCopy> - Path to the associated working copy; not strictly required
116as many commands will happily crunch on a bare repository.
117
Petr Baudisd5c77212006-06-24 04:34:51 +0200118B<WorkingSubdir> - Subdirectory in the working copy to work inside.
119Just left undefined if you do not want to limit the scope of operations.
120
121B<Directory> - Path to the Git working directory in its usual setup.
122The C<.git> directory is searched in the directory and all the parent
123directories; if found, C<WorkingCopy> is set to the directory containing
124it and C<Repository> to the C<.git> directory itself. If no C<.git>
125directory was found, the C<Directory> is assumed to be a bare repository,
126C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
127If the C<$GIT_DIR> environment variable is set, things behave as expected
128as well.
Petr Baudisb1edc532006-06-24 04:34:29 +0200129
Petr Baudisb1edc532006-06-24 04:34:29 +0200130You should not use both C<Directory> and either of C<Repository> and
131C<WorkingCopy> - the results of that are undefined.
132
133Alternatively, a directory path may be passed as a single scalar argument
134to the constructor; it is equivalent to setting only the C<Directory> option
135field.
136
137Calling the constructor with no options whatsoever is equivalent to
Petr Baudisd5c77212006-06-24 04:34:51 +0200138calling it with C<< Directory => '.' >>. In general, if you are building
139a standard porcelain command, simply doing C<< Git->repository() >> should
140do the right thing and setup the object to reflect exactly where the user
141is right now.
Petr Baudisb1edc532006-06-24 04:34:29 +0200142
143=cut
144
145sub repository {
146 my $class = shift;
147 my @args = @_;
148 my %opts = ();
149 my $self;
150
151 if (defined $args[0]) {
152 if ($#args % 2 != 1) {
153 # Not a hash.
Petr Baudis97b16c02006-06-24 04:34:42 +0200154 $#args == 0 or throw Error::Simple("bad usage");
155 %opts = ( Directory => $args[0] );
Petr Baudisb1edc532006-06-24 04:34:29 +0200156 } else {
157 %opts = @args;
158 }
Petr Baudisd5c77212006-06-24 04:34:51 +0200159 }
Petr Baudisb1edc532006-06-24 04:34:29 +0200160
Petr Baudisd5c77212006-06-24 04:34:51 +0200161 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
162 $opts{Directory} ||= '.';
163 }
164
165 if ($opts{Directory}) {
166 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
167
168 my $search = Git->repository(WorkingCopy => $opts{Directory});
169 my $dir;
170 try {
171 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
172 STDERR => 0);
173 } catch Git::Error::Command with {
174 $dir = undef;
175 };
176
177 if ($dir) {
Petr Baudis71efe0c2006-06-25 03:54:28 +0200178 $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
179 $opts{Repository} = $dir;
Petr Baudisd5c77212006-06-24 04:34:51 +0200180
181 # If --git-dir went ok, this shouldn't die either.
182 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
183 $dir = abs_path($opts{Directory}) . '/';
184 if ($prefix) {
185 if (substr($dir, -length($prefix)) ne $prefix) {
186 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
187 }
188 substr($dir, -length($prefix)) = '';
Petr Baudisb1edc532006-06-24 04:34:29 +0200189 }
Petr Baudisd5c77212006-06-24 04:34:51 +0200190 $opts{WorkingCopy} = $dir;
191 $opts{WorkingSubdir} = $prefix;
192
193 } else {
194 # A bare repository? Let's see...
195 $dir = $opts{Directory};
196
197 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
198 # Mimick git-rev-parse --git-dir error message:
199 throw Error::Simple('fatal: Not a git repository');
200 }
201 my $search = Git->repository(Repository => $dir);
202 try {
203 $search->command('symbolic-ref', 'HEAD');
204 } catch Git::Error::Command with {
205 # Mimick git-rev-parse --git-dir error message:
206 throw Error::Simple('fatal: Not a git repository');
207 }
208
209 $opts{Repository} = abs_path($dir);
Petr Baudisb1edc532006-06-24 04:34:29 +0200210 }
Petr Baudisd5c77212006-06-24 04:34:51 +0200211
212 delete $opts{Directory};
Petr Baudisb1edc532006-06-24 04:34:29 +0200213 }
214
Junio C Hamano81a71732006-09-02 22:58:48 -0700215 $self = { opts => \%opts };
Petr Baudisb1edc532006-06-24 04:34:29 +0200216 bless $self, $class;
217}
218
219
220=back
221
222=head1 METHODS
223
224=over 4
225
226=item command ( COMMAND [, ARGUMENTS... ] )
227
Petr Baudisd43ba462006-06-24 04:34:49 +0200228=item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
229
Petr Baudisb1edc532006-06-24 04:34:29 +0200230Execute the given Git C<COMMAND> (specify it without the 'git-'
231prefix), optionally with the specified extra C<ARGUMENTS>.
232
Petr Baudisd43ba462006-06-24 04:34:49 +0200233The second more elaborate form can be used if you want to further adjust
234the command execution. Currently, only one option is supported:
235
236B<STDERR> - How to deal with the command's error output. By default (C<undef>)
237it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
238it to be thrown away. If you want to process it, you can get it in a filehandle
239you specify, but you must be extremely careful; if the error output is not
240very short and you want to read it in the same process as where you called
241C<command()>, you are set up for a nice deadlock!
242
Petr Baudisb1edc532006-06-24 04:34:29 +0200243The method can be called without any instance or on a specified Git repository
244(in that case the command will be run in the repository context).
245
246In scalar context, it returns all the command output in a single string
247(verbatim).
248
249In array context, it returns an array containing lines printed to the
250command's stdout (without trailing newlines).
251
252In both cases, the command's stdin and stderr are the same as the caller's.
253
254=cut
255
256sub command {
Petr Baudisd79850e2006-06-24 04:34:47 +0200257 my ($fh, $ctx) = command_output_pipe(@_);
Petr Baudisb1edc532006-06-24 04:34:29 +0200258
259 if (not defined wantarray) {
Petr Baudis8b9150e2006-06-24 04:34:44 +0200260 # Nothing to pepper the possible exception with.
261 _cmd_close($fh, $ctx);
Petr Baudisb1edc532006-06-24 04:34:29 +0200262
263 } elsif (not wantarray) {
264 local $/;
265 my $text = <$fh>;
Petr Baudis8b9150e2006-06-24 04:34:44 +0200266 try {
267 _cmd_close($fh, $ctx);
268 } catch Git::Error::Command with {
269 # Pepper with the output:
270 my $E = shift;
271 $E->{'-outputref'} = \$text;
272 throw $E;
273 };
Petr Baudisb1edc532006-06-24 04:34:29 +0200274 return $text;
275
276 } else {
277 my @lines = <$fh>;
Alex Riesen67e4baf2007-01-22 15:58:03 +0100278 defined and chomp for @lines;
Petr Baudis8b9150e2006-06-24 04:34:44 +0200279 try {
280 _cmd_close($fh, $ctx);
281 } catch Git::Error::Command with {
282 my $E = shift;
283 $E->{'-outputref'} = \@lines;
284 throw $E;
285 };
Petr Baudisb1edc532006-06-24 04:34:29 +0200286 return @lines;
287 }
288}
289
290
291=item command_oneline ( COMMAND [, ARGUMENTS... ] )
292
Petr Baudisd43ba462006-06-24 04:34:49 +0200293=item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
294
Petr Baudisb1edc532006-06-24 04:34:29 +0200295Execute the given C<COMMAND> in the same way as command()
296does but always return a scalar string containing the first line
297of the command's standard output.
298
299=cut
300
301sub command_oneline {
Petr Baudisd79850e2006-06-24 04:34:47 +0200302 my ($fh, $ctx) = command_output_pipe(@_);
Petr Baudisb1edc532006-06-24 04:34:29 +0200303
304 my $line = <$fh>;
Petr Baudisd5c77212006-06-24 04:34:51 +0200305 defined $line and chomp $line;
Petr Baudis8b9150e2006-06-24 04:34:44 +0200306 try {
307 _cmd_close($fh, $ctx);
308 } catch Git::Error::Command with {
309 # Pepper with the output:
310 my $E = shift;
311 $E->{'-outputref'} = \$line;
312 throw $E;
313 };
Petr Baudisb1edc532006-06-24 04:34:29 +0200314 return $line;
315}
316
317
Petr Baudisd79850e2006-06-24 04:34:47 +0200318=item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
Petr Baudisb1edc532006-06-24 04:34:29 +0200319
Petr Baudisd43ba462006-06-24 04:34:49 +0200320=item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
321
Petr Baudisb1edc532006-06-24 04:34:29 +0200322Execute the given C<COMMAND> in the same way as command()
323does but return a pipe filehandle from which the command output can be
324read.
325
Petr Baudisd79850e2006-06-24 04:34:47 +0200326The function can return C<($pipe, $ctx)> in array context.
327See C<command_close_pipe()> for details.
328
Petr Baudisb1edc532006-06-24 04:34:29 +0200329=cut
330
Petr Baudisd79850e2006-06-24 04:34:47 +0200331sub command_output_pipe {
332 _command_common_pipe('-|', @_);
333}
Petr Baudisb1edc532006-06-24 04:34:29 +0200334
Petr Baudisb1edc532006-06-24 04:34:29 +0200335
Petr Baudisd79850e2006-06-24 04:34:47 +0200336=item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
337
Petr Baudisd43ba462006-06-24 04:34:49 +0200338=item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
339
Petr Baudisd79850e2006-06-24 04:34:47 +0200340Execute the given C<COMMAND> in the same way as command_output_pipe()
341does but return an input pipe filehandle instead; the command output
342is not captured.
343
344The function can return C<($pipe, $ctx)> in array context.
345See C<command_close_pipe()> for details.
346
347=cut
348
349sub command_input_pipe {
350 _command_common_pipe('|-', @_);
Petr Baudis8b9150e2006-06-24 04:34:44 +0200351}
352
353
354=item command_close_pipe ( PIPE [, CTX ] )
355
Petr Baudisd79850e2006-06-24 04:34:47 +0200356Close the C<PIPE> as returned from C<command_*_pipe()>, checking
Pavel Roskin3dff5372007-02-03 23:49:16 -0500357whether the command finished successfully. The optional C<CTX> argument
Petr Baudis8b9150e2006-06-24 04:34:44 +0200358is required if you want to see the command name in the error message,
Petr Baudisd79850e2006-06-24 04:34:47 +0200359and it is the second value returned by C<command_*_pipe()> when
Petr Baudis8b9150e2006-06-24 04:34:44 +0200360called in array context. The call idiom is:
361
Petr Baudisd79850e2006-06-24 04:34:47 +0200362 my ($fh, $ctx) = $r->command_output_pipe('status');
363 while (<$fh>) { ... }
364 $r->command_close_pipe($fh, $ctx);
Petr Baudis8b9150e2006-06-24 04:34:44 +0200365
366Note that you should not rely on whatever actually is in C<CTX>;
367currently it is simply the command name but in future the context might
368have more complicated structure.
369
370=cut
371
372sub command_close_pipe {
373 my ($self, $fh, $ctx) = _maybe_self(@_);
374 $ctx ||= '<unknown>';
375 _cmd_close($fh, $ctx);
Petr Baudisb1edc532006-06-24 04:34:29 +0200376}
377
378
379=item command_noisy ( COMMAND [, ARGUMENTS... ] )
380
381Execute the given C<COMMAND> in the same way as command() does but do not
382capture the command output - the standard output is not redirected and goes
383to the standard output of the caller application.
384
385While the method is called command_noisy(), you might want to as well use
386it for the most silent Git commands which you know will never pollute your
387stdout but you want to avoid the overhead of the pipe setup when calling them.
388
389The function returns only after the command has finished running.
390
391=cut
392
393sub command_noisy {
394 my ($self, $cmd, @args) = _maybe_self(@_);
Petr Baudisd79850e2006-06-24 04:34:47 +0200395 _check_valid_cmd($cmd);
Petr Baudisb1edc532006-06-24 04:34:29 +0200396
397 my $pid = fork;
398 if (not defined $pid) {
Petr Baudis97b16c02006-06-24 04:34:42 +0200399 throw Error::Simple("fork failed: $!");
Petr Baudisb1edc532006-06-24 04:34:29 +0200400 } elsif ($pid == 0) {
401 _cmd_exec($self, $cmd, @args);
402 }
Petr Baudis8b9150e2006-06-24 04:34:44 +0200403 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
404 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
Petr Baudisb1edc532006-06-24 04:34:29 +0200405 }
406}
407
408
Petr Baudis63df97a2006-06-24 04:34:36 +0200409=item version ()
410
411Return the Git version in use.
412
Petr Baudis63df97a2006-06-24 04:34:36 +0200413=cut
414
Petr Baudis18b0fc12006-09-23 20:20:47 +0200415sub version {
416 my $verstr = command_oneline('--version');
417 $verstr =~ s/^git version //;
418 $verstr;
419}
Petr Baudis63df97a2006-06-24 04:34:36 +0200420
421
Petr Baudiseca1f6f2006-06-24 04:34:31 +0200422=item exec_path ()
423
Petr Baudisd5c77212006-06-24 04:34:51 +0200424Return path to the Git sub-command executables (the same as
Petr Baudiseca1f6f2006-06-24 04:34:31 +0200425C<git --exec-path>). Useful mostly only internally.
426
Petr Baudiseca1f6f2006-06-24 04:34:31 +0200427=cut
428
Petr Baudis18b0fc12006-09-23 20:20:47 +0200429sub exec_path { command_oneline('--exec-path') }
Petr Baudiseca1f6f2006-06-24 04:34:31 +0200430
431
Petr Baudisd5c77212006-06-24 04:34:51 +0200432=item repo_path ()
433
434Return path to the git repository. Must be called on a repository instance.
435
436=cut
437
438sub repo_path { $_[0]->{opts}->{Repository} }
439
440
441=item wc_path ()
442
443Return path to the working copy. Must be called on a repository instance.
444
445=cut
446
447sub wc_path { $_[0]->{opts}->{WorkingCopy} }
448
449
450=item wc_subdir ()
451
452Return path to the subdirectory inside of a working copy. Must be called
453on a repository instance.
454
455=cut
456
457sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
458
459
460=item wc_chdir ( SUBDIR )
461
462Change the working copy subdirectory to work within. The C<SUBDIR> is
463relative to the working copy root directory (not the current subdirectory).
464Must be called on a repository instance attached to a working copy
465and the directory must exist.
466
467=cut
468
469sub wc_chdir {
470 my ($self, $subdir) = @_;
Petr Baudisd5c77212006-06-24 04:34:51 +0200471 $self->wc_path()
472 or throw Error::Simple("bare repository");
473
474 -d $self->wc_path().'/'.$subdir
475 or throw Error::Simple("subdir not found: $!");
476 # Of course we will not "hold" the subdirectory so anyone
477 # can delete it now and we will never know. But at least we tried.
478
479 $self->{opts}->{WorkingSubdir} = $subdir;
480}
481
482
Petr Baudisdc2613d2006-07-03 22:47:55 +0200483=item config ( VARIABLE )
484
Tom Princee0d10e12007-01-28 16:16:53 -0800485Retrieve the configuration C<VARIABLE> in the same manner as C<config>
Petr Baudisdc2613d2006-07-03 22:47:55 +0200486does. In scalar context requires the variable to be set only one time
487(exception is thrown otherwise), in array context returns allows the
488variable to be set multiple times and returns all the values.
489
490Must be called on a repository instance.
491
Tom Princee0d10e12007-01-28 16:16:53 -0800492This currently wraps command('config') so it is not so fast.
Petr Baudisdc2613d2006-07-03 22:47:55 +0200493
494=cut
495
496sub config {
497 my ($self, $var) = @_;
498 $self->repo_path()
499 or throw Error::Simple("not a repository");
500
501 try {
502 if (wantarray) {
Tom Princee0d10e12007-01-28 16:16:53 -0800503 return $self->command('config', '--get-all', $var);
Petr Baudisdc2613d2006-07-03 22:47:55 +0200504 } else {
Tom Princee0d10e12007-01-28 16:16:53 -0800505 return $self->command_oneline('config', '--get', $var);
Petr Baudisdc2613d2006-07-03 22:47:55 +0200506 }
507 } catch Git::Error::Command with {
508 my $E = shift;
509 if ($E->value() == 1) {
510 # Key not found.
511 return undef;
512 } else {
513 throw $E;
514 }
515 };
516}
517
518
Petr Baudis35c49ee2007-05-09 12:49:41 +0200519=item config_bool ( VARIABLE )
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500520
Petr Baudis35c49ee2007-05-09 12:49:41 +0200521Retrieve the bool configuration C<VARIABLE>. The return value
522is usable as a boolean in perl (and C<undef> if it's not defined,
523of course).
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500524
525Must be called on a repository instance.
526
527This currently wraps command('config') so it is not so fast.
528
529=cut
530
Petr Baudis35c49ee2007-05-09 12:49:41 +0200531sub config_bool {
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500532 my ($self, $var) = @_;
533 $self->repo_path()
534 or throw Error::Simple("not a repository");
535
536 try {
Petr Baudis35c49ee2007-05-09 12:49:41 +0200537 my $val = $self->command_oneline('config', '--bool', '--get',
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500538 $var);
Petr Baudis35c49ee2007-05-09 12:49:41 +0200539 return undef unless defined $val;
540 return $val eq 'true';
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500541 } catch Git::Error::Command with {
542 my $E = shift;
543 if ($E->value() == 1) {
544 # Key not found.
545 return undef;
546 } else {
547 throw $E;
548 }
549 };
550}
551
Jakub Narebski346d2032007-11-23 19:04:52 +0100552=item config_int ( VARIABLE )
553
554Retrieve the integer configuration C<VARIABLE>. The return value
555is simple decimal number. An optional value suffix of 'k', 'm',
556or 'g' in the config file will cause the value to be multiplied
557by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
558It would return C<undef> if configuration variable is not defined,
559
560Must be called on a repository instance.
561
562This currently wraps command('config') so it is not so fast.
563
564=cut
565
566sub config_int {
567 my ($self, $var) = @_;
568 $self->repo_path()
569 or throw Error::Simple("not a repository");
570
571 try {
572 return $self->command_oneline('config', '--int', '--get', $var);
573 } catch Git::Error::Command with {
574 my $E = shift;
575 if ($E->value() == 1) {
576 # Key not found.
577 return undef;
578 } else {
579 throw $E;
580 }
581 };
582}
Theodore Ts'o7b9a13e2007-02-20 15:13:42 -0500583
Junio C Hamanob4c61ed2007-12-05 00:50:23 -0800584=item get_colorbool ( NAME )
585
586Finds if color should be used for NAMEd operation from the configuration,
587and returns boolean (true for "use color", false for "do not use color").
588
589=cut
590
591sub get_colorbool {
592 my ($self, $var) = @_;
593 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
594 my $use_color = $self->command_oneline('config', '--get-colorbool',
595 $var, $stdout_to_tty);
596 return ($use_color eq 'true');
597}
598
599=item get_color ( SLOT, COLOR )
600
601Finds color for SLOT from the configuration, while defaulting to COLOR,
602and returns the ANSI color escape sequence:
603
604 print $repo->get_color("color.interactive.prompt", "underline blue white");
605 print "some text";
606 print $repo->get_color("", "normal");
607
608=cut
609
610sub get_color {
611 my ($self, $slot, $default) = @_;
612 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
613 if (!defined $color) {
614 $color = "";
615 }
616 return $color;
617}
618
Petr Baudisc7a30e52006-07-03 22:48:01 +0200619=item ident ( TYPE | IDENTSTR )
620
621=item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
622
623This suite of functions retrieves and parses ident information, as stored
624in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
625C<TYPE> can be either I<author> or I<committer>; case is insignificant).
626
627The C<ident> method retrieves the ident information from C<git-var>
628and either returns it as a scalar string or as an array with the fields parsed.
629Alternatively, it can take a prepared ident string (e.g. from the commit
630object) and just parse it.
631
632C<ident_person> returns the person part of the ident - name and email;
633it can take the same arguments as C<ident> or the array returned by C<ident>.
634
635The synopsis is like:
636
637 my ($name, $email, $time_tz) = ident('author');
638 "$name <$email>" eq ident_person('author');
639 "$name <$email>" eq ident_person($name);
640 $time_tz =~ /^\d+ [+-]\d{4}$/;
641
642Both methods must be called on a repository instance.
643
644=cut
645
646sub ident {
647 my ($self, $type) = @_;
648 my $identstr;
649 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
650 $identstr = $self->command_oneline('var', 'GIT_'.uc($type).'_IDENT');
651 } else {
652 $identstr = $type;
653 }
654 if (wantarray) {
655 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
656 } else {
657 return $identstr;
658 }
659}
660
661sub ident_person {
662 my ($self, @ident) = @_;
663 $#ident == 0 and @ident = $self->ident($ident[0]);
664 return "$ident[0] <$ident[1]>";
665}
666
667
Petr Baudis24c4b712006-06-25 03:54:26 +0200668=item hash_object ( TYPE, FILENAME )
Petr Baudisb1edc532006-06-24 04:34:29 +0200669
Petr Baudisb1edc532006-06-24 04:34:29 +0200670Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
Petr Baudis24c4b712006-06-25 03:54:26 +0200671C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>,
672C<commit>, C<tree>).
Petr Baudisb1edc532006-06-24 04:34:29 +0200673
Petr Baudisb1edc532006-06-24 04:34:29 +0200674The method can be called without any instance or on a specified Git repository,
675it makes zero difference.
676
677The function returns the SHA1 hash.
678
Petr Baudisb1edc532006-06-24 04:34:29 +0200679=cut
680
Petr Baudis18b0fc12006-09-23 20:20:47 +0200681# TODO: Support for passing FILEHANDLE instead of FILENAME
Petr Baudise6634ac2006-07-02 01:38:56 +0200682sub hash_object {
683 my ($self, $type, $file) = _maybe_self(@_);
Petr Baudis18b0fc12006-09-23 20:20:47 +0200684 command_oneline('hash-object', '-t', $type, $file);
Petr Baudise6634ac2006-07-02 01:38:56 +0200685}
Petr Baudisb1edc532006-06-24 04:34:29 +0200686
687
Petr Baudis8b9150e2006-06-24 04:34:44 +0200688
Petr Baudisb1edc532006-06-24 04:34:29 +0200689=back
690
Petr Baudis97b16c02006-06-24 04:34:42 +0200691=head1 ERROR HANDLING
Petr Baudisb1edc532006-06-24 04:34:29 +0200692
Petr Baudis97b16c02006-06-24 04:34:42 +0200693All functions are supposed to throw Perl exceptions in case of errors.
Petr Baudis8b9150e2006-06-24 04:34:44 +0200694See the L<Error> module on how to catch those. Most exceptions are mere
695L<Error::Simple> instances.
696
697However, the C<command()>, C<command_oneline()> and C<command_noisy()>
698functions suite can throw C<Git::Error::Command> exceptions as well: those are
699thrown when the external command returns an error code and contain the error
700code as well as access to the captured command's output. The exception class
701provides the usual C<stringify> and C<value> (command's exit code) methods and
702in addition also a C<cmd_output> method that returns either an array or a
703string with the captured command output (depending on the original function
704call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
705returns the command and its arguments (but without proper quoting).
706
Petr Baudisd79850e2006-06-24 04:34:47 +0200707Note that the C<command_*_pipe()> functions cannot throw this exception since
Petr Baudis8b9150e2006-06-24 04:34:44 +0200708it has no idea whether the command failed or not. You will only find out
709at the time you C<close> the pipe; if you want to have that automated,
710use C<command_close_pipe()>, which can throw the exception.
711
712=cut
713
714{
715 package Git::Error::Command;
716
717 @Git::Error::Command::ISA = qw(Error);
718
719 sub new {
720 my $self = shift;
721 my $cmdline = '' . shift;
722 my $value = 0 + shift;
723 my $outputref = shift;
724 my(@args) = ();
725
726 local $Error::Depth = $Error::Depth + 1;
727
728 push(@args, '-cmdline', $cmdline);
729 push(@args, '-value', $value);
730 push(@args, '-outputref', $outputref);
731
732 $self->SUPER::new(-text => 'command returned error', @args);
733 }
734
735 sub stringify {
736 my $self = shift;
737 my $text = $self->SUPER::stringify;
738 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
739 }
740
741 sub cmdline {
742 my $self = shift;
743 $self->{'-cmdline'};
744 }
745
746 sub cmd_output {
747 my $self = shift;
748 my $ref = $self->{'-outputref'};
749 defined $ref or undef;
750 if (ref $ref eq 'ARRAY') {
751 return @$ref;
752 } else { # SCALAR
753 return $$ref;
754 }
755 }
756}
757
758=over 4
759
760=item git_cmd_try { CODE } ERRMSG
761
762This magical statement will automatically catch any C<Git::Error::Command>
763exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
764on its lips; the message will have %s substituted for the command line
765and %d for the exit status. This statement is useful mostly for producing
766more user-friendly error messages.
767
768In case of no exception caught the statement returns C<CODE>'s return value.
769
770Note that this is the only auto-exported function.
771
772=cut
773
774sub git_cmd_try(&$) {
775 my ($code, $errmsg) = @_;
776 my @result;
777 my $err;
778 my $array = wantarray;
779 try {
780 if ($array) {
781 @result = &$code;
782 } else {
783 $result[0] = &$code;
784 }
785 } catch Git::Error::Command with {
786 my $E = shift;
787 $err = $errmsg;
788 $err =~ s/\%s/$E->cmdline()/ge;
789 $err =~ s/\%d/$E->value()/ge;
790 # We can't croak here since Error.pm would mangle
791 # that to Error::Simple.
792 };
793 $err and croak $err;
794 return $array ? @result : $result[0];
795}
796
797
798=back
Petr Baudisb1edc532006-06-24 04:34:29 +0200799
800=head1 COPYRIGHT
801
802Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
803
804This module is free software; it may be used, copied, modified
805and distributed under the terms of the GNU General Public Licence,
806either version 2, or (at your option) any later version.
807
808=cut
809
810
811# Take raw method argument list and return ($obj, @args) in case
812# the method was called upon an instance and (undef, @args) if
813# it was called directly.
814sub _maybe_self {
815 # This breaks inheritance. Oh well.
816 ref $_[0] eq 'Git' ? @_ : (undef, @_);
817}
818
Petr Baudisd79850e2006-06-24 04:34:47 +0200819# Check if the command id is something reasonable.
820sub _check_valid_cmd {
821 my ($cmd) = @_;
822 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
823}
824
825# Common backend for the pipe creators.
826sub _command_common_pipe {
827 my $direction = shift;
Petr Baudisd43ba462006-06-24 04:34:49 +0200828 my ($self, @p) = _maybe_self(@_);
829 my (%opts, $cmd, @args);
830 if (ref $p[0]) {
831 ($cmd, @args) = @{shift @p};
832 %opts = ref $p[0] ? %{$p[0]} : @p;
833 } else {
834 ($cmd, @args) = @p;
835 }
Petr Baudisd79850e2006-06-24 04:34:47 +0200836 _check_valid_cmd($cmd);
837
Petr Baudisa6065b52006-06-25 03:54:23 +0200838 my $fh;
Alex Riesend3b17852007-01-22 17:14:56 +0100839 if ($^O eq 'MSWin32') {
Petr Baudisa6065b52006-06-25 03:54:23 +0200840 # ActiveState Perl
841 #defined $opts{STDERR} and
842 # warn 'ignoring STDERR option - running w/ ActiveState';
843 $direction eq '-|' or
844 die 'input pipe for ActiveState not implemented';
Alex Riesenbed118d2007-01-22 17:16:05 +0100845 # the strange construction with *ACPIPE is just to
846 # explain the tie below that we want to bind to
847 # a handle class, not scalar. It is not known if
848 # it is something specific to ActiveState Perl or
849 # just a Perl quirk.
850 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
851 $fh = *ACPIPE;
Petr Baudisa6065b52006-06-25 03:54:23 +0200852
853 } else {
854 my $pid = open($fh, $direction);
855 if (not defined $pid) {
856 throw Error::Simple("open failed: $!");
857 } elsif ($pid == 0) {
858 if (defined $opts{STDERR}) {
859 close STDERR;
860 }
861 if ($opts{STDERR}) {
862 open (STDERR, '>&', $opts{STDERR})
863 or die "dup failed: $!";
864 }
865 _cmd_exec($self, $cmd, @args);
Petr Baudisd43ba462006-06-24 04:34:49 +0200866 }
Petr Baudisd79850e2006-06-24 04:34:47 +0200867 }
868 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
869}
870
Petr Baudisb1edc532006-06-24 04:34:29 +0200871# When already in the subprocess, set up the appropriate state
872# for the given repository and execute the git command.
873sub _cmd_exec {
874 my ($self, @args) = @_;
875 if ($self) {
Petr Baudisd5c77212006-06-24 04:34:51 +0200876 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
877 $self->wc_path() and chdir($self->wc_path());
878 $self->wc_subdir() and chdir($self->wc_subdir());
Petr Baudisb1edc532006-06-24 04:34:29 +0200879 }
Petr Baudis97b16c02006-06-24 04:34:42 +0200880 _execv_git_cmd(@args);
Ask Bjørn Hansen6aaa65d2007-11-06 02:54:01 -0800881 die qq[exec "@args" failed: $!];
Petr Baudisb1edc532006-06-24 04:34:29 +0200882}
883
Petr Baudis8062f812006-06-24 04:34:34 +0200884# Execute the given Git command ($_[0]) with arguments ($_[1..])
885# by searching for it at proper places.
Petr Baudis18b0fc12006-09-23 20:20:47 +0200886sub _execv_git_cmd { exec('git', @_); }
Petr Baudis8062f812006-06-24 04:34:34 +0200887
Petr Baudisb1edc532006-06-24 04:34:29 +0200888# Close pipe to a subprocess.
889sub _cmd_close {
Petr Baudis8b9150e2006-06-24 04:34:44 +0200890 my ($fh, $ctx) = @_;
Petr Baudisb1edc532006-06-24 04:34:29 +0200891 if (not close $fh) {
892 if ($!) {
893 # It's just close, no point in fatalities
894 carp "error closing pipe: $!";
895 } elsif ($? >> 8) {
Petr Baudis8b9150e2006-06-24 04:34:44 +0200896 # The caller should pepper this.
897 throw Git::Error::Command($ctx, $? >> 8);
Petr Baudisb1edc532006-06-24 04:34:29 +0200898 }
899 # else we might e.g. closed a live stream; the command
900 # dying of SIGPIPE would drive us here.
901 }
902}
903
904
Petr Baudisb1edc532006-06-24 04:34:29 +0200905sub DESTROY { }
906
907
Petr Baudisa6065b52006-06-25 03:54:23 +0200908# Pipe implementation for ActiveState Perl.
909
910package Git::activestate_pipe;
911use strict;
912
913sub TIEHANDLE {
914 my ($class, @params) = @_;
915 # FIXME: This is probably horrible idea and the thing will explode
916 # at the moment you give it arguments that require some quoting,
917 # but I have no ActiveState clue... --pasky
Alex Riesend3b17852007-01-22 17:14:56 +0100918 # Let's just hope ActiveState Perl does at least the quoting
919 # correctly.
920 my @data = qx{git @params};
Petr Baudisa6065b52006-06-25 03:54:23 +0200921 bless { i => 0, data => \@data }, $class;
922}
923
924sub READLINE {
925 my $self = shift;
926 if ($self->{i} >= scalar @{$self->{data}}) {
927 return undef;
928 }
Alex Riesen2f5b3982007-08-22 18:13:07 +0200929 my $i = $self->{i};
930 if (wantarray) {
931 $self->{i} = $#{$self->{'data'}} + 1;
932 return splice(@{$self->{'data'}}, $i);
933 }
934 $self->{i} = $i + 1;
935 return $self->{'data'}->[ $i ];
Petr Baudisa6065b52006-06-25 03:54:23 +0200936}
937
938sub CLOSE {
939 my $self = shift;
940 delete $self->{data};
941 delete $self->{i};
942}
943
944sub EOF {
945 my $self = shift;
946 return ($self->{i} >= scalar @{$self->{data}});
947}
948
949
Petr Baudisb1edc532006-06-24 04:34:29 +02009501; # Famous last words