Git(3)

โœจ NAME โœจ

Git(3) โ€” the Perl interface to the Git version control system, bestie. Fresh from the User Contributed Perl Documentation crew, and honestly? iconic. ๐Ÿ’–


๐Ÿ’… SYNOPSIS ๐Ÿ’…

okay so here's the whole moodboard, no cap โ€” exact code, exact vibes:

         use Git;

         my $version = Git::command_oneline('version');

         git_cmd_try { Git::command_noisy('update-server-info') }
                     '%s failed w/ code %d';

         my $repo = Git->repository (Directory => '/srv/git/cogito.git');

         my @revs = $repo->command('rev-list', '--since=last monday', '--all');

         my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
         my $lastrev = <$fh>; chomp $lastrev;
         $repo->command_close_pipe($fh, $c);

         my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
                                               STDERR => 0 );

         my $sha1 = $repo->hash_and_insert_object('file.txt');
         my $tempfile = tempfile();
         my $size = $repo->cat_blob($sha1, $tempfile);

๐ŸŽ€ DESCRIPTION ๐ŸŽ€

Okay so this module gives Perl scripts an easy way to interface with the Git version control system. The modules have an easy and well-tested way to call arbitrary Git commands; and in the future, the interface will also provide specialized methods for operations that aren't totally trivial to do over the generic command interface. The future is cute, periodt. โœจ

Some commands can be executed outside of any context (e.g. 'version' or 'init'), but most operations require a repository context โ€” which in practice means getting an instance of the Git object using the repository() constructor. (In the future, we will also get a new_repository() constructor.) All commands called as methods of the object are then executed in the context of the repository. ๐Ÿซถ

Part of the "repository state" is also information about path to the attached working copy (unless you work with a bare repository). You can also navigate inside of the working copy using the wc_chdir() method. (Note that the repository object is self-contained and will not change the working directory of your process.) ๐Ÿฆ‹

TODO: In the future, we might also do

               my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
               $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
               my @refs = $remoterepo->refs();

Currently, the module merely wraps calls to external Git tools. In the future, it will provide a much faster way to interact with Git by linking directly to libgit. This should be completely opaque to the user, though (performance increase notwithstanding). Ngl, that's the glow-up. ๐Ÿ”ฅ


๐Ÿฆ‹ CONSTRUCTORS ๐Ÿฆ‹

repository

repository ( OPTIONS )
repository ( DIRECTORY )
repository ()

Construct a new repository object. OPTIONS are passed in a hash like fashion, using key and value pairs. Possible options are:

  • Repository โ€” Path to the Git repository.
  • WorkingCopy โ€” Path to the associated working copy; not strictly required as many commands will happily crunch on a bare repository.
  • WorkingSubdir โ€” Subdirectory in the working copy to work inside. Just left undefined if you do not want to limit the scope of operations.
  • Directory โ€” Path to the Git working directory in its usual setup. The .git directory is searched in the directory and all the parent directories; if found, WorkingCopy is set to the directory containing it and Repository to the .git directory itself. If no .git directory was found, the Directory is assumed to be a bare repository, Repository is set to point at it and WorkingCopy is left undefined. If the $GIT_DIR environment variable is set, things behave as expected as well.
โš ๏ธ You should not use both Directory and either of Repository and WorkingCopy โ€” the results of that are undefined. So don't. It's giving chaos, and not the cute kind. ๐Ÿ’€

Alternatively, a directory path may be passed as a single scalar argument to the constructor; it is equivalent to setting only the Directory option field.

Calling the constructor with no options whatsoever is equivalent to calling it with Directory => '.'. In general, if you are building a standard porcelain command, simply doing Git->repository() should do the right thing and setup the object to reflect exactly where the user is right now. Slay. ๐Ÿ’…


๐ŸŒˆ METHODS ๐ŸŒˆ

command

command ( COMMAND [, ARGUMENTS... ] )
command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )

Execute the given Git COMMAND (specify it without the 'git-' prefix), optionally with the specified extra ARGUMENTS. ๐ŸŽ€

The second more elaborate form can be used if you want to further adjust the command execution. Currently, only one option is supported:

  • STDERR โ€” How to deal with the command's error output. By default (undef) it is delivered to the caller's STDERR. A false value (0 or '') will cause it to be thrown away. If you want to process it, you can get it in a filehandle you specify, but you must be extremely careful; if the error output is not very short and you want to read it in the same process as where you called command(), you are set up for a nice deadlock! ๐Ÿ˜ญ

The method can be called without any instance or on a specified Git repository (in that case the command will be run in the repository context).

