1Git::Repository::TutoriUasle(r3)Contributed Perl DocumenGtiatt:i:oRnepository::Tutorial(3)
2
3
4

NAME

6       Git::Repository::Tutorial - Control git from Perl using Git::Repository
7

SYNOPSIS

9           use Git::Repository;
10
11           # do cool stuff with Git, using the following advice
12

HOW-TO

14       A Git::Repository object represents an actual Git repository, against
15       which you can run commands.
16
17   Obtain a Git::Repository object from an existing repository
18       If your script is expected to run against a repository in the current
19       directory (like most Git commands), let Git::Repository handle the
20       magic:
21
22           $r = Git::Repository->new();
23
24       If the repository has a working copy (work tree):
25
26           $r = Git::Repository->new( work_tree => $dir );
27
28       In this case, the git dir is computed as the output of "git rev-parse
29       --git-dir", and the the work tree is normalized using "git rev-parse
30       --show-cdup". To force the use of a different work tree, set the
31       "GIT_WORK_TREE" environment variable in the option hash.
32
33       If the repository is a bare repository, or you prefer to provide the
34       location of the .git directory:
35
36           $r = Git::Repository->new( git_dir => $gitdir );
37
38       If the work tree and the git directory are in unrelated locations, you
39       can also provide both:
40
41           $r = Git::Repository->new( work_tree => $dir, git_dir => $gitdir );
42
43       The constructor also accepts an option hash. The various options are
44       detailed in the manual page for Git::Repository::Command.
45
46   Run any git command
47       Git commands can be run against an existing Git::Repository object, or
48       against the class itself (in which case, git will try to deduce its
49       context from the current directory and the environment).
50
51       The pattern for running commands is always the same:
52
53           $r->run( $command => @arguments, \%options );
54
55       The $command and @arguments are identical to those you'd pass to the
56       "git" command-line tool. The options hash contains options, as
57       described in the manual page for Git::Repository::Command.
58
59   Create a new repository
60       Sometime, you'll need to create the Git repository from scratch:
61
62           # git version 1.6.5 and above
63           Git::Repository->run( init => $dir );
64           $r = Git::Repository->new( work_tree => $dir );
65
66       Any git older than 1.6.5 requires the command to be run in the work
67       tree, so we use the "cwd" option:
68
69           # git version 1.5.0.rc1 and above
70           Git::Repository->run( init => { cwd => $dir } );
71           $r = Git::Repository->new( work_tree => $dir );
72
73           # older git versions
74           Git::Repository->run( 'init-db' => { cwd => $dir } );
75           $r = Git::Repository->new( work_tree => $dir );
76
77       Note that the old "create()" method is obsolete (as of Git::Repository
78       1.18, from April 16, 2011) and has been removed (as of Git::Repository
79       1.301, January 21, 2013).
80
81   Clone a repository
82       Cloning works the same way:
83
84           Git::Repository->run( clone => $url => $dir );
85           $r = Git::Repository->new( work_tree => $dir );
86
87   Run a simple command
88       When you don't really care about the output of the command, just call
89       it:
90
91           $r->run( add => '.' );
92           $r->run( commit => '-m', 'my commit message' );
93
94       In case of an error or warning, Git::Repository will "croak()" or
95       "carp()" appropriately.
96
97   Properly quote options
98       It's common to work out the proper string of Git commands needed to
99       achieve your goal in the shell, before actually turning them into calls
100       to "Git::Repository->run".
101
102       Some options might require quoting, to properly get the arguments to
103       Git through the shell:
104
105           # shell
106           $ git log --since='Fri Jul 26 19:34:15 2013 +0200' --grep='report ticket'
107
108       Such quoting is of course not needed with Git::Repository:
109
110           $since = 'Fri Jul 26 19:34:15 2013 +0200';
111           $grep  = 'report ticket';
112           my $cmd = $r->command( log => "--since=$since", "--grep=$grep" );
113
114   Be careful with spaces in options
115       For the same reasons as above (individual arguments to "run" or
116       "command" are turned into individual "argv" elements for git,
117       whitespace included), some command-line usages of git need to be
118       slightly reformatted to make them suitable for "run()".
119
120       For example, these two commands have the same effect when run from the
121       shell:
122
123               shell> git checkout -b sometopic
124               shell> git checkout -bsometopic
125
126       In the first case, git receives three arguments in "argv": "checkout",
127       "-b" and "sometopic". In the second case, it receives two arguments:
128       "checkout" and "-bsometopic", and then git recognizes the beginning of
129       the -b option and splits "sometopic" out of the second argument.
130
131       So, in a call such as:
132
133           $command = $repo->run( checkout => "-b$branch_name", { quiet => 0 } );
134
135       If $branch_name contains an initial space character, the call will be
136       equivalent the following shell command:
137
138               shell> git checkout -b\ sometopic
139
140       and git will receive two arguments: "checkout" and "-b sometopic", from
141       which it will split out " sometopic" (note the initial space).
142
143       The space after -b must be removed, as otherwise the code attempts to
144       create a branch called " sometopic", which git rejects.
145
146   Silence warnings for some Git commands
147       Some Git porcelain commands provide additional information on "STDERR".
148       One typical example is "git checkout":
149
150           $ git checkout mybranch
151           Switched to branch 'mybranch'
152
153       The "run()" method of Git::Repository treats all output on "STDERR" as
154       a warning. Therefore, the following code:
155
156           $r->run( checkout => 'mybranch' );
157
158       will output a warning like this one:
159
160           Switched to branch 'mybranch' at myscript.pl line 10.
161
162       In such a case, you can use the "quiet" option to silence the warning
163       for a single command:
164
165           $r->run( checkout => 'mybranch', { quiet => 1 } );
166
167       To silence all warnings, you can pass the "quiet" option during the
168       creation of the original repository object:
169
170           my $r = Git::Repository->new( { quiet => 1 } );
171
172       This is not recommended, as it might hide important information from
173       you.
174
175   Process normal and error output
176       The "run()" command doesn't capture "STDERR": it only warns (or dies)
177       if something was printed on it. To be able to actually capture error
178       output, "command()" must be used.
179
180           my $cmd = $r->command( @cmd );
181           my @errput = $cmd->stderr->getlines();
182           $cmd->close;
183
184       "run()" also captures all output at once, which can lead to unnecessary
185       memory consumption when capturing the output of some really verbose
186       commands.
187
188           my $cmd = $r->command( log => '--pretty=oneline', '--all' );
189           my $log = $cmd->stdout;
190           while (<$log>) {
191               ...;
192           }
193           $cmd->close;
194
195       Of course, as soon as one starts reading and writing to an external
196       process' communication handles, a risk of blocking exists.  Caveat
197       emptor.
198
199   Provide input on standard input
200       Use the "input" option:
201
202           my $commit = $r->run( 'commit-tree', $tree, '-p', $parent,
203               { input => $message } );
204
205   Change the environment of a command
206       Use the "env" option:
207
208           $r->run(
209               'commit', '-m', 'log message',
210               {   env => {
211                       GIT_COMMITTER_NAME  => 'Git::Repository',
212                       GIT_COMMITTER_EMAIL => 'book@cpan.org',
213                   },
214               },
215           );
216
217       Note that Git::Repository::Command does small changes to the
218       environment a command before running it. Specifically, it:
219
220       •   deletes "GIT_DIR" and "GIT_WORK_TREE", and sets them to the
221           corresponding values from the current Git::Repository object
222
223       •   deletes "TERM"
224
225       •   replaces "PATH" with the value of the "env->{PATH}" option
226
227       The easiest way to preserve en environment variable is to pass it with
228       the "env" option, for example:
229
230           $r->run( qw( config --get-colorbool githooks.color true ),
231               { env => { TERM => $ENV{TERM} } } );
232
233       See Git::Repository::Command and System::Command for other available
234       options.
235
236   Ignore the system and global configuration files
237       Git has three levels of configuration files that can change the output
238       of porcelain commands: system ($(prefix)/etc/gitconfig), global
239       ($HOME/.gitconfig and $XDG_CONFIG_HOME/git/config) and local
240       (.git/config inside the repository).
241
242       To ensure the system and global configuration files will be ignored and
243       won't interfere with the expected output of your Git commands, you can
244       add the following keys to the "env" option:
245
246           GIT_CONFIG_NOSYSTEM => 1,
247           XDG_CONFIG_HOME     => undef,
248           HOME                => undef,
249
250   Ensure the output from Git commands is not localized
251       Since version 1.7.9, Git translates its most common interface messages
252       into the user's language if translations are available and the locale
253       is appropriately set.
254
255       This means that naively parsing the output "porcelain" commands might
256       fail if the program is unexpectedly run under an unexpected locale.
257
258       The easiest way to ensure your Git commands will be run in a "locale-
259       safe" environment, is to set the "LC_ALL" environment variable to "C".
260
261       The brutal way:
262
263           $ENV{LC_ALL} = 'C';
264
265       The temporary way:
266
267           local $ENV{LC_ALL} = 'C';
268
269       The subtle way (restricted to the commands run on a given
270       Git::Repository instance):
271
272           my $r = Git::Repository->new( { env => { LC_ALL => 'C' } } );
273
274       The stealthiest way (restricted to a single command):
275
276           $r->run( ..., { env => { LC_ALL => 'C' } } );
277
278   Ensure the Git commands are run from the current working directory
279       By default, Git::Repository::Command will "chdir()" to the root of the
280       work tree before launching the requested Git command.
281
282       This means that no matter where your program "chdir()" to, commands on
283       the Git::Repository instance will by default be run from the root of
284       the work tree. So, commands such as "add" need to use the "full" path
285       (relative to "GIT_WORK_TREE") of the files to be added.
286
287       The "cwd" option can be used to define where Git::Repository::Command
288       will "chdir()" to. To instruct Git::Repository::Command to not
289       "chdir()" (and therefore run the Git command from the current working
290       directory), set the option to "undef":
291
292           # run from cwd for this command only
293           $r->run( ..., { cwd => undef } );
294
295           # always run git from cwd
296           my $r = Git::Repository->new( { cwd => undef } );
297
298   Finely control when "run()" dies
299       By default, "Git::Repository->run( ... )" dies if the Git command
300       exited with a status code of 128 (fatal error) or 129 (usage message).
301
302       Some commands will throw an error and exit with a status different from
303       the previous two:
304
305           $r->run( checkout => 'does-not-exist' );    # exit status: 1
306
307       The above "run()" call does not die, and output the following warning:
308
309           error: pathspec 'does-not-exist' did not match any file(s) known to git.
310
311       The exit status (as given by "$? >> 8") is 1.
312
313       To force "run()" to die when the Git command exits with status 1, use
314       the "fatal" option (added in version 1.304, May 25, 2013):
315
316           $r->run( checkout => 'does-not-exist', { fatal => 1 } );
317
318       By default, 128 and 129 remain in the list of fatal codes.
319
320       Here are a few examples:
321
322           # set the fatal codes for all call to run() on this object
323           $r = Git::Repository->new( { fatal => [ 1 .. 255 ] } );
324
325       As usual, setting the option to the Git::Repository object will set it
326       for all commands run for it:
327
328           # "!0" is a shortcut for 1 .. 255
329           $r = Git::Repository->new( { fatal => [ "!0" ] } );
330
331       Using negative codes will make these values non-fatal:
332
333           # the above call to new() makes all exit codes fatal
334           # but 3 and 7 won't be fatal for this specific run
335           $r->run( ..., { fatal => [ -3, -7 ] } );
336
337       When the list contains a single item, there is no need to use an array
338       reference:
339
340           # same as [ "!0" ]
341           $r = Git::Repository->new( { fatal => "!0" } );
342
343           # remove 17 from the list of fatal exit codes for this run only
344           $r->run( ..., { fatal => -17 } );
345
346       See Git::Repository::Command for other available options.
347
348   Process the output of git log
349       When creating a tool that needs to process the output of git log, you
350       should always define precisely the expected format using the --pretty
351       option, and choose a format that is easy to parse.
352
353       Assuming git log will output the default format will eventually lead to
354       problems, for example when the user's git configuration defines
355       "format.pretty" to be something else than the default of "medium".
356
357       See also Git::Repository::Plugin::Log for adding to your
358       Git::Repository objects a "log()" method that will parse the log output
359       for you.
360
361       Understanding the various options for git log can make it very simple
362       to obtain a lot of information.
363
364       For example:
365
366           # all tags reachable from $committish
367           my @tags = map {
368               s/^ \((.*)\)/$1/;
369               ( map +( split /: / )[1], grep /^tag: /, split /, / )
370             }
371             $_->run( qw( log --simplify-by-decoration --pretty=%d ), $committish );
372
373   Process the output of git shortlog
374       git shortlog behaves differently when it detects it's not attached to a
375       terminal. In that case, it just tries to read some git log output from
376       its standard input.
377
378       So this oneliner will hang, because git shortlog is waiting for some
379       data from the program connected to its standard input (the oneliner):
380
381           perl -MGit::Repository -le 'print scalar Git::Repository->run( shortlog => -5 )'
382
383       Whereas this one will "work" (as in "immediately return with no
384       output"):
385
386           perl -MGit::Repository -le 'print scalar Git::Repository->run( shortlog => -5, { input => "" } )'
387
388       So, you need to give git shortlog some input (from git log):
389
390           perl -MGit::Repository -le 'print scalar Git::Repository->run( shortlog => { input => scalar Git::Repository->run( log => -5 ) } )'
391
392       If the log output is large, you'll probably be better off with
393       something like the following:
394
395           use Git::Repository;
396
397           # start both git commands
398           my $log = Git::Repository->command('log')->stdout;
399           my $cmd = Git::Repository->command( shortlog => -ens );
400
401           # feed one with the output of the other
402           my $in = $cmd->stdin;
403           print {$in} $_ while <$log>;
404           close $in;
405
406           # and do something with the output
407           print $cmd->stdout->getlines;
408
409   Wrap git in a sudo call
410       If for a given repository you want to wrap all calls to git in a "sudo"
411       call, you can use the "git" option with an array ref:
412
413           my $r = Git::Repository->new( { git => [qw( sudo -u nobody git )] } );
414
415       In this case, every call to git from $r will actually call "sudo -u
416       nobody git".
417
418   Use submodules
419       Because Git::Repository automatically sets the "GIT_DIR" and
420       "GIT_WORK_TREE" environment variables, some "submodule" sub-commands
421       may fail. For example:
422
423           $r->run( submodule => add => $repository => 'sub' );
424
425       will give the following error:
426
427           error: pathspec 'sub' did not match any file(s) known to git.
428
429       To avoid this error, you should enforce the removal of the
430       "GIT_WORK_TREE" variable from the environment in which the command is
431       run:
432
433           $r->run(
434               submodule => add => $repository => 'sub',
435               { env => { GIT_WORK_TREE => undef } }
436           );
437
438       Note that System::Command version 1.04 is required to be able to remove
439       variables from the environment.
440
441   Sort git versions
442       Since version 1.318, Git::Repository lets Git::Version::Compare handle
443       all version comparisons.
444
445       Sorting version numbers is therefore as simple as:
446
447           use Git::Version::Compare qw( cmp_git );
448
449           @sort_verson = sort cmp_git @versions;
450
451   Add specialized methods to your Git::Repository objects
452       Have a look at Git::Repository::Plugin and
453       Git::Repository::Plugin::Log, to learn how to add your own methods to
454       Git::Repository.
455
456   Run code on the output of a git command through callback
457       Sometimes you need to process the output of a command by running a
458       callback on each line of the output.
459
460           # code inspiration:
461           # https://github.com/dolmen/github-keygen/blob/24c501072ba7d890810de3008434c1fe1f757286/release.pl#L178
462
463           my %tree;
464           $r->run( 'ls-tree' => $commit, sub {
465               my ($mode, $type, $object, $file) = split;
466               $tree{$file} = [ $mode, $type, $object ];
467           } );
468
469       Note that the value returned by the callback will be returned as part
470       of the "run()" output, instead of the original line.
471
472   Initialize a test repository with a bundle
473       Instead of creating a test repository using a series of file editions
474       and commits, one can simply import data into the test repository using
475       a bundle. Bundles are created with the "git bundle create" command (see
476       the Git documentation for details).
477
478       First create a temporary repository with the help of Test::Git:
479
480           use Test::Git;
481           my $r = test_repository();
482
483       then import the bundle data in your repository, and collect the
484       references:
485
486           my @refs = $r->run( bundle => 'unbundle', $bundle_file );
487
488       and finally update the references:
489
490           for my $line (@refs) {
491               my ( $sha1, $ref ) = split / /, $line;
492               $r->run( 'update-ref', $ref => $sha1 );
493           }
494
495       Since Git version 1.6.5, it's also possible to clone directly from a
496       bundle (this creates an "origin" remote pointing to the bundle file):
497
498           my $r = test_repository( clone => [ $bundle_file ] );
499
500       A bundle from a recipient repository's point of view is just like a
501       regular remote repository. See the documentation of git bundle for
502       details of what's possible (e.g. incremental bundles).
503

AUTHOR

505       Philippe Bruhat (BooK) <book@cpan.org>
506
508       Copyright 2010-2016 Philippe Bruhat (BooK), all rights reserved.
509

LICENSE

511       This program is free software; you can redistribute it and/or modify it
512       under the same terms as Perl itself.
513
514
515
516perl v5.34.0                      2022-01-21      Git::Repository::Tutorial(3)
Impressum