3 # Debian::Dgit: functions common to dgit and its helpers and servers
5 # Copyright (C) 2015-2016 Ian Jackson
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
34 use Dpkg::Control::Hash;
35 use Debian::Dgit::ExitStatus;
36 use Debian::Dgit::I18n;
40 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
44 @EXPORT = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
46 debiantags debiantag_new
49 upstream_commitish_search resolve_upstream_version
50 stripepoch source_file_leafname is_orig_file_of_p_v
51 server_branch server_ref
52 stat_exists link_ltarget rename_link_xf
54 fail failmsg ensuredir must_getcwd executable_on_path
55 waitstatusmsg failedcmd_waitstatus
56 failedcmd_report_cmd failedcmd
57 runcmd shell_cmd cmdoutput cmdoutput_errok
58 git_rev_parse changedir_git_toplevel git_cat_file
59 git_get_ref git_get_symref git_for_each_ref
60 git_for_each_tag_referring is_fast_fwd
62 git_reflog_action_msg git_update_ref_cmd
63 rm_subdir_cached read_tree_subdir
64 read_tree_debian read_tree_upstream
65 make_commit hash_commit hash_commit_text
66 reflog_cache_insert reflog_cache_lookup
67 $package_re $component_re $suite_re $deliberately_re
68 $distro_re $versiontag_re $series_filename_re
69 $orig_f_comp_re $orig_f_sig_re $orig_f_tail_re
70 $extra_orig_namepart_re
73 $ffq_refprefix $gdrlast_refprefix
74 initdebug enabledebug enabledebuglevel
76 $printdebug_when_debuglevel $debugcmd_when_debuglevel
77 $debugprefix *debuglevel *DEBUG
78 shellquote printcmd messagequote
79 $negate_harmful_gitattrs
80 changedir git_slurp_config_src
81 gdr_ffq_prev_branchinfo
82 parsecontrolfh parsecontrol parsechangelog
83 getfield parsechangelog_loop
85 # implicitly uses $main::us
86 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
87 playground => [qw(record_maindir $maindir $local_git_cfg
88 $maindir_gitdir $maindir_gitcommon
90 ensure_a_playground)]);
91 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
92 @{ $EXPORT_TAGS{playground} } );
97 our $package_re = '[0-9a-z][-+.0-9a-z]*';
98 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
99 our $suite_re = '[-+.0-9a-z]+';
100 our $deliberately_re = "(?:TEST-)?$package_re";
101 our $distro_re = $component_re;
102 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
103 our $branchprefix = 'dgit';
104 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
105 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
106 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
107 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
108 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
109 our $git_null_obj = '0' x 40;
110 our $ffq_refprefix = 'ffq-prev';
111 our $gdrlast_refprefix = 'debrebase-last';
112 our $printdebug_when_debuglevel = 1;
113 our $debugcmd_when_debuglevel = 1;
115 # these three all go together, only valid after record_maindir
118 our $maindir_gitcommon;
120 # policy hook exit status bits
121 # see dgit-repos-server head comment for documentation
122 # 1 is reserved in case something fails with `exit 1' and to spot
123 # dynamic loader, runtime, etc., failures, which report 127 or 255
124 sub NOFFCHECK () { return 0x2; }
125 sub FRESHREPO () { return 0x4; }
126 sub NOCOMMITCHECK () { return 0x8; }
131 our $negate_harmful_gitattrs =
132 "-text -eol -crlf -ident -filter -working-tree-encoding";
133 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
135 our $forkcheck_mainprocess;
137 sub forkcheck_setup () {
138 $forkcheck_mainprocess = $$;
141 sub forkcheck_mainprocess () {
142 # You must have called forkcheck_setup or setup_sigwarn already
143 getppid != $forkcheck_mainprocess;
146 sub setup_sigwarn () {
148 $SIG{__WARN__} = sub {
149 confess $_[0] if forkcheck_mainprocess;
155 open DEBUG, ">/dev/null" or confess "$!";
159 open DEBUG, ">&STDERR" or confess "$!";
164 sub enabledebuglevel ($) {
165 my ($newlevel) = @_; # may be undef (eg from env var)
166 confess if $debuglevel;
169 return unless $newlevel;
170 $debuglevel = $newlevel;
175 # Prints a prefix, and @_, to DEBUG. @_ should normally contain
178 # With no (or only empty) arguments just prints the prefix and
179 # leaves the caller to do more with DEBUG. The caller should make
180 # sure then to call printdebug with something ending in "\n" to
181 # get the prefix right in subsequent calls.
183 return unless $debuglevel >= $printdebug_when_debuglevel;
184 our $printdebug_noprefix;
185 print DEBUG $debugprefix unless $printdebug_noprefix;
186 pop @_ while @_ and !length $_[-1];
188 print DEBUG @_ or confess "$!";
189 $printdebug_noprefix = $_[-1] !~ m{\n$};
192 sub messagequote ($) {
198 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
205 defined or confess __ 'internal error' foreach @_;
208 if (!length || m{[^-=_./:0-9a-z]}i) {
215 return join ' ', @out;
220 my $intro = shift @_;
221 print $fh $intro," " or confess "$!";
222 print $fh shellquote @_ or confess "$!";
223 print $fh "\n" or confess "$!";
227 my $extraprefix = shift @_;
228 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
229 if $debuglevel >= $debugcmd_when_debuglevel;
232 sub dep14_version_mangle ($) {
234 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
236 $v =~ s/\.(?=\.|$|lock$)/.#/g;
240 sub debiantag_new ($$) {
241 my ($v,$distro) = @_;
242 return "archive/$distro/".dep14_version_mangle $v;
245 sub debiantag_maintview ($$) {
246 my ($v,$distro) = @_;
247 return "$distro/".dep14_version_mangle $v;
250 sub debiantags ($$) {
251 my ($version,$distro) = @_;
252 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
261 sub upstreamversion ($) {
267 sub source_file_leafname ($$$) {
268 my ($package,$vsn,$sfx) = @_;
269 return "${package}_".(stripepoch $vsn).$sfx
272 sub is_orig_file_of_p_v ($$$) {
273 my ($f, $package, $upstreamvsn) = @_;
274 my $base = source_file_leafname $package, $upstreamvsn, '';
275 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
279 sub server_branch ($) { return "$branchprefix/$_[0]"; }
280 sub server_ref ($) { return "refs/".server_branch($_[0]); }
282 sub stat_exists ($) {
285 return 0 if $!==&ENOENT;
286 confess "stat $f: $!";
290 $::us // ($0 =~ m#[^/]*$#, $&);
294 my $s = f_ "error: %s\n", "@_";
296 my $prefix = _us().": ";
297 $s =~ s/^/$prefix/gm;
306 my ($dir) = @_; # does not create parents
307 return if mkdir $dir;
308 return if $! == EEXIST;
309 confess "mkdir $dir: $!";
314 defined $d or fail f_ "getcwd failed: %s\n", $!;
318 sub executable_on_path ($) {
320 return 1 if $program =~ m{/};
321 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
322 foreach my $pe (@path) {
323 my $here = "$pe/$program";
324 return $here if stat_exists $here && -x _;
329 our @signames = split / /, $Config{sig_name};
331 sub waitstatusmsg () {
333 return __ "terminated, reporting successful completion";
334 } elsif (!($? & 255)) {
335 return f_ "failed with error exit status %s", WEXITSTATUS($?);
336 } elsif (WIFSIGNALED($?)) {
337 my $signum=WTERMSIG($?);
338 return f_ "died due to fatal signal %s",
339 ($signames[$signum] // "number $signum").
340 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
342 return f_ "failed with unknown wait status %s", $?;
346 sub failedcmd_report_cmd {
347 my $intro = shift @_;
348 $intro //= __ "failed command";
349 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
352 sub failedcmd_waitstatus {
354 return f_ "failed to fork/exec: %s", $!;
356 return f_ "subprocess %s", waitstatusmsg();
358 return __ "subprocess produced invalid output";
363 # Expects $!,$? as set by close - see below.
364 # To use with system(), set $?=-1 first.
366 # Actual behaviour of perl operations:
367 # success $!==0 $?==0 close of piped open
368 # program failed $!==0 $? >0 close of piped open
369 # syscall failure $! >0 $?=-1 close of piped open
370 # failure $! >0 unchanged close of something else
371 # success trashed $?==0 system
372 # program failed trashed $? >0 system
373 # syscall failure $! >0 unchanged system
374 failedcmd_report_cmd undef, @_;
375 fail failedcmd_waitstatus();
381 failedcmd @_ if system @_;
385 my ($first_shell, @cmd) = @_;
386 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
389 sub cmdoutput_errok {
390 confess Dumper(\@_)." ?" if grep { !defined } @_;
391 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
393 open P, "-|", @_ or confess "$_[0] $!";
396 { local $/ = undef; $d = <P>; }
397 confess "$!" if P->error;
398 if (!close P) { printdebug "=>!$?\n"; return undef; }
400 if ($debuglevel > 0) {
403 my $more = (length $' ? '...' : ''); #');
404 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
405 printdebug "=> \`$dd'",$more,"\n";
411 my $d = cmdoutput_errok @_;
412 defined $d or failedcmd @_;
416 sub link_ltarget ($$) {
418 lstat $old or return undef;
420 $old = cmdoutput qw(realpath --), $old;
422 my $r = link $old, $new;
423 $r = symlink $old, $new if !$r && $!==EXDEV;
424 $r or fail "(sym)link $old $new: $!\n";
427 sub rename_link_xf ($$$) {
428 # renames/moves or links/copies $src to $dst,
429 # even if $dst is on a different fs
430 # (May use the filename "$dst.tmp".);
431 # On success, returns true.
432 # On failure, returns false and sets
433 # $@ to a reason message
434 # $! to an errno value, or -1 if not known
435 # having possibly printed something about mv to stderr.
436 # Not safe to use without $keeporig if $dst might be a symlink
437 # to $src, as it might delete $src leaving $dst invalid.
438 my ($keeporig,$src,$dst) = @_;
441 : rename $src, $dst) {
449 $@ = f_ "stat source file: %S", $!;
452 my @src_stat = (stat _)[0..1];
456 @dst_stat = (stat _)[0..1];
457 } elsif ($! == ENOENT) {
459 $@ = f_ "stat destination file: %S", $!;
463 if ("@src_stat" eq "@dst_stat") {
464 # (Symlinks to) the same file. No need for a copy but
465 # we may need to delete the original.
466 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
469 my @cmd = (qw(cp --), $src, "$dst.tmp");
472 failedcmd_report_cmd undef, @cmd;
473 $@ = failedcmd_waitstatus();
477 if (!rename "$dst.tmp", $dst) {
478 $@ = f_ "finally install file after cp: %S", $!;
484 $@ = f_ "delete old file after cp: %S", $!;
493 my $h = Digest::SHA->new(256);
495 return $h->hexdigest();
498 sub git_rev_parse ($) {
499 return cmdoutput qw(git rev-parse), "$_[0]~0";
502 sub changedir_git_toplevel () {
503 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
504 length $toplevel or fail __ <<END;
505 not in a git working tree?
506 (git rev-parse --show-toplevel produced no output)
508 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
511 sub git_cat_file ($;$) {
512 my ($objname, $etype) = @_;
513 # => ($type, $data) or ('missing', undef)
514 # in scalar context, just the data
515 # if $etype defined, dies unless type is $etype or in @$etype
516 our ($gcf_pid, $gcf_i, $gcf_o);
517 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
519 my ($gtype, $data) = @_;
521 $etype = [$etype] unless ref $etype;
522 confess "$objname expected @$etype but is $gtype"
523 unless grep { $gtype eq $_ } @$etype;
525 return ($gtype, $data);
528 my @cmd = qw(git cat-file --batch);
529 debugcmd "GCF|", @cmd;
530 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
532 printdebug "GCF>| $objname\n";
533 print $gcf_i $objname, "\n" or confess "$!";
535 printdebug "GCF<| ", $x;
536 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
537 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
539 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
541 $x eq "\n" or confess "$objname ($_) $!";
542 return $chk->($type, $data);
545 sub git_get_symref (;$) {
546 my ($symref) = @_; $symref //= 'HEAD';
547 # => undef if not a symref, otherwise refs/...
548 my @cmd = (qw(git symbolic-ref -q HEAD));
549 my $branch = cmdoutput_errok @cmd;
550 if (!defined $branch) {
551 $?==256 or failedcmd @cmd;
558 sub git_for_each_ref ($$;$) {
559 my ($pattern,$func,$gitdir) = @_;
560 # calls $func->($objid,$objtype,$fullrefname,$reftail);
561 # $reftail is RHS of ref after refs/[^/]+/
562 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
563 # $pattern may be an array ref to mean multiple patterns
564 $pattern = [ $pattern ] unless ref $pattern;
565 my @cmd = (qw(git for-each-ref), @$pattern);
566 if (defined $gitdir) {
567 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
569 open GFER, "-|", @cmd or confess "$!";
572 chomp or confess "$_ ?";
573 printdebug "|> ", $_, "\n";
574 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
575 $func->($1,$2,$3,$4);
577 $!=0; $?=0; close GFER or confess "$pattern $? $!";
580 sub git_get_ref ($) {
581 # => '' if no such ref
584 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
585 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
588 sub git_for_each_tag_referring ($$) {
589 my ($objreferring, $func) = @_;
590 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
591 printdebug "git_for_each_tag_referring ",
592 ($objreferring // 'UNDEF'),"\n";
593 git_for_each_ref('refs/tags', sub {
594 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
595 return unless $objtype eq 'tag';
596 my $refobjid = git_rev_parse $tagobjid;
598 !defined $objreferring # caller wants them all
599 or $tagobjid eq $objreferring
600 or $refobjid eq $objreferring;
601 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
605 sub git_check_unmodified () {
606 foreach my $cached (qw(0 1)) {
607 my @cmd = qw(git diff --quiet);
608 push @cmd, qw(--cached) if $cached;
611 $!=0; $?=-1; system @cmd;
616 ? __ "git index contains changes (does not match HEAD)"
617 : __ "working tree is dirty (does not match HEAD)";
624 sub upstream_commitish_search ($$) {
625 my ($upstream_version, $tried) = @_;
626 # todo: at some point maybe use git-deborig to do this
627 foreach my $tagpfx ('', 'v', 'upstream/') {
628 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
629 my $new_upstream = git_get_ref "refs/tags/$tag";
631 return $new_upstream if length $new_upstream;
635 sub resolve_upstream_version ($$) {
636 my ($new_upstream, $upstream_version) = @_;
638 my $used = $new_upstream;
639 my $message = __ 'using specified upstream commitish';
640 if (!defined $new_upstream) {
642 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
643 if (!length $new_upstream) {
645 "Could not determine appropriate upstream commitish.\n".
646 " (Tried these tags: %s)\n".
647 " Check version, and specify upstream commitish explicitly.",
651 $message = f_ 'using upstream from git tag %s', $used;
653 $new_upstream = git_rev_parse $new_upstream;
655 return ($new_upstream, $used, $message);
656 # used is a human-readable idea of what we found
659 sub is_fast_fwd ($$) {
660 my ($ancestor,$child) = @_;
661 my @cmd = (qw(git merge-base), $ancestor, $child);
662 my $mb = cmdoutput_errok @cmd;
664 return git_rev_parse($mb) eq git_rev_parse($ancestor);
666 $?==256 or failedcmd @cmd;
671 sub git_reflog_action_msg ($) {
673 my $rla = $ENV{GIT_REFLOG_ACTION};
674 $msg = "$rla: $msg" if length $rla;
678 sub git_update_ref_cmd {
679 # returns qw(git update-ref), qw(-m), @_
680 # except that message may be modified to honour GIT_REFLOG_ACTION
682 $msg = git_reflog_action_msg $msg;
683 return qw(git update-ref -m), $msg, @_;
686 sub rm_subdir_cached ($) {
688 runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
691 sub read_tree_subdir ($$) {
692 my ($subdir, $new_tree_object) = @_;
693 # If $new_tree_object is '', the subtree is deleted.
694 confess unless defined $new_tree_object;
695 rm_subdir_cached $subdir;
696 runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object
697 if length $new_tree_object;
700 sub read_tree_debian ($) {
702 read_tree_subdir 'debian', "$treeish:debian";
703 rm_subdir_cached 'debian/patches';
706 sub read_tree_upstream ($;$$) {
707 my ($treeish, $keep_patches, $tree_with_debian) = @_;
708 # if $tree_with_debian is supplied, will use that for debian/
709 # otherwise will save and restore it. If $tree_with_debian
710 # is '' then debian/ is deleted.
712 defined $tree_with_debian ? "$tree_with_debian:debian"
713 : cmdoutput qw(git write-tree --prefix=debian/);
714 runcmd qw(git read-tree), $treeish;
715 read_tree_subdir 'debian', $debian;
716 rm_subdir_cached 'debian/patches' unless $keep_patches;
721 printdebug "CD $newdir\n";
722 chdir $newdir or confess "chdir: $newdir: $!";
725 sub git_slurp_config_src ($) {
727 # returns $r such that $r->{KEY}[] = VALUE
728 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
731 local ($debuglevel) = $debuglevel-2;
735 open GITS, "-|", @cmd or confess "$!";
738 printdebug "=> ", (messagequote $_), "\n";
739 m/\n/ or confess "$_ ?";
740 push @{ $r->{$`} }, $'; #';
744 or ($!==0 && $?==256)
749 sub gdr_ffq_prev_branchinfo ($) {
751 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
753 # branch message is undef
754 # weird-symref } no $symref,
755 # notbranch } no $ffq_prev
756 return ('detached', __ 'detached HEAD') unless defined $symref;
757 return ('weird-symref', __ 'HEAD symref is not to refs/')
758 unless $symref =~ m{^refs/};
759 my $ffq_prev = "refs/$ffq_refprefix/$'";
760 my $gdrlast = "refs/$gdrlast_refprefix/$'";
761 printdebug "ffq_prev_branchinfo branch current $symref\n";
762 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
765 sub parsecontrolfh ($$;$) {
766 my ($fh, $desc, $allowsigned) = @_;
767 our $dpkgcontrolhash_noissigned;
770 my %opts = ('name' => $desc);
771 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
772 $c = Dpkg::Control::Hash->new(%opts);
773 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
774 last if $allowsigned;
775 last if $dpkgcontrolhash_noissigned;
776 my $issigned= $c->get_option('is_pgp_signed');
777 if (!defined $issigned) {
778 $dpkgcontrolhash_noissigned= 1;
779 seek $fh, 0,0 or confess "seek $desc: $!";
780 } elsif ($issigned) {
782 "control file %s is (already) PGP-signed. ".
783 " Note that dgit push needs to modify the .dsc and then".
784 " do the signature itself",
794 my ($file, $desc, $allowsigned) = @_;
795 my $fh = new IO::Handle;
796 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
797 my $c = parsecontrolfh($fh,$desc,$allowsigned);
798 $fh->error and confess "$!";
804 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
805 my $p = new IO::Handle;
806 my @cmd = (qw(dpkg-parsechangelog), @_);
807 open $p, '-|', @cmd or confess "$!";
809 $?=0; $!=0; close $p or failedcmd @cmd;
814 my ($dctrl,$field) = @_;
815 my $v = $dctrl->{$field};
816 return $v if defined $v;
817 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
820 sub parsechangelog_loop ($$$) {
821 my ($clogcmd, $descbase, $fn) = @_;
822 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
823 # calls $fn->($thisstanza, $desc);
824 debugcmd "|",@$clogcmd;
825 open CLOGS, "-|", @$clogcmd or confess "$!";
827 my $stanzatext = do { local $/=""; <CLOGS>; };
828 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
829 last if !defined $stanzatext;
831 my $desc = "$descbase, entry no.$.";
832 open my $stanzafh, "<", \$stanzatext or confess;
833 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
835 $fn->($thisstanza, $desc);
837 confess "$!" if CLOGS->error;
838 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
841 sub make_commit ($$) {
842 my ($parents, $message_paras) = @_;
843 my $tree = cmdoutput qw(git write-tree);
844 my @cmd = (qw(git commit-tree), $tree);
845 push @cmd, qw(-p), $_ foreach @$parents;
846 push @cmd, qw(-m), $_ foreach @$message_paras;
847 return cmdoutput @cmd;
850 sub hash_commit ($) {
852 return cmdoutput qw(git hash-object -w -t commit), $file;
855 sub hash_commit_text ($) {
858 my @cmd = (qw(git hash-object -w -t commit --stdin));
860 print Dumper($text) if $debuglevel > 1;
861 my $child = open2($out, $in, @cmd) or confess "$!";
864 print $in $text or confess "$!";
865 close $in or confess "$!";
867 $h =~ m/^\w+$/ or confess;
869 printdebug "=> $h\n";
872 waitpid $child, 0 == $child or confess "$child $!";
873 $? and failedcmd @cmd;
877 sub reflog_cache_insert ($$$) {
878 my ($ref, $cachekey, $value) = @_;
879 # you must call this in $maindir
880 # you must have called record_maindir
882 # When we no longer need to support squeeze, use --create-reflog
884 my $parent = $ref; $parent =~ s{/[^/]+$}{};
885 ensuredir "$maindir_gitcommon/logs/$parent";
886 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
889 my $oldcache = git_get_ref $ref;
891 if ($oldcache eq $value) {
892 my $tree = cmdoutput qw(git rev-parse), "$value:";
893 # git update-ref doesn't always update, in this case. *sigh*
894 my $authline = (ucfirst _us()).
895 ' <'._us().'@example.com> 1000000000 +0000';
896 my $dummy = hash_commit_text <<ENDU.(__ <<END);
903 Dummy commit - do not use
905 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
907 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
910 sub reflog_cache_lookup ($$) {
911 my ($ref, $cachekey) = @_;
912 # you may call this in $maindir or in a playtree
913 # you must have called record_maindir
914 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
915 debugcmd "|(probably)",@cmd;
916 my $child = open GC, "-|"; defined $child or confess "$!";
918 chdir $maindir or confess "$!";
919 if (!stat "$maindir_gitcommon/logs/$ref") {
920 $! == ENOENT or confess "$!";
921 printdebug ">(no reflog)\n";
924 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
928 printdebug ">| ", $_, "\n" if $debuglevel > 1;
929 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
933 confess "$!" if GC->error;
934 failedcmd unless close GC;
938 # ========== playground handling ==========
942 # $maindir user's git working tree
943 # playground area in .git/ where we can make files, unpack, etc. etc.
944 # playtree git working tree sharing object store with the user's
945 # inside playground, or identical to it
949 # $local_git_cfg hash of arrays of values: git config from $maindir
951 # expected calling pattern
956 # must be run in directory containing .git
957 # assigns to $maindir if not already set
958 # also calls git_slurp_config_src to record git config
959 # in $local_git_cfg, unless it's already set
961 # fresh_playground SUBDIR_PATH_COMPONENTS
962 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
963 # default SUBDIR_PATH_COMPONENTS is playground_subdir
964 # calls record_maindir
965 # sets up a new playground (destroying any old one)
966 # returns playground pathname
967 # caller may call multiple times with different subdir paths
968 # createing different playgrounds
970 # ensure_a_playground SUBDIR_PATH_COMPONENTS
971 # like fresh_playground except:
972 # merely ensures the directory exists; does not delete an existing one
976 # changedir playground
979 # playtree_setup $local_git_cfg
980 # # ^ call in some (perhaps trivial) subdir of playground
984 # ----- maindir -----
988 sub record_maindir () {
989 if (!defined $maindir) {
990 $maindir = must_getcwd();
991 if (!stat "$maindir/.git") {
992 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
995 # we fall back to this in case we have a pre-worktree
996 # git, which may not know git rev-parse --git-common-dir
997 $maindir_gitdir = "$maindir/.git";
998 $maindir_gitcommon = "$maindir/.git";
1000 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
1001 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
1004 $local_git_cfg //= git_slurp_config_src 'local';
1007 # ----- playgrounds -----
1009 sub ensure_a_playground_parent ($) {
1012 $spc = "$maindir_gitdir/$spc";
1013 my $parent = dirname $spc;
1014 mkdir $parent or $!==EEXIST or fail f_
1015 "failed to mkdir playground parent %s: %s", $parent, $!;
1019 sub ensure_a_playground ($) {
1021 $spc = ensure_a_playground_parent $spc;
1022 mkdir $spc or $!==EEXIST or fail f_
1023 "failed to mkdir a playground %s: %s", $spc, $!;
1027 sub fresh_playground ($) {
1029 $spc = ensure_a_playground_parent $spc;
1031 mkdir $spc or fail f_
1032 "failed to mkdir the playground %s: %s", $spc, $!;
1036 # ----- playtrees -----
1038 sub playtree_setup (;$) {
1039 my ($t_local_git_cfg) = @_;
1040 $t_local_git_cfg //= $local_git_cfg;
1041 # for use in the playtree
1042 # $maindir must be set, eg by calling record_maindir or fresh_playground
1043 runcmd qw(git init -q);
1044 runcmd qw(git config gc.auto 0);
1045 foreach my $copy (qw(user.email user.name user.useConfigOnly
1046 core.sharedRepository
1047 core.compression core.looseCompression
1048 core.bigFileThreshold core.fsyncObjectFiles)) {
1049 my $v = $t_local_git_cfg->{$copy};
1051 runcmd qw(git config), $copy, $_ foreach @$v;
1053 # this is confusing: we have
1054 # . playtree, not a worktree, has .git/, our cwd
1055 # $maindir might be a worktree so
1056 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1057 # $maindir_gitcommon the shared stuff, including .objects
1058 rmtree('.git/objects');
1059 symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1060 ensuredir '.git/info';
1061 open GA, "> .git/info/attributes" or confess "$!";
1062 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1063 close GA or confess "$!";