In scalar context, it returns all the command output in a single string (verbatim).

In array context, it returns an array containing lines printed to the command's stdout (without trailing newlines).

In both cases, the command's stdin and stderr are the same as the caller's.

command_oneline

command_oneline ( COMMAND [, ARGUMENTS... ] )
command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )

Execute the given COMMAND in the same way as command() does but always return a scalar string containing the first line of the command's standard output.

command_output_pipe

command_output_pipe ( COMMAND [, ARGUMENTS... ] )
command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )

Execute the given COMMAND in the same way as command() does but return a pipe filehandle from which the command output can be read.

The function can return ($pipe, $ctx) in array context. See command_close_pipe() for details.

command_input_pipe

command_input_pipe ( COMMAND [, ARGUMENTS... ] )
command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )

Execute the given COMMAND in the same way as command_output_pipe() does but return an input pipe filehandle instead; the command output is not captured.

The function can return ($pipe, $ctx) in array context. See command_close_pipe() for details.

command_close_pipe

command_close_pipe ( PIPE [, CTX ] )

Close the PIPE as returned from command_*_pipe(), checking whether the command finished successfully. The optional CTX argument is required if you want to see the command name in the error message, and it is the second value returned by command_*_pipe() when called in array context. The call idiom is:

                   my ($fh, $ctx) = $r->command_output_pipe('status');
                   while (<$fh>) { ... }
                   $r->command_close_pipe($fh, $ctx);

Note that you should not rely on whatever actually is in CTX; currently it is simply the command name but in future the context might have more complicated structure. ๐Ÿ‘€

command_bidi_pipe

command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )

Execute the given COMMAND in the same way as command_output_pipe() does but return both an input pipe filehandle and an output pipe filehandle.

The function will return ($pid, $pipe_in, $pipe_out, $ctx). See command_close_bidi_pipe() for details.

command_close_bidi_pipe

command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )

Close the PIPE_IN and PIPE_OUT as returned from command_bidi_pipe(), checking whether the command finished successfully. The optional CTX argument is required if you want to see the command name in the error message, and it is the fourth value returned by command_bidi_pipe(). The call idiom is:

                   my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe(qw(cat-file --batch-check));
                   print $out "000000000\n";
                   while (<$in>) { ... }
                   $r->command_close_bidi_pipe($pid, $in, $out, $ctx);

Note that you should not rely on whatever actually is in CTX; currently it is simply the command name but in future the context might have more complicated structure.

PIPE_IN and PIPE_OUT may be undef if they have been closed prior to calling this function. This may be useful in a query-response type of commands where caller first writes a query and later reads response, eg:

                   my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe(qw(cat-file --batch-check));
                   print $out "000000000\n";
                   close $out;
                   while (<$in>) { ... }
                   $r->command_close_bidi_pipe($pid, $in, undef, $ctx);

This idiom may prevent potential dead locks caused by data sent to the output pipe not being flushed and thus not reaching the executed command. iykyk. ๐Ÿ’œ

command_noisy

command_noisy ( COMMAND [, ARGUMENTS... ] )

Execute the given COMMAND in the same way as command() does but do not capture the command output โ€” the standard output is not redirected and goes to the standard output of the caller application.

While the method is called command_noisy(), you might want to as well use it for the most silent Git commands which you know will never pollute your stdout but you want to avoid the overhead of the pipe setup when calling them.

The function returns only after the command has finished running.

version

version ()

Return the Git version in use.

exec_path

exec_path ()

Return path to the Git sub-command executables (the same as git --exec-path). Useful mostly only internally.

html_path

html_path ()

Return path to the Git html documentation (the same as git --html-path). Useful mostly only internally.

get_tz_offset

get_tz_offset ( TIME )

Return the time zone offset from GMT in the form +/-HHMM where HH is the number of hours from GMT and MM is the number of minutes. This is the equivalent of what strftime("%z", ...) would provide on a GNU platform.

If TIME is not supplied, the current local time is used.

get_record

get_record ( FILEHANDLE, INPUT_RECORD_SEPARATOR )

Read one record from FILEHANDLE delimited by INPUT_RECORD_SEPARATOR, removing any trailing INPUT_RECORD_SEPARATOR.

prompt

prompt ( PROMPT , ISPASSWORD  )

Query user PROMPT and return answer from user.

Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying the user. If no *_ASKPASS variable is set or an error occurred, the terminal is tried as a fallback. If ISPASSWORD is set and true, the terminal disables echo. ๐Ÿ“

๐Ÿงญ repo_path ()

