1Git(3)                User Contributed Perl Documentation               Git(3)
2
3
4

NAME

6       Git - Perl interface to the Git version control system
7

SYNOPSIS

9         use Git;
10
11         my $version = Git::command_oneline('version');
12
13         git_cmd_try { Git::command_noisy('update-server-info') }
14                     '%s failed w/ code %d';
15
16         my $repo = Git->repository (Directory => '/srv/git/cogito.git');
17
18
19         my @revs = $repo->command('rev-list', '--since=last monday', '--all');
20
21         my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
22         my $lastrev = <$fh>; chomp $lastrev;
23         $repo->command_close_pipe($fh, $c);
24
25         my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
26                                               STDERR => 0 );
27
28         my $sha1 = $repo->hash_and_insert_object('file.txt');
29         my $tempfile = tempfile();
30         my $size = $repo->cat_blob($sha1, $tempfile);
31

DESCRIPTION

33       This module provides Perl scripts easy way to interface the Git version
34       control system. The modules have an easy and well-tested way to call
35       arbitrary Git commands; in the future, the interface will also provide
36       specialized methods for doing easily operations which are not totally
37       trivial to do over the generic command interface.
38
39       While some commands can be executed outside of any context (e.g.
40       'version' or 'init'), most operations require a repository context,
41       which in practice means getting an instance of the Git object using the
42       repository() constructor.  (In the future, we will also get a
43       new_repository() constructor.) All commands called as methods of the
44       object are then executed in the context of the repository.
45
46       Part of the "repository state" is also information about path to the
47       attached working copy (unless you work with a bare repository). You can
48       also navigate inside of the working copy using the "wc_chdir()" method.
49       (Note that the repository object is self-contained and will not change
50       working directory of your process.)
51
52       TODO: In the future, we might also do
53
54               my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
55               $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
56               my @refs = $remoterepo->refs();
57
58       Currently, the module merely wraps calls to external Git tools. In the
59       future, it will provide a much faster way to interact with Git by
60       linking directly to libgit. This should be completely opaque to the
61       user, though (performance increase notwithstanding).
62

CONSTRUCTORS

64       repository ( OPTIONS )
65       repository ( DIRECTORY )
66       repository ()
67           Construct a new repository object.  "OPTIONS" are passed in a hash
68           like fashion, using key and value pairs.  Possible options are:
69
70           Repository - Path to the Git repository.
71
72           WorkingCopy - Path to the associated working copy; not strictly
73           required as many commands will happily crunch on a bare repository.
74
75           WorkingSubdir - Subdirectory in the working copy to work inside.
76           Just left undefined if you do not want to limit the scope of
77           operations.
78
79           Directory - Path to the Git working directory in its usual setup.
80           The ".git" directory is searched in the directory and all the
81           parent directories; if found, "WorkingCopy" is set to the directory
82           containing it and "Repository" to the ".git" directory itself. If
83           no ".git" directory was found, the "Directory" is assumed to be a
84           bare repository, "Repository" is set to point at it and
85           "WorkingCopy" is left undefined.  If the $GIT_DIR environment
86           variable is set, things behave as expected as well.
87
88           You should not use both "Directory" and either of "Repository" and
89           "WorkingCopy" - the results of that are undefined.
90
91           Alternatively, a directory path may be passed as a single scalar
92           argument to the constructor; it is equivalent to setting only the
93           "Directory" option field.
94
95           Calling the constructor with no options whatsoever is equivalent to
96           calling it with "Directory => '.'". In general, if you are building
97           a standard porcelain command, simply doing "Git->repository()"
98           should do the right thing and setup the object to reflect exactly
99           where the user is right now.
100

METHODS

