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 "($pid, $pipe_in, $pipe_out, $ctx)".  See
176           "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       get_record ( FILEHANDLE, INPUT_RECORD_SEPARATOR )
242           Read one record from FILEHANDLE delimited by
243           INPUT_RECORD_SEPARATOR, removing any trailing
244           INPUT_RECORD_SEPARATOR.
245
246       prompt ( PROMPT , ISPASSWORD  )
247           Query user "PROMPT" and return answer from user.
248
249           Honours GIT_ASKPASS and SSH_ASKPASS environment variables for
250           querying the user. If no *_ASKPASS variable is set or an error
251           occoured, the terminal is tried as a fallback.  If "ISPASSWORD" is
252           set and true, the terminal disables echo.
253
254       repo_path ()
255           Return path to the git repository. Must be called on a repository
256           instance.
257
258       wc_path ()
259           Return path to the working copy. Must be called on a repository
260           instance.
261
262       wc_subdir ()
263           Return path to the subdirectory inside of a working copy. Must be
264           called on a repository instance.
265
266       wc_chdir ( SUBDIR )
267           Change the working copy subdirectory to work within. The "SUBDIR"
268           is relative to the working copy root directory (not the current
269           subdirectory).  Must be called on a repository instance attached to
270           a working copy and the directory must exist.
271
272       config ( VARIABLE )
273           Retrieve the configuration "VARIABLE" in the same manner as
274           "config" does. In scalar context requires the variable to be set
275           only one time (exception is thrown otherwise), in array context
276           returns allows the variable to be set multiple times and returns
277           all the values.
278
279       config_bool ( VARIABLE )
280           Retrieve the bool configuration "VARIABLE". The return value is
281           usable as a boolean in perl (and "undef" if it's not defined, of
282           course).
283
284       config_path ( VARIABLE )
285           Retrieve the path configuration "VARIABLE". The return value is an
286           expanded path or "undef" if it's not defined.
287
288       config_int ( VARIABLE )
289           Retrieve the integer configuration "VARIABLE". The return value is
290           simple decimal number.  An optional value suffix of 'k', 'm', or
291           'g' in the config file will cause the value to be multiplied by
292           1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.  It
293           would return "undef" if configuration variable is not defined.
294
295       get_colorbool ( NAME )
296           Finds if color should be used for NAMEd operation from the
297           configuration, and returns boolean (true for "use color", false for
298           "do not use color").
299
300       get_color ( SLOT, COLOR )
301           Finds color for SLOT from the configuration, while defaulting to
302           COLOR, and returns the ANSI color escape sequence:
303
304                   print $repo->get_color("color.interactive.prompt", "underline blue white");
305                   print "some text";
306                   print $repo->get_color("", "normal");
307
308       remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
309           This function returns a hashref of refs stored in a given remote
310           repository.  The hash is in the format "refname =\" hash>. For
311           tags, the "refname" entry contains the tag object while a
312           "refname^{}" entry gives the tagged objects.
313
314           "REPOSITORY" has the same meaning as the appropriate
315           "git-ls-remote" argument; either a URL or a remote name (if called
316           on a repository instance).  "GROUPS" is an optional arrayref that
317           can contain 'tags' to return all the tags and/or 'heads' to return
318           all the heads. "REFGLOB" is an optional array of strings containing
319           a shell-like glob to further limit the refs returned in the hash;
320           the meaning is again the same as the appropriate "git-ls-remote"
321           argument.
322
323           This function may or may not be called on a repository instance. In
324           the former case, remote names as defined in the repository are
325           recognized as repository specifiers.
326
327       ident ( TYPE | IDENTSTR )
328       ident_person ( TYPE | IDENTSTR | IDENTARRAY )
329           This suite of functions retrieves and parses ident information, as
330           stored in the commit and tag objects or produced by "var
331           GIT_type_IDENT" (thus "TYPE" can be either author or committer;
332           case is insignificant).
333
334           The "ident" method retrieves the ident information from "git var"
335           and either returns it as a scalar string or as an array with the
336           fields parsed.  Alternatively, it can take a prepared ident string
337           (e.g. from the commit object) and just parse it.
338
339           "ident_person" returns the person part of the ident - name and
340           email; it can take the same arguments as "ident" or the array
341           returned by "ident".
342
343           The synopsis is like:
344
345                   my ($name, $email, $time_tz) = ident('author');
346                   "$name <$email>" eq ident_person('author');
347                   "$name <$email>" eq ident_person($name);
348                   $time_tz =~ /^\d+ [+-]\d{4}$/;
349
350       hash_object ( TYPE, FILENAME )
351           Compute the SHA1 object id of the given "FILENAME" considering it
352           is of the "TYPE" object type ("blob", "commit", "tree").
353
354           The method can be called without any instance or on a specified Git
355           repository, it makes zero difference.
356
357           The function returns the SHA1 hash.
358
359       hash_and_insert_object ( FILENAME )
360           Compute the SHA1 object id of the given "FILENAME" and add the
361           object to the object database.
362
363           The function returns the SHA1 hash.
364
365       cat_blob ( SHA1, FILEHANDLE )
366           Prints the contents of the blob identified by "SHA1" to
367           "FILEHANDLE" and returns the number of bytes printed.
368
369       credential_read( FILEHANDLE )
370           Reads credential key-value pairs from "FILEHANDLE".  Reading stops
371           at EOF or when an empty line is encountered.  Each line must be of
372           the form "key=value" with a non-empty key.  Function returns hash
373           with all read values.  Any white space (other than new-line
374           character) is preserved.
375
376       credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
377           Writes credential key-value pairs from hash referenced by
378           "CREDENTIAL_HASHREF" to "FILEHANDLE".  Keys and values cannot
379           contain new-lines or NUL bytes characters, and key cannot contain
380           equal signs nor be empty (if they do Error::Simple is thrown).  Any
381           white space is preserved.  If value for a key is "undef", it will
382           be skipped.
383
384           If 'url' key exists it will be written first.  (All the other key-
385           value pairs are written in sorted order but you should not depend
386           on that).  Once all lines are written, an empty line is printed.
387
388       credential( CREDENTIAL_HASHREF [, OPERATION ] )
389       credential( CREDENTIAL_HASHREF, CODE )
390           Executes "git credential" for a given set of credentials and
391           specified operation.  In both forms "CREDENTIAL_HASHREF" needs to
392           be a reference to a hash which stores credentials.  Under certain
393           conditions the hash can change.
394
395           In the first form, "OPERATION" can be 'fill', 'approve' or
396           'reject', and function will execute corresponding "git credential"
397           sub-command.  If it's omitted 'fill' is assumed.  In case of 'fill'
398           the values stored in "CREDENTIAL_HASHREF" will be changed to the
399           ones returned by the "git credential fill" command.  The usual
400           usage would look something like:
401
402                   my %cred = (
403                           'protocol' => 'https',
404                           'host' => 'example.com',
405                           'username' => 'bob'
406                   );
407                   Git::credential \%cred;
408                   if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
409                           Git::credential \%cred, 'approve';
410                           ... do more stuff ...
411                   } else {
412                           Git::credential \%cred, 'reject';
413                   }
414
415           In the second form, "CODE" needs to be a reference to a subroutine.
416           The function will execute "git credential fill" to fill the
417           provided credential hash, then call "CODE" with
418           "CREDENTIAL_HASHREF" as the sole argument.  If "CODE"'s return
419           value is defined, the function will execute "git credential
420           approve" (if return value yields true) or "git credential reject"
421           (if return value is false).  If the return value is undef, nothing
422           at all is executed; this is useful, for example, if the credential
423           could neither be verified nor rejected due to an unrelated network
424           error.  The return value is the same as what "CODE" returns.  With
425           this form, the usage might look as follows:
426
427                   if (Git::credential {
428                           'protocol' => 'https',
429                           'host' => 'example.com',
430                           'username' => 'bob'
431                   }, sub {
432                           my $cred = shift;
433                           return !!try_to_authenticate($cred->{'username'},
434                                                        $cred->{'password'});
435                   }) {
436                           ... do more stuff ...
437                   }
438
439       temp_acquire ( NAME )
440           Attempts to retrieve the temporary file mapped to the string
441           "NAME". If an associated temp file has not been created this
442           session or was closed, it is created, cached, and set for autoflush
443           and binmode.
444
445           Internally locks the file mapped to "NAME". This lock must be
446           released with "temp_release()" when the temp file is no longer
447           needed. Subsequent attempts to retrieve temporary files mapped to
448           the same "NAME" while still locked will cause an error. This
449           locking mechanism provides a weak guarantee and is not threadsafe.
450           It does provide some error checking to help prevent temp file refs
451           writing over one another.
452
453           In general, the File::Handle returned should not be closed by
454           consumers as it defeats the purpose of this caching mechanism. If
455           you need to close the temp file handle, then you should use
456           File::Temp or another temp file faculty directly. If a handle is
457           closed and then requested again, then a warning will issue.
458
459       temp_is_locked ( NAME )
460           Returns true if the internal lock created by a previous
461           "temp_acquire()" call with "NAME" is still in effect.
462
463           When temp_acquire is called on a "NAME", it internally locks the
464           temporary file mapped to "NAME".  That lock will not be released
465           until "temp_release()" is called with either the original "NAME" or
466           the File::Handle that was returned from the original call to
467           temp_acquire.
468
469           Subsequent attempts to call "temp_acquire()" with the same "NAME"
470           will fail unless there has been an intervening "temp_release()"
471           call for that "NAME" (or its corresponding File::Handle that was
472           returned by the original "temp_acquire()" call).
473
474           If true is returned by "temp_is_locked()" for a "NAME", an attempt
475           to "temp_acquire()" the same "NAME" will cause an error unless
476           "temp_release" is first called on that "NAME" (or its corresponding
477           File::Handle that was returned by the original "temp_acquire()"
478           call).
479
480       temp_release ( NAME )
481       temp_release ( FILEHANDLE )
482           Releases a lock acquired through "temp_acquire()". Can be called
483           either with the "NAME" mapping used when acquiring the temp file or
484           with the "FILEHANDLE" referencing a locked temp file.
485
486           Warns if an attempt is made to release a file that is not locked.
487
488           The temp file will be truncated before being released. This can
489           help to reduce disk I/O where the system is smart enough to detect
490           the truncation while data is in the output buffers. Beware that
491           after the temp file is released and truncated, any operations on
492           that file may fail miserably until it is re-acquired. All contents
493           are lost between each release and acquire mapped to the same
494           string.
495
496       temp_reset ( FILEHANDLE )
497           Truncates and resets the position of the "FILEHANDLE".
498
499       temp_path ( NAME )
500       temp_path ( FILEHANDLE )
501           Returns the filename associated with the given tempfile.
502
503       prefix_lines ( PREFIX, STRING [, STRING... ])
504           Prefixes lines in "STRING" with "PREFIX".
505
506       unquote_path ( PATH )
507           Unquote a quoted path containing c-escapes as returned by ls-files
508           etc.  when not using -z or when parsing the output of diff -u.
509
510       get_comment_line_char ( )
511           Gets the core.commentchar configuration value.  The value falls-
512           back to '#' if core.commentchar is set to 'auto'.
513
514       comment_lines ( STRING [, STRING... ])
515           Comments lines following core.commentchar configuration.
516