Gives you the path to the git repository. You must call this on a repository instance, bestie โ€” it's not a free-floating vibe, it needs a repo to belong to. โœจ

๐Ÿ“ wc_path ()

Returns the path to the working copy. Again โ€” repository instance only, no exceptions. ๐Ÿ’…

๐Ÿ—‚๏ธ wc_subdir ()

Returns the path to the subdirectory inside the working copy. Repository instance required, periodt. ๐ŸŽ€

๐Ÿšถโ€โ™€๏ธ wc_chdir ( SUBDIR )

Changes the working copy subdirectory you're working within. Heads up though: SUBDIR is relative to the working copy root directory โ€” not the current subdirectory, okay? Don't get it twisted. ๐Ÿ™ˆ

Has to be called on a repository instance that's attached to a working copy, and the directory must exist. No imaginary folders allowed, sorry! ๐Ÿฆ‹

โš™๏ธ config ( VARIABLE )

Grabs the configuration VARIABLE in the exact same manner as config does. In scalar context it requires the variable to be set only one time (otherwise an exception gets thrown, oop ๐Ÿ˜ญ), and in array context it allows the variable to be set multiple times and hands back all the values. Best of both worlds, honestly. ๐Ÿ’–

โœ… config_bool ( VARIABLE )

Gets the bool configuration VARIABLE. The return value is usable as a boolean in perl โ€” and undef if it's not defined, of course. Keeping it real. ๐Ÿซถ

๐Ÿ›ค๏ธ config_path ( VARIABLE )

Retrieves the path configuration VARIABLE. You get back an expanded path, or undef if it's not defined. Simple as that. โœจ

๐Ÿ”ข config_int ( VARIABLE )

Retrieves the integer configuration VARIABLE. The return value is a simple decimal number. But here's the fun part โ€” an optional value suffix of 'k', 'm', or 'g' in the config file will cause the value to be multiplied by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output. Math is mathing! ๐Ÿ”ฅ

It would return undef if the configuration variable isn't defined. ๐Ÿ’€

๐Ÿ” config_regexp ( RE )

Retrieves the list of configuration key names matching the regular expression RE. The return value is a list of strings matching this regex. Iconic search behaviour, ngl. ๐ŸŒธ

๐ŸŒˆ get_colorbool ( NAME )

Figures out if color should be used for the NAME'd operation from the configuration, and returns a boolean โ€” true for "use color", false for "do not use color". Aesthetic decisions, automated. ๐Ÿ’…

๐ŸŽจ get_color ( SLOT, COLOR )

Finds the color for SLOT from the configuration, defaulting to COLOR, and returns the ANSI color escape sequence:

print $repo->get_color("color.interactive.prompt", "underline blue white");
print "some text";
print $repo->get_color("", "normal");

Look at that glow-up. ๐ŸŒˆ

๐Ÿ“ก remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )

This function returns a hashref of refs stored in a given remote repository. The hash is in the format "refname" => hash. For tags, the "refname" entry contains the tag object while a "refname^{}" entry gives the tagged objects. ๐Ÿท๏ธ

REPOSITORY has the same meaning as the appropriate git-ls-remote argument โ€” either a URL or a remote name (if called on a repository instance). GROUPS is an optional arrayref that can contain 'tags' to return all the tags and/or 'heads' to return all the heads. REFGLOB is an optional array of strings containing a shell-like glob to further limit the refs returned in the hash; the meaning is again the same as the appropriate git-ls-remote argument. ๐Ÿš

This function may or may not be called on a repository instance. In the former case, remote names as defined in the repository are recognized as repository specifiers. Flexible queen behaviour. ๐Ÿ‘‘

๐Ÿชช ident ( TYPE | IDENTSTR )

๐Ÿชช ident_person ( TYPE | IDENTSTR | IDENTARRAY )