102       command ( COMMAND [, ARGUMENTS... ] )
103       command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
104           Execute the given Git "COMMAND" (specify it without the 'git-'
105           prefix), optionally with the specified extra "ARGUMENTS".
106
107           The second more elaborate form can be used if you want to further
108           adjust the command execution. Currently, only one option is
109           supported:
110
111           STDERR - How to deal with the command's error output. By default
112           ("undef") it is delivered to the caller's "STDERR". A false value
113           (0 or '') will cause it to be thrown away. If you want to process
114           it, you can get it in a filehandle you specify, but you must be
115           extremely careful; if the error output is not very short and you
116           want to read it in the same process as where you called
117           "command()", you are set up for a nice deadlock!
118
119           The method can be called without any instance or on a specified Git
120           repository (in that case the command will be run in the repository
121           context).
122
123           In scalar context, it returns all the command output in a single
124           string (verbatim).
125
126           In array context, it returns an array containing lines printed to
127           the command's stdout (without trailing newlines).
128
129           In both cases, the command's stdin and stderr are the same as the
130           caller's.
131
132       command_oneline ( COMMAND [, ARGUMENTS... ] )
133       command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
134           Execute the given "COMMAND" in the same way as command() does but
135           always return a scalar string containing the first line of the
136           command's standard output.
137
138       command_output_pipe ( COMMAND [, ARGUMENTS... ] )
139       command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
140           Execute the given "COMMAND" in the same way as command() does but
141           return a pipe filehandle from which the command output can be read.
142
143           The function can return "($pipe, $ctx)" in array context.  See
144           "command_close_pipe()" for details.
145
146       command_input_pipe ( COMMAND [, ARGUMENTS... ] )
147       command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
148           Execute the given "COMMAND" in the same way as
149           command_output_pipe() does but return an input pipe filehandle
150           instead; the command output is not captured.
151
152           The function can return "($pipe, $ctx)" in array context.  See
153           "command_close_pipe()" for details.
154
155       command_close_pipe ( PIPE [, CTX ] )
156           Close the "PIPE" as returned from "command_*_pipe()", checking
157           whether the command finished successfully. The optional "CTX"
158           argument is required if you want to see the command name in the
159           error message, and it is the second value returned by
160           "command_*_pipe()" when called in array context. The call idiom is:
161
162                   my ($fh, $ctx) = $r->command_output_pipe('status');
163                   while (<$fh>) { ... }
164                   $r->command_close_pipe($fh, $ctx);
165
166           Note that you should not rely on whatever actually is in "CTX";
167           currently it is simply the command name but in future the context
168           might have more complicated structure.
169
170       command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
171           Execute the given "COMMAND" in the same way as
172           command_output_pipe() does but return both an input pipe filehandle
173           and an output pipe filehandle.
174
175           The function will return return "($pid, $pipe_in, $pipe_out,
176           $ctx)".  See "command_close_bidi_pipe()" for details.
177
178       command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
179           Close the "PIPE_IN" and "PIPE_OUT" as returned from
180           "command_bidi_pipe()", checking whether the command finished
181           successfully. The optional "CTX" argument is required if you want
182           to see the command name in the error message, and it is the fourth
183           value returned by "command_bidi_pipe()".  The call idiom is:
184
185                   my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
186                   print $out "000000000\n";
187                   while (<$in>) { ... }
188                   $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
189
190           Note that you should not rely on whatever actually is in "CTX";
191           currently it is simply the command name but in future the context
192           might have more complicated structure.
193
194           "PIPE_IN" and "PIPE_OUT" may be "undef" if they have been closed
195           prior to calling this function.  This may be useful in a query-
196           response type of commands where caller first writes a query and
197           later reads response, eg:
198
199                   my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
200                   print $out "000000000\n";
201                   close $out;
202                   while (<$in>) { ... }
203                   $r->command_close_bidi_pipe($pid, $in, undef, $ctx);
204
205           This idiom may prevent potential dead locks caused by data sent to
206           the output pipe not being flushed and thus not reaching the
207           executed command.
208
209       command_noisy ( COMMAND [, ARGUMENTS... ] )
210           Execute the given "COMMAND" in the same way as command() does but
211           do not capture the command output - the standard output is not
212           redirected and goes to the standard output of the caller
213           application.
214
215           While the method is called command_noisy(), you might want to as
216           well use it for the most silent Git commands which you know will
217           never pollute your stdout but you want to avoid the overhead of the
218           pipe setup when calling them.
219
220           The function returns only after the command has finished running.
221
222       version ()
223           Return the Git version in use.
224
225       exec_path ()
226           Return path to the Git sub-command executables (the same as "git
227           --exec-path"). Useful mostly only internally.
228
229       html_path ()
230           Return path to the Git html documentation (the same as "git
231           --html-path"). Useful mostly only internally.
232
233       get_tz_offset ( TIME )
234           Return the time zone offset from GMT in the form +/-HHMM where HH
235           is the number of hours from GMT and MM is the number of minutes.
236           This is the equivalent of what strftime("%z", ...) would provide on
237           a GNU platform.
238
239           If TIME is not supplied, the current local time is used.
240
241       prompt ( PROMPT , ISPASSWORD  )
242           Query user "PROMPT" and return answer from user.
243
244           Honours GIT_ASKPASS and SSH_ASKPASS environment variables for
245           querying the user. If no *_ASKPASS variable is set or an error
246           occoured, the terminal is tried as a fallback.  If "ISPASSWORD" is
247           set and true, the terminal disables echo.
248
249       repo_path ()
250           Return path to the git repository. Must be called on a repository
251           instance.
252
253       wc_path ()
254           Return path to the working copy. Must be called on a repository
255           instance.
256
257       wc_subdir ()
258           Return path to the subdirectory inside of a working copy. Must be
259           called on a repository instance.
260
261       wc_chdir ( SUBDIR )
262           Change the working copy subdirectory to work within. The "SUBDIR"
263           is relative to the working copy root directory (not the current
264           subdirectory).  Must be called on a repository instance attached to
265           a working copy and the directory must exist.
266
267       config ( VARIABLE )
268           Retrieve the configuration "VARIABLE" in the same manner as
269           "config" does. In scalar context requires the variable to be set
270           only one time (exception is thrown otherwise), in array context
271           returns allows the variable to be set multiple times and returns
272           all the values.
273
274       config_bool ( VARIABLE )
275           Retrieve the bool configuration "VARIABLE". The return value is
276           usable as a boolean in perl (and "undef" if it's not defined, of
277           course).
278
279       config_path ( VARIABLE )
280           Retrieve the path configuration "VARIABLE". The return value is an
281           expanded path or "undef" if it's not defined.
282
283       config_int ( VARIABLE )
284           Retrieve the integer configuration "VARIABLE". The return value is
285           simple decimal number.  An optional value suffix of 'k', 'm', or
286           'g' in the config file will cause the value to be multiplied by
287           1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.  It
288           would return "undef" if configuration variable is not defined,
289
290       get_colorbool ( NAME )
291           Finds if color should be used for NAMEd operation from the
292           configuration, and returns boolean (true for "use color", false for
293           "do not use color").
294
295       get_color ( SLOT, COLOR )
296           Finds color for SLOT from the configuration, while defaulting to
297           COLOR, and returns the ANSI color escape sequence:
298
299                   print $repo->get_color("color.interactive.prompt", "underline blue white");
300                   print "some text";
301                   print $repo->get_color("", "normal");
302
303       remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
304           This function returns a hashref of refs stored in a given remote
305           repository.  The hash is in the format "refname =\" hash>. For
306           tags, the "refname" entry contains the tag object while a
307           "refname^{}" entry gives the tagged objects.
308
309           "REPOSITORY" has the same meaning as the appropriate
310           "git-ls-remote" argument; either a URL or a remote name (if called
311           on a repository instance).  "GROUPS" is an optional arrayref that
312           can contain 'tags' to return all the tags and/or 'heads' to return
313           all the heads. "REFGLOB" is an optional array of strings containing
314           a shell-like glob to further limit the refs returned in the hash;
315           the meaning is again the same as the appropriate "git-ls-remote"
316           argument.
317
318           This function may or may not be called on a repository instance. In
319           the former case, remote names as defined in the repository are
320           recognized as repository specifiers.
321
322       ident ( TYPE | IDENTSTR )
323       ident_person ( TYPE | IDENTSTR | IDENTARRAY )
324           This suite of functions retrieves and parses ident information, as
325           stored in the commit and tag objects or produced by "var
326           GIT_type_IDENT" (thus "TYPE" can be either author or committer;
327           case is insignificant).
328
329           The "ident" method retrieves the ident information from "git var"
330           and either returns it as a scalar string or as an array with the
331           fields parsed.  Alternatively, it can take a prepared ident string
332           (e.g. from the commit object) and just parse it.
333
334           "ident_person" returns the person part of the ident - name and
335           email; it can take the same arguments as "ident" or the array
336           returned by "ident".
337
338           The synopsis is like:
339
340                   my ($name, $email, $time_tz) = ident('author');
341                   "$name <$email>" eq ident_person('author');
342                   "$name <$email>" eq ident_person($name);
343                   $time_tz =~ /^\d+ [+-]\d{4}$/;
344
345       hash_object ( TYPE, FILENAME )
346           Compute the SHA1 object id of the given "FILENAME" considering it
347           is of the "TYPE" object type ("blob", "commit", "tree").
348
349           The method can be called without any instance or on a specified Git
350           repository, it makes zero difference.
351
352           The function returns the SHA1 hash.
353
354       hash_and_insert_object ( FILENAME )
355           Compute the SHA1 object id of the given "FILENAME" and add the
356           object to the object database.
357
358           The function returns the SHA1 hash.
359
360       cat_blob ( SHA1, FILEHANDLE )
361           Prints the contents of the blob identified by "SHA1" to
362           "FILEHANDLE" and returns the number of bytes printed.
363
364       credential_read( FILEHANDLE )
365           Reads credential key-value pairs from "FILEHANDLE".  Reading stops
366           at EOF or when an empty line is encountered.  Each line must be of
367           the form "key=value" with a non-empty key.  Function returns hash
368           with all read values.  Any white space (other than new-line
369           character) is preserved.
370
371       credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
372           Writes credential key-value pairs from hash referenced by
373           "CREDENTIAL_HASHREF" to "FILEHANDLE".  Keys and values cannot
374           contain new-lines or NUL bytes characters, and key cannot contain
375           equal signs nor be empty (if they do Error::Simple is thrown).  Any
376           white space is preserved.  If value for a key is "undef", it will
377           be skipped.
378
379           If 'url' key exists it will be written first.  (All the other key-
380           value pairs are written in sorted order but you should not depend
381           on that).  Once all lines are written, an empty line is printed.
382
383       credential( CREDENTIAL_HASHREF [, OPERATION ] )
384       credential( CREDENTIAL_HASHREF, CODE )
385           Executes "git credential" for a given set of credentials and
386           specified operation.  In both forms "CREDENTIAL_HASHREF" needs to
387           be a reference to a hash which stores credentials.  Under certain
388           conditions the hash can change.
389
390           In the first form, "OPERATION" can be 'fill', 'approve' or
391           'reject', and function will execute corresponding "git credential"
392           sub-command.  If it's omitted 'fill' is assumed.  In case of 'fill'
393           the values stored in "CREDENTIAL_HASHREF" will be changed to the
394           ones returned by the "git credential fill" command.  The usual
395           usage would look something like:
396
397                   my %cred = (
398                           'protocol' => 'https',
399                           'host' => 'example.com',
400                           'username' => 'bob'
401                   );
402                   Git::credential \%cred;
403                   if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
404                           Git::credential \%cred, 'approve';
405                           ... do more stuff ...
406                   } else {
407                           Git::credential \%cred, 'reject';
408                   }
409
410           In the second form, "CODE" needs to be a reference to a subroutine.
411           The function will execute "git credential fill" to fill the
412           provided credential hash, then call "CODE" with
413           "CREDENTIAL_HASHREF" as the sole argument.  If "CODE"'s return
414           value is defined, the function will execute "git credential
415           approve" (if return value yields true) or "git credential reject"
416           (if return value is false).  If the return value is undef, nothing
417           at all is executed; this is useful, for example, if the credential
418           could neither be verified nor rejected due to an unrelated network
419           error.  The return value is the same as what "CODE" returns.  With
420           this form, the usage might look as follows:
421
422                   if (Git::credential {
423                           'protocol' => 'https',
424                           'host' => 'example.com',
425                           'username' => 'bob'
426                   }, sub {
427                           my $cred = shift;
428                           return !!try_to_authenticate($cred->{'username'},
429                                                        $cred->{'password'});
430                   }) {
431                           ... do more stuff ...
432                   }
433
434       temp_acquire ( NAME )
435           Attempts to retrieve the temporary file mapped to the string
436           "NAME". If an associated temp file has not been created this
437           session or was closed, it is created, cached, and set for autoflush
438           and binmode.
439
440           Internally locks the file mapped to "NAME". This lock must be
441           released with "temp_release()" when the temp file is no longer
442           needed. Subsequent attempts to retrieve temporary files mapped to
443           the same "NAME" while still locked will cause an error. This
444           locking mechanism provides a weak guarantee and is not threadsafe.
445           It does provide some error checking to help prevent temp file refs
446           writing over one another.
447
448           In general, the File::Handle returned should not be closed by
449           consumers as it defeats the purpose of this caching mechanism. If
450           you need to close the temp file handle, then you should use
451           File::Temp or another temp file faculty directly. If a handle is
452           closed and then requested again, then a warning will issue.
453
454       temp_release ( NAME )
455       temp_release ( FILEHANDLE )
456           Releases a lock acquired through "temp_acquire()". Can be called
457           either with the "NAME" mapping used when acquiring the temp file or
458           with the "FILEHANDLE" referencing a locked temp file.
459
460           Warns if an attempt is made to release a file that is not locked.
461
462           The temp file will be truncated before being released. This can
463           help to reduce disk I/O where the system is smart enough to detect
464           the truncation while data is in the output buffers. Beware that
465           after the temp file is released and truncated, any operations on
466           that file may fail miserably until it is re-acquired. All contents
467           are lost between each release and acquire mapped to the same
468           string.
469
470       temp_reset ( FILEHANDLE )
471           Truncates and resets the position of the "FILEHANDLE".
472
473       temp_path ( NAME )
474       temp_path ( FILEHANDLE )
475           Returns the filename associated with the given tempfile.
476

