1Git(3) User Contributed Perl Documentation Git(3)
2
3
4
6 Git - Perl interface to the Git version control system
7
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
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
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
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 occurred, 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 config_regexp ( RE )
296 Retrieve the list of configuration key names matching the regular
297 expression "RE". The return value is a list of strings matching
298 this regex.
299
300 get_colorbool ( NAME )
301 Finds if color should be used for NAMEd operation from the
302 configuration, and returns boolean (true for "use color", false for
303 "do not use color").
304
305 get_color ( SLOT, COLOR )
306 Finds color for SLOT from the configuration, while defaulting to
307 COLOR, and returns the ANSI color escape sequence:
308
309 print $repo->get_color("color.interactive.prompt", "underline blue white");
310 print "some text";
311 print $repo->get_color("", "normal");
312
313 remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
314 This function returns a hashref of refs stored in a given remote
315 repository. The hash is in the format "refname =\" hash>. For
316 tags, the "refname" entry contains the tag object while a
317 "refname^{}" entry gives the tagged objects.
318
319 "REPOSITORY" has the same meaning as the appropriate
320 "git-ls-remote" argument; either a URL or a remote name (if called
321 on a repository instance). "GROUPS" is an optional arrayref that
322 can contain 'tags' to return all the tags and/or 'heads' to return
323 all the heads. "REFGLOB" is an optional array of strings containing
324 a shell-like glob to further limit the refs returned in the hash;
325 the meaning is again the same as the appropriate "git-ls-remote"
326 argument.
327
328 This function may or may not be called on a repository instance. In
329 the former case, remote names as defined in the repository are
330 recognized as repository specifiers.
331
332 ident ( TYPE | IDENTSTR )
333 ident_person ( TYPE | IDENTSTR | IDENTARRAY )
334 This suite of functions retrieves and parses ident information, as
335 stored in the commit and tag objects or produced by "var
336 GIT_type_IDENT" (thus "TYPE" can be either author or committer;
337 case is insignificant).
338
339 The "ident" method retrieves the ident information from "git var"
340 and either returns it as a scalar string or as an array with the
341 fields parsed. Alternatively, it can take a prepared ident string
342 (e.g. from the commit object) and just parse it.
343
344 "ident_person" returns the person part of the ident - name and
345 email; it can take the same arguments as "ident" or the array
346 returned by "ident".
347
348 The synopsis is like:
349
350 my ($name, $email, $time_tz) = ident('author');
351 "$name <$email>" eq ident_person('author');
352 "$name <$email>" eq ident_person($name);
353 $time_tz =~ /^\d+ [+-]\d{4}$/;
354
355 hash_object ( TYPE, FILENAME )
356 Compute the SHA1 object id of the given "FILENAME" considering it
357 is of the "TYPE" object type ("blob", "commit", "tree").
358
359 The method can be called without any instance or on a specified Git
360 repository, it makes zero difference.
361
362 The function returns the SHA1 hash.
363
364 hash_and_insert_object ( FILENAME )
365 Compute the SHA1 object id of the given "FILENAME" and add the
366 object to the object database.
367
368 The function returns the SHA1 hash.
369
370 cat_blob ( SHA1, FILEHANDLE )
371 Prints the contents of the blob identified by "SHA1" to
372 "FILEHANDLE" and returns the number of bytes printed.
373
374 credential_read( FILEHANDLE )
375 Reads credential key-value pairs from "FILEHANDLE". Reading stops
376 at EOF or when an empty line is encountered. Each line must be of
377 the form "key=value" with a non-empty key. Function returns hash
378 with all read values. Any white space (other than new-line
379 character) is preserved.
380
381 credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
382 Writes credential key-value pairs from hash referenced by
383 "CREDENTIAL_HASHREF" to "FILEHANDLE". Keys and values cannot
384 contain new-lines or NUL bytes characters, and key cannot contain
385 equal signs nor be empty (if they do Error::Simple is thrown). Any
386 white space is preserved. If value for a key is "undef", it will
387 be skipped.
388
389 If 'url' key exists it will be written first. (All the other key-
390 value pairs are written in sorted order but you should not depend
391 on that). Once all lines are written, an empty line is printed.
392
393 credential( CREDENTIAL_HASHREF [, OPERATION ] )
394 credential( CREDENTIAL_HASHREF, CODE )
395 Executes "git credential" for a given set of credentials and
396 specified operation. In both forms "CREDENTIAL_HASHREF" needs to
397 be a reference to a hash which stores credentials. Under certain
398 conditions the hash can change.
399
400 In the first form, "OPERATION" can be 'fill', 'approve' or
401 'reject', and function will execute corresponding "git credential"
402 sub-command. If it's omitted 'fill' is assumed. In case of 'fill'
403 the values stored in "CREDENTIAL_HASHREF" will be changed to the
404 ones returned by the "git credential fill" command. The usual
405 usage would look something like:
406
407 my %cred = (
408 'protocol' => 'https',
409 'host' => 'example.com',
410 'username' => 'bob'
411 );
412 Git::credential \%cred;
413 if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
414 Git::credential \%cred, 'approve';
415 ... do more stuff ...
416 } else {
417 Git::credential \%cred, 'reject';
418 }
419
420 In the second form, "CODE" needs to be a reference to a subroutine.
421 The function will execute "git credential fill" to fill the
422 provided credential hash, then call "CODE" with
423 "CREDENTIAL_HASHREF" as the sole argument. If "CODE"'s return
424 value is defined, the function will execute "git credential
425 approve" (if return value yields true) or "git credential reject"
426 (if return value is false). If the return value is undef, nothing
427 at all is executed; this is useful, for example, if the credential
428 could neither be verified nor rejected due to an unrelated network
429 error. The return value is the same as what "CODE" returns. With
430 this form, the usage might look as follows:
431
432 if (Git::credential {
433 'protocol' => 'https',
434 'host' => 'example.com',
435 'username' => 'bob'
436 }, sub {
437 my $cred = shift;
438 return !!try_to_authenticate($cred->{'username'},
439 $cred->{'password'});
440 }) {
441 ... do more stuff ...
442 }
443
444 temp_acquire ( NAME )
445 Attempts to retrieve the temporary file mapped to the string
446 "NAME". If an associated temp file has not been created this
447 session or was closed, it is created, cached, and set for autoflush
448 and binmode.
449
450 Internally locks the file mapped to "NAME". This lock must be
451 released with "temp_release()" when the temp file is no longer
452 needed. Subsequent attempts to retrieve temporary files mapped to
453 the same "NAME" while still locked will cause an error. This
454 locking mechanism provides a weak guarantee and is not threadsafe.
455 It does provide some error checking to help prevent temp file refs
456 writing over one another.
457
458 In general, the File::Handle returned should not be closed by
459 consumers as it defeats the purpose of this caching mechanism. If
460 you need to close the temp file handle, then you should use
461 File::Temp or another temp file faculty directly. If a handle is
462 closed and then requested again, then a warning will issue.
463
464 temp_is_locked ( NAME )
465 Returns true if the internal lock created by a previous
466 "temp_acquire()" call with "NAME" is still in effect.
467
468 When temp_acquire is called on a "NAME", it internally locks the
469 temporary file mapped to "NAME". That lock will not be released
470 until "temp_release()" is called with either the original "NAME" or
471 the File::Handle that was returned from the original call to
472 temp_acquire.
473
474 Subsequent attempts to call "temp_acquire()" with the same "NAME"
475 will fail unless there has been an intervening "temp_release()"
476 call for that "NAME" (or its corresponding File::Handle that was
477 returned by the original "temp_acquire()" call).
478
479 If true is returned by "temp_is_locked()" for a "NAME", an attempt
480 to "temp_acquire()" the same "NAME" will cause an error unless
481 "temp_release" is first called on that "NAME" (or its corresponding
482 File::Handle that was returned by the original "temp_acquire()"
483 call).
484
485 temp_release ( NAME )
486 temp_release ( FILEHANDLE )
487 Releases a lock acquired through "temp_acquire()". Can be called
488 either with the "NAME" mapping used when acquiring the temp file or
489 with the "FILEHANDLE" referencing a locked temp file.
490
491 Warns if an attempt is made to release a file that is not locked.
492
493 The temp file will be truncated before being released. This can
494 help to reduce disk I/O where the system is smart enough to detect
495 the truncation while data is in the output buffers. Beware that
496 after the temp file is released and truncated, any operations on
497 that file may fail miserably until it is re-acquired. All contents
498 are lost between each release and acquire mapped to the same
499 string.
500
501 temp_reset ( FILEHANDLE )
502 Truncates and resets the position of the "FILEHANDLE".
503
504 temp_path ( NAME )
505 temp_path ( FILEHANDLE )
506 Returns the filename associated with the given tempfile.
507
508 prefix_lines ( PREFIX, STRING [, STRING... ])
509 Prefixes lines in "STRING" with "PREFIX".
510
511 unquote_path ( PATH )
512 Unquote a quoted path containing c-escapes as returned by ls-files
513 etc. when not using -z or when parsing the output of diff -u.
514
515 get_comment_line_char ( )
516 Gets the core.commentchar configuration value. The value falls-
517 back to '#' if core.commentchar is set to 'auto'.
518
519 comment_lines ( STRING [, STRING... ])
520 Comments lines following core.commentchar configuration.
521
523 All functions are supposed to throw Perl exceptions in case of errors.
524 See the Error module on how to catch those. Most exceptions are mere
525 Error::Simple instances.
526
527 However, the "command()", "command_oneline()" and "command_noisy()"
528 functions suite can throw "Git::Error::Command" exceptions as well:
529 those are thrown when the external command returns an error code and
530 contain the error code as well as access to the captured command's
531 output. The exception class provides the usual "stringify" and "value"
532 (command's exit code) methods and in addition also a "cmd_output"
533 method that returns either an array or a string with the captured
534 command output (depending on the original function call context;
535 "command_noisy()" returns "undef") and $<cmdline> which returns the
536 command and its arguments (but without proper quoting).
537
538 Note that the "command_*_pipe()" functions cannot throw this exception
539 since it has no idea whether the command failed or not. You will only
540 find out at the time you "close" the pipe; if you want to have that
541 automated, use "command_close_pipe()", which can throw the exception.
542
543 git_cmd_try { CODE } ERRMSG
544 This magical statement will automatically catch any
545 "Git::Error::Command" exceptions thrown by "CODE" and make your
546 program die with "ERRMSG" on its lips; the message will have %s
547 substituted for the command line and %d for the exit status. This
548 statement is useful mostly for producing more user-friendly error
549 messages.
550
551 In case of no exception caught the statement returns "CODE"'s
552 return value.
553
554 Note that this is the only auto-exported function.
555
557 Copyright 2006 by Petr Baudis <pasky@suse.cz>.
558
559 This module is free software; it may be used, copied, modified and
560 distributed under the terms of the GNU General Public Licence, either
561 version 2, or (at your option) any later version.
562
563
564
565perl v5.32.1 2021-03-08 Git(3)