This suite of functions retrieves and parses ident information, as stored in the commit and tag objects or produced by var GIT_type_IDENT (thus TYPE can be either author or committer; case is insignificant โ€” we don't discriminate here ๐Ÿ’–).

The ident method retrieves the ident information from git var and either returns it as a scalar string or as an array with the fields parsed. Alternatively, it can take a prepared ident string (e.g. from the commit object) and just parse it. Obsessed with the flexibility, honestly. โœจ

ident_person returns the person part of the ident โ€” name and email. It can take the same arguments as ident or the array returned by ident. ๐Ÿซถ

The synopsis is like:

my ($name, $email, $time_tz) = ident('author');
"$name <$email>" eq ident_person('author');
"$name <$email>" eq ident_person($name);
$time_tz =~ /^\d+ [+-]\d{4}$/;

#๏ธโƒฃ hash_object ( TYPE, FILENAME )

Computes the SHA1 object id of the given FILENAME, considering it to be of the TYPE object type (blob, commit, tree). ๐Ÿงฎ

The method can be called without any instance or on a specified Git repository โ€” it makes zero difference, no cap. โญ

The function returns the SHA1 hash. Slay. ๐Ÿ’œ

๐Ÿ“ฅ hash_and_insert_object ( FILENAME )

Computes the SHA1 object id of the given FILENAME and adds the object to the object database. Two-for-one deal, we love to see it. ๐ŸŽ€

The function returns the SHA1 hash. ๐Ÿ”ฅ

๐Ÿˆ cat_blob ( SHA1, FILEHANDLE )

Prints the contents of the blob identified by SHA1 to FILEHANDLE and returns the number of bytes printed. Yes, she's named cat and yes, she's iconic for it. ๐Ÿ˜บ

๐Ÿ” credential_read( FILEHANDLE )

Reads credential key-value pairs from FILEHANDLE. Reading stops at EOF or when an empty line is encountered. Each line must be of the form key=value with a non-empty key. The function returns a hash with all the read values. Any white space (other than the new-line character) is preserved โ€” every space matters, diva. ๐Ÿ’…

โœ๏ธ credential_write( FILEHANDLE, CREDENTIAL_HASHREF )

Writes credential key-value pairs from the hash referenced by CREDENTIAL_HASHREF to FILEHANDLE. Keys and values cannot contain new-lines or NUL byte characters, and a key cannot contain equal signs nor be empty (if they do, Error::Simple is thrown). Any white space is preserved. If the value for a key is undef, it will be skipped. ๐Ÿ™ˆ

If the 'url' key exists it will be written first. (All the other key-value pairs are written in sorted order but you should not depend on that โ€” it's giving "don't rely on the vibes" energy.) Once all lines are written, an empty line is printed. ๐ŸŒธ

๐Ÿ—๏ธ credential( CREDENTIAL_HASHREF [, OPERATION ] )

๐Ÿ—๏ธ credential( CREDENTIAL_HASHREF, CODE )

Executes git credential for a given set of credentials and the specified operation. In both forms CREDENTIAL_HASHREF needs to be a reference to a hash which stores credentials. Under certain conditions the hash can change โ€” keep an eye on it, bestie. ๐Ÿ‘€

In the first form, OPERATION can be 'fill', 'approve', or 'reject', and the function will execute the corresponding git credential sub-command. If it's omitted, 'fill' is assumed. In the case of 'fill' the values stored in CREDENTIAL_HASHREF will be changed to the ones returned by the git credential fill command. The usual usage would look something like:

my %cred = (
        'protocol' => 'https',
        'host' => 'example.com',
        'username' => 'bob'
);
Git::credential \%cred;
if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
        Git::credential \%cred, 'approve';
        ... do more stuff ...
} else {
        Git::credential \%cred, 'reject';
}

In the second form, CODE needs to be a reference to a subroutine. The function will execute git credential fill to fill the provided credential hash, then call CODE with CREDENTIAL_HASHREF as the sole argument. If CODE's return value is defined, the function will execute git credential approve (if the return value yields true) or git credential reject (if the return value is false). If the return value is undef, nothing at all is executed โ€” which is lowkey useful, for example, if the credential could neither be verified nor rejected due to an unrelated network error. The return value is the same as what CODE returns. With this form, the usage might look as follows:

if (Git::credential {
        'protocol' => 'https',
        'host' => 'example.com',
        'username' => 'bob'
}, sub {
        my $cred = shift;
        return !!try_to_authenticate($cred->{'username'},
                                     $cred->{'password'});
}) {
        ... do more stuff ...
}

๐ŸŒก๏ธ temp_acquire ( NAME )

Attempts to retrieve the temporary file mapped to the string NAME. If an associated temp file hasn't been created this session or was closed, it is created, cached, and set for autoflush and binmode. โœจ

Internally it locks the file mapped to NAME. This lock must be released with temp_release() when the temp file is no longer needed. Subsequent attempts to retrieve temporary files mapped to the same NAME while still locked will cause an error. This locking mechanism provides a weak guarantee and is not threadsafe. It does provide some error checking to help prevent temp file refs writing over one another. ๐Ÿซถ

In general, the File::Handle returned should not be closed by consumers, since that defeats the purpose of this caching mechanism. If you need to close the temp file handle, then you should use File::Temp or another temp file faculty directly. If a handle is closed and then requested again, then a warning will issue. โš ๏ธ

๐Ÿ”’ temp_is_locked ( NAME )

Returns true if the internal lock created by a previous temp_acquire() call with NAME is still in effect. ๐Ÿ’…

When temp_acquire is called on a NAME, it internally locks the temporary file mapped to NAME. That lock will not be released until temp_release() is called with either the original NAME or the File::Handle that was returned from the original call to temp_acquire. ๐Ÿ”

Subsequent attempts to call temp_acquire() with the same NAME will fail unless there has been an intervening temp_release() call for that NAME (or its corresponding File::Handle that was returned by the original temp_acquire() call).

If true is returned by temp_is_locked() for a NAME, an attempt to temp_acquire() the same NAME will cause an error unless temp_release is first called on that NAME (or its corresponding File::Handle that was returned by the original temp_acquire() call). No sneaky double-locking, okay? ๐Ÿ˜ค

๐Ÿ”“ temp_release ( NAME )

๐Ÿ”“ temp_release ( FILEHANDLE )

Releases a lock acquired through temp_acquire(). Can be called either with the NAME mapping used when acquiring the temp file or with the FILEHANDLE referencing a locked temp file. ๐ŸŽ€

Warns if an attempt is made to release a file that is not locked. Rude awakening, but fair. ๐Ÿ’€

So, the temp file will be truncated before itโ€™s released. This can help to reduce disk I/O where the system is smart enough to detect the truncation while data is in the output buffers. Ngl thatโ€™s kind of iconic for performance. ๐Ÿš€

โš ๏ธ Beware: after the temp file is released and truncated, any operations on that file may fail miserably until it is re-acquired. All contents are lost between each release and acquire mapped to the same string. ๐Ÿ˜ญ

Okay bestie, hereโ€™s the rest of the function vibe check:

  • temp_reset ( FILEHANDLE ) โ€” Truncates and resets the position of the FILEHANDLE. ๐ŸŽฏ
  • temp_path ( NAME ) โ€” Returns the filename associated with the given tempfile. ๐ŸŒธ
  • temp_path ( FILEHANDLE ) โ€” Also returns the filename associated with the given tempfile. ๐Ÿซถ
  • prefix_lines ( PREFIX, STRING [, STRING... ]) โ€” Prefixes lines in STRING with PREFIX. โœจ
  • unquote_path ( PATH ) โ€” Unquote a quoted path containing c-escapes as returned by ls-files etc. when not using -z or when parsing the output of diff -u. ๐Ÿ”
  • get_comment_line_char ( ) โ€” Gets the core.commentchar configuration value. The value falls-back to '#' if core.commentchar is set to 'auto'. ๐ŸŽ€
  • comment_lines ( STRING [, STRING... ]) โ€” Comments lines following core.commentchar configuration. ๐Ÿ’ฌ

๐Ÿ’ฅ ERROR HANDLING ๐Ÿ’ฅ

All functions are supposed to throw Perl exceptions in case of errors. See the Error module on how to catch those. Most exceptions are mere Error::Simple instances. ๐Ÿซก

However, the command(), command_oneline() and command_noisy() functions suite can throw Git::Error::Command exceptions as well: those are thrown when the external command returns an error code and contain the error code as well as access to the captured commandโ€™s output. The exception class provides the usual stringify and value (commandโ€™s exit code) methods and in addition also a cmd_output method that returns either an array or a string with the captured command output (depending on the original function call context; command_noisy() returns undef) and $<cmdline> which returns the command and its arguments (but without proper quoting). ๐Ÿง 

Note that the command_*_pipe() functions cannot throw this exception since it has no idea whether the command failed or not. You will only find out at the time you close the pipe; if you want to have that automated, use command_close_pipe(), which can throw the exception. ๐Ÿšฐ

git_cmd_try { CODE } ERRMSG โ€” this magical statement will automatically catch any Git::Error::Command exceptions thrown by CODE and make your program die with ERRMSG on its lips; the message will have %s substituted for the command line and %d for the exit status. This statement is useful mostly for producing more user-friendly error messages. ๐Ÿ’…

In case of no exception caught the statement returns CODEโ€™s return value. ๐Ÿ‘‘

Note that this is the only auto-exported function. ๐Ÿšจ


Copyright 2006 by Petr Baudis <pasky@suse.cz>.

This module is free software; it may be used, copied, modified and distributed under the terms of the GNU General Public Licence, either version 2, or (at your option) any later version. ๐Ÿ“œ

okay bye bestie, this is Git(3) from perl v5.42.2, dated 2026-09-28 โ€” catch u later, mwah ๐Ÿ’‹โœจ

๐Ÿ“ฆ where this page comes from