ERROR HANDLING

478       All functions are supposed to throw Perl exceptions in case of errors.
479       See the Error module on how to catch those. Most exceptions are mere
480       Error::Simple instances.
481
482       However, the "command()", "command_oneline()" and "command_noisy()"
483       functions suite can throw "Git::Error::Command" exceptions as well:
484       those are thrown when the external command returns an error code and
485       contain the error code as well as access to the captured command's
486       output. The exception class provides the usual "stringify" and "value"
487       (command's exit code) methods and in addition also a "cmd_output"
488       method that returns either an array or a string with the captured
489       command output (depending on the original function call context;
490       "command_noisy()" returns "undef") and $<cmdline> which returns the
491       command and its arguments (but without proper quoting).
492
493       Note that the "command_*_pipe()" functions cannot throw this exception
494       since it has no idea whether the command failed or not. You will only
495       find out at the time you "close" the pipe; if you want to have that
496       automated, use "command_close_pipe()", which can throw the exception.
497
498       git_cmd_try { CODE } ERRMSG
499           This magical statement will automatically catch any
500           "Git::Error::Command" exceptions thrown by "CODE" and make your
501           program die with "ERRMSG" on its lips; the message will have %s
502           substituted for the command line and %d for the exit status. This
503           statement is useful mostly for producing more user-friendly error
504           messages.
505
506           In case of no exception caught the statement returns "CODE"'s
507           return value.
508
509           Note that this is the only auto-exported function.
510
512       Copyright 2006 by Petr Baudis <pasky@suse.cz>.
513
514       This module is free software; it may be used, copied, modified and
515       distributed under the terms of the GNU General Public Licence, either
516       version 2, or (at your option) any later version.
517
518
519
520perl v5.16.3                      2013-06-10                            Git(3)
Impressum