ERROR HANDLING

518       All functions are supposed to throw Perl exceptions in case of errors.
519       See the Error module on how to catch those. Most exceptions are mere
520       Error::Simple instances.
521
522       However, the "command()", "command_oneline()" and "command_noisy()"
523       functions suite can throw "Git::Error::Command" exceptions as well:
524       those are thrown when the external command returns an error code and
525       contain the error code as well as access to the captured command's
526       output. The exception class provides the usual "stringify" and "value"
527       (command's exit code) methods and in addition also a "cmd_output"
528       method that returns either an array or a string with the captured
529       command output (depending on the original function call context;
530       "command_noisy()" returns "undef") and $<cmdline> which returns the
531       command and its arguments (but without proper quoting).
532
533       Note that the "command_*_pipe()" functions cannot throw this exception
534       since it has no idea whether the command failed or not. You will only
535       find out at the time you "close" the pipe; if you want to have that
536       automated, use "command_close_pipe()", which can throw the exception.
537
538       git_cmd_try { CODE } ERRMSG
539           This magical statement will automatically catch any
540           "Git::Error::Command" exceptions thrown by "CODE" and make your
541           program die with "ERRMSG" on its lips; the message will have %s
542           substituted for the command line and %d for the exit status. This
543           statement is useful mostly for producing more user-friendly error
544           messages.
545
546           In case of no exception caught the statement returns "CODE"'s
547           return value.
548
549           Note that this is the only auto-exported function.
550
552       Copyright 2006 by Petr Baudis <pasky@suse.cz>.
553
554       This module is free software; it may be used, copied, modified and
555       distributed under the terms of the GNU General Public Licence, either
556       version 2, or (at your option) any later version.
557
558
559
560perl v5.28.1                      2019-02-24                            Git(3)
Impressum