3 # Debian::Dgit: functions common to dgit and its helpers and servers
5 # Copyright (C) 2015-2019 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/>.
32 use File::Path qw(:DEFAULT make_path);
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 ensurepath
55 must_getcwd executable_on_path
56 waitstatusmsg failedcmd_waitstatus
57 failedcmd_report_cmd failedcmd
58 runcmd shell_cmd cmdoutput cmdoutput_errok
60 git_rev_parse changedir_git_toplevel git_cat_file
61 git_get_ref git_get_symref git_for_each_ref
62 git_for_each_tag_referring is_fast_fwd
64 git_reflog_action_msg git_update_ref_cmd
65 rm_subdir_cached read_tree_subdir
66 read_tree_debian read_tree_upstream
67 make_commit hash_commit hash_commit_text
68 reflog_cache_insert reflog_cache_lookup
69 $package_re $component_re $suite_re $deliberately_re
70 $distro_re $versiontag_re $series_filename_re
71 $orig_f_comp_re $orig_f_sig_re
72 $tarball_f_ext_re $orig_f_tail_re
73 $extra_orig_namepart_re
76 $ffq_refprefix $gdrlast_refprefix
77 initdebug enabledebug enabledebuglevel
79 $printdebug_when_debuglevel $debugcmd_when_debuglevel
80 $debugprefix *debuglevel *DEBUG
81 shellquote printcmd messagequote
82 $negate_harmful_gitattrs
83 changedir git_slurp_config_src
84 gdr_ffq_prev_branchinfo
85 parsecontrolfh parsecontrol parsechangelog
86 getfield parsechangelog_loop
88 # implicitly uses $main::us
89 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
90 playground => [qw(record_maindir $maindir $local_git_cfg
91 $maindir_gitdir $maindir_gitcommon
93 ensure_a_playground)]);
94 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
95 @{ $EXPORT_TAGS{playground} } );
100 our $package_re = '[0-9a-z][-+.0-9a-z]*';
101 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
102 our $suite_re = '[-+.0-9a-z]+';
103 our $deliberately_re = "(?:TEST-)?$package_re";
104 our $distro_re = $component_re;
105 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
106 our $branchprefix = 'dgit';
107 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
108 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
109 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
110 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
111 our $tarball_f_ext_re = "\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
112 our $orig_f_tail_re = "$orig_f_comp_re$tarball_f_ext_re";
113 our $git_null_obj = '0' x 40;
114 our $ffq_refprefix = 'ffq-prev';
115 our $gdrlast_refprefix = 'debrebase-last';
116 our $printdebug_when_debuglevel = 1;
117 our $debugcmd_when_debuglevel = 1;
119 our (@git) = qw(git);
121 # these three all go together, only valid after record_maindir
124 our $maindir_gitcommon;
126 # policy hook exit status bits
127 # see dgit-repos-server head comment for documentation
128 # 1 is reserved in case something fails with `exit 1' and to spot
129 # dynamic loader, runtime, etc., failures, which report 127 or 255
130 sub NOFFCHECK () { return 0x2; }
131 sub FRESHREPO () { return 0x4; }
132 sub NOCOMMITCHECK () { return 0x8; }
137 our $negate_harmful_gitattrs =
138 "-text -eol -crlf -ident -filter -working-tree-encoding";
139 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
141 our $forkcheck_mainprocess;
143 sub forkcheck_setup () {
144 $forkcheck_mainprocess = $$;
147 sub forkcheck_mainprocess () {
148 # You must have called forkcheck_setup or setup_sigwarn already
149 getppid != $forkcheck_mainprocess;
152 sub setup_sigwarn () {
154 $SIG{__WARN__} = sub {
155 confess $_[0] if forkcheck_mainprocess;
161 open DEBUG, ">/dev/null" or confess "$!";
165 open DEBUG, ">&STDERR" or confess "$!";
170 sub enabledebuglevel ($) {
171 my ($newlevel) = @_; # may be undef (eg from env var)
172 confess if $debuglevel;
175 return unless $newlevel;
176 $debuglevel = $newlevel;
181 # Prints a prefix, and @_, to DEBUG. @_ should normally contain
184 # With no (or only empty) arguments just prints the prefix and
185 # leaves the caller to do more with DEBUG. The caller should make
186 # sure then to call printdebug with something ending in "\n" to
187 # get the prefix right in subsequent calls.
189 return unless $debuglevel >= $printdebug_when_debuglevel;
190 our $printdebug_noprefix;
191 print DEBUG $debugprefix unless $printdebug_noprefix;
192 pop @_ while @_ and !length $_[-1];
194 print DEBUG @_ or confess "$!";
195 $printdebug_noprefix = $_[-1] !~ m{\n$};
198 sub messagequote ($) {
204 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
211 defined or confess __ 'internal error' foreach @_;
214 if (!length || m{[^-=_./:0-9a-z]}i) {
221 return join ' ', @out;
226 my $intro = shift @_;
227 print $fh $intro." ".(join '', shellquote @_)."\n" or confess "$!";
231 my $extraprefix = shift @_;
232 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
233 if $debuglevel >= $debugcmd_when_debuglevel;
236 sub dep14_version_mangle ($) {
238 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
240 $v =~ s/\.(?=\.|$|lock$)/.#/g;
244 sub debiantag_new ($$) {
245 my ($v,$distro) = @_;
246 return "archive/$distro/".dep14_version_mangle $v;
249 sub debiantag_maintview ($$) {
250 my ($v,$distro) = @_;
251 return "$distro/".dep14_version_mangle $v;
254 sub debiantags ($$) {
255 my ($version,$distro) = @_;
256 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
265 sub upstreamversion ($) {
271 sub source_file_leafname ($$$) {
272 my ($package,$vsn,$sfx) = @_;
273 return "${package}_".(stripepoch $vsn).$sfx
276 sub is_orig_file_of_p_v ($$$) {
277 my ($f, $package, $upstreamvsn) = @_;
278 my $base = source_file_leafname $package, $upstreamvsn, '';
279 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
283 sub server_branch ($) { return "$branchprefix/$_[0]"; }
284 sub server_ref ($) { return "refs/".server_branch($_[0]); }
286 sub stat_exists ($) {
289 return 0 if $!==&ENOENT;
290 confess "stat $f: $!";
294 $::us // ($0 =~ m#[^/]*$#, $&);
298 my $s = f_ "error: %s\n", "@_";
300 my $prefix = _us().": ";
301 $s =~ s/^/$prefix/gm;
310 my ($dir) = @_; # does not create parents
311 return if mkdir $dir;
312 return if $! == EEXIST;
313 confess "mkdir $dir: $!";
316 sub ensurepath ($$) {
317 my ($firsttocreate, $subdir) = @_; # creates necessary bits of $subidr
318 ensuredir $firsttocreate;
319 make_path "$firsttocreate/$subdir";
324 defined $d or fail f_ "getcwd failed: %s\n", $!;
328 sub executable_on_path ($) {
330 return 1 if $program =~ m{/};
331 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
332 foreach my $pe (@path) {
333 my $here = "$pe/$program";
334 return $here if stat_exists $here && -x _;
339 our @signames = split / /, $Config{sig_name};
341 sub waitstatusmsg () {
343 return __ "terminated, reporting successful completion";
344 } elsif (!($? & 255)) {
345 return f_ "failed with error exit status %s", WEXITSTATUS($?);
346 } elsif (WIFSIGNALED($?)) {
347 my $signum=WTERMSIG($?);
348 return f_ "died due to fatal signal %s",
349 ($signames[$signum] // "number $signum").
350 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
352 return f_ "failed with unknown wait status %s", $?;
356 sub failedcmd_report_cmd {
357 my $intro = shift @_;
358 $intro //= __ "failed command";
359 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
362 sub failedcmd_waitstatus {
364 return f_ "failed to fork/exec: %s", $!;
366 return f_ "subprocess %s", waitstatusmsg();
368 return __ "subprocess produced invalid output";
373 # Expects $!,$? as set by close - see below.
374 # To use with system(), set $?=-1 first.
376 # Actual behaviour of perl operations:
377 # success $!==0 $?==0 close of piped open
378 # program failed $!==0 $? >0 close of piped open
379 # syscall failure $! >0 $?=-1 close of piped open
380 # failure $! >0 unchanged close of something else
381 # success trashed $?==0 system
382 # program failed trashed $? >0 system
383 # syscall failure $! >0 unchanged system
384 failedcmd_report_cmd undef, @_;
385 fail failedcmd_waitstatus();
391 failedcmd @_ if system @_;
395 my ($first_shell, @cmd) = @_;
396 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
399 sub cmdoutput_errok {
400 confess Dumper(\@_)." ?" if grep { !defined } @_;
401 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
403 open P, "-|", @_ or confess "$_[0] $!";
406 { local $/ = undef; $d = <P>; }
407 confess "$!" if P->error;
408 if (!close P) { printdebug "=>!$?\n"; return undef; }
410 if ($debuglevel > 0) {
413 my $more = (length $' ? '...' : ''); #');
414 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
415 printdebug "=> \`$dd'",$more,"\n";
421 my $d = cmdoutput_errok @_;
422 defined $d or failedcmd @_;
426 sub link_ltarget ($$) {
428 lstat $old or return undef;
430 $old = cmdoutput qw(realpath --), $old;
432 my $r = link $old, $new;
433 $r = symlink $old, $new if !$r && $!==EXDEV;
434 $r or fail "(sym)link $old $new: $!\n";
437 sub rename_link_xf ($$$) {
438 # renames/moves or links/copies $src to $dst,
439 # even if $dst is on a different fs
440 # (May use the filename "$dst.tmp".);
441 # On success, returns true.
442 # On failure, returns false and sets
443 # $@ to a reason message
444 # $! to an errno value, or -1 if not known
445 # having possibly printed something about mv to stderr.
446 # Not safe to use without $keeporig if $dst might be a symlink
447 # to $src, as it might delete $src leaving $dst invalid.
448 my ($keeporig,$src,$dst) = @_;
451 : rename $src, $dst) {
459 $@ = f_ "stat source file: %S", $!;
462 my @src_stat = (stat _)[0..1];
466 @dst_stat = (stat _)[0..1];
467 } elsif ($! == ENOENT) {
469 $@ = f_ "stat destination file: %S", $!;
473 if ("@src_stat" eq "@dst_stat") {
474 # (Symlinks to) the same file. No need for a copy but
475 # we may need to delete the original.
476 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
479 my @cmd = (qw(cp --), $src, "$dst.tmp");
482 failedcmd_report_cmd undef, @cmd;
483 $@ = failedcmd_waitstatus();
487 if (!rename "$dst.tmp", $dst) {
488 $@ = f_ "finally install file after cp: %S", $!;
494 $@ = f_ "delete old file after cp: %S", $!;
503 my $h = Digest::SHA->new(256);
505 return $h->hexdigest();
508 sub git_rev_parse ($) {
509 return cmdoutput qw(git rev-parse), "$_[0]~0";
512 sub changedir_git_toplevel () {
513 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
514 length $toplevel or fail __ <<END;
515 not in a git working tree?
516 (git rev-parse --show-toplevel produced no output)
518 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
521 sub git_cat_file ($;$) {
522 my ($objname, $etype) = @_;
523 # => ($type, $data) or ('missing', undef)
524 # in scalar context, just the data
525 # if $etype defined, dies unless type is $etype or in @$etype
526 our ($gcf_pid, $gcf_i, $gcf_o);
527 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
529 my ($gtype, $data) = @_;
531 $etype = [$etype] unless ref $etype;
532 confess "$objname expected @$etype but is $gtype"
533 unless grep { $gtype eq $_ } @$etype;
535 return ($gtype, $data);
538 my @cmd = qw(git cat-file --batch);
539 debugcmd "GCF|", @cmd;
540 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
542 printdebug "GCF>| $objname\n";
543 print $gcf_i $objname, "\n" or confess "$!";
545 printdebug "GCF<| ", $x;
546 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
547 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
549 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
551 $x eq "\n" or confess "$objname ($_) $!";
552 return $chk->($type, $data);
555 sub git_get_symref (;$) {
556 my ($symref) = @_; $symref //= 'HEAD';
557 # => undef if not a symref, otherwise refs/...
558 my @cmd = (qw(git symbolic-ref -q HEAD));
559 my $branch = cmdoutput_errok @cmd;
560 if (!defined $branch) {
561 $?==256 or failedcmd @cmd;
568 sub git_for_each_ref ($$;$) {
569 my ($pattern,$func,$gitdir) = @_;
570 # calls $func->($objid,$objtype,$fullrefname,$reftail);
571 # $reftail is RHS of ref after refs/[^/]+/
572 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
573 # $pattern may be an array ref to mean multiple patterns
574 $pattern = [ $pattern ] unless ref $pattern;
575 my @cmd = (qw(git for-each-ref), @$pattern);
576 if (defined $gitdir) {
577 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
579 open GFER, "-|", @cmd or confess "$!";
582 chomp or confess "$_ ?";
583 printdebug "|> ", $_, "\n";
584 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
585 $func->($1,$2,$3,$4);
587 $!=0; $?=0; close GFER or confess "$pattern $? $!";
590 sub git_get_ref ($) {
591 # => '' if no such ref
594 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
595 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
598 sub git_for_each_tag_referring ($$) {
599 my ($objreferring, $func) = @_;
600 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
601 printdebug "git_for_each_tag_referring ",
602 ($objreferring // 'UNDEF'),"\n";
603 git_for_each_ref('refs/tags', sub {
604 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
605 return unless $objtype eq 'tag';
606 my $refobjid = git_rev_parse $tagobjid;
608 !defined $objreferring # caller wants them all
609 or $tagobjid eq $objreferring
610 or $refobjid eq $objreferring;
611 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
615 sub git_check_unmodified () {
616 foreach my $cached (qw(0 1)) {
617 my @cmd = qw(git diff --quiet);
618 push @cmd, qw(--cached) if $cached;
621 $!=0; $?=-1; system @cmd;
626 ? __ "git index contains changes (does not match HEAD)"
627 : __ "working tree is dirty (does not match HEAD)";
634 sub upstream_commitish_search ($$) {
635 my ($upstream_version, $tried) = @_;
636 # todo: at some point maybe use git-deborig to do this
638 foreach my $tagpfx ('', 'v', 'upstream/') {
639 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
640 my $new_upstream = git_get_ref "refs/tags/$tag";
642 push @found, [ $tag, $new_upstream ] if $new_upstream;
644 return @{ $found[0] } if @found == 1;
648 sub resolve_upstream_version ($$) {
649 my ($new_upstream, $upstream_version) = @_;
651 my $used = $new_upstream;
652 my $message = __ 'using specified upstream commitish';
653 if (!defined $new_upstream) {
655 ($used, $new_upstream) =
656 upstream_commitish_search $upstream_version, \@tried;
657 if (!length $new_upstream) {
659 "Could not determine appropriate upstream commitish.\n".
660 " (Tried these tags: %s)\n".
661 " Check version, and specify upstream commitish explicitly.",
664 $message = f_ 'using upstream from git tag %s', $used;
665 } elsif ($new_upstream =~ m{^refs/tags/($versiontag_re)$}s) {
666 $message = f_ 'using upstream from git tag %s', $1;
669 $new_upstream = git_rev_parse $new_upstream;
671 return ($new_upstream, $used, $message);
672 # used is a human-readable idea of what we found
675 sub is_fast_fwd ($$) {
676 my ($ancestor,$child) = @_;
677 my @cmd = (qw(git merge-base), $ancestor, $child);
678 my $mb = cmdoutput_errok @cmd;
680 return git_rev_parse($mb) eq git_rev_parse($ancestor);
682 $?==256 or failedcmd @cmd;
687 sub git_reflog_action_msg ($) {
689 my $rla = $ENV{GIT_REFLOG_ACTION};
690 $msg = "$rla: $msg" if length $rla;
694 sub git_update_ref_cmd {
695 # returns qw(git update-ref), qw(-m), @_
696 # except that message may be modified to honour GIT_REFLOG_ACTION
698 $msg = git_reflog_action_msg $msg;
699 return qw(git update-ref -m), $msg, @_;
702 sub rm_subdir_cached ($) {
704 runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
707 sub read_tree_subdir ($$) {
708 my ($subdir, $new_tree_object) = @_;
709 # If $new_tree_object is '', the subtree is deleted.
710 confess unless defined $new_tree_object;
711 rm_subdir_cached $subdir;
712 runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object
713 if length $new_tree_object;
716 sub read_tree_debian ($) {
718 read_tree_subdir 'debian', "$treeish:debian";
719 rm_subdir_cached 'debian/patches';
722 sub read_tree_upstream ($;$$) {
723 my ($treeish, $keep_patches, $tree_with_debian) = @_;
724 # if $tree_with_debian is supplied, will use that for debian/
725 # otherwise will save and restore it. If $tree_with_debian
726 # is '' then debian/ is deleted.
728 defined $tree_with_debian ? "$tree_with_debian:debian"
729 : cmdoutput qw(git write-tree --prefix=debian/);
730 runcmd qw(git read-tree), $treeish;
731 read_tree_subdir 'debian', $debian;
732 rm_subdir_cached 'debian/patches' unless $keep_patches;
737 printdebug "CD $newdir\n";
738 chdir $newdir or confess "chdir: $newdir: $!";
741 sub git_slurp_config_src ($) {
743 # returns $r such that $r->{KEY}[] = VALUE
744 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
747 local ($debuglevel) = $debuglevel-2;
751 open GITS, "-|", @cmd or confess "$!";
754 printdebug "=> ", (messagequote $_), "\n";
755 m/\n/ or confess "$_ ?";
756 push @{ $r->{$`} }, $'; #';
760 or ($!==0 && $?==256)
765 sub gdr_ffq_prev_branchinfo ($) {
767 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
769 # branch message is undef
770 # weird-symref } no $symref,
771 # notbranch } no $ffq_prev
772 return ('detached', __ 'detached HEAD') unless defined $symref;
773 return ('weird-symref', __ 'HEAD symref is not to refs/')
774 unless $symref =~ m{^refs/};
775 my $ffq_prev = "refs/$ffq_refprefix/$'";
776 my $gdrlast = "refs/$gdrlast_refprefix/$'";
777 printdebug "ffq_prev_branchinfo branch current $symref\n";
778 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
781 sub parsecontrolfh ($$;$) {
782 my ($fh, $desc, $allowsigned) = @_;
783 our $dpkgcontrolhash_noissigned;
786 my %opts = ('name' => $desc);
787 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
788 $c = Dpkg::Control::Hash->new(%opts);
789 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
790 last if $allowsigned;
791 last if $dpkgcontrolhash_noissigned;
792 my $issigned= $c->get_option('is_pgp_signed');
793 if (!defined $issigned) {
794 $dpkgcontrolhash_noissigned= 1;
795 seek $fh, 0,0 or confess "seek $desc: $!";
796 } elsif ($issigned) {
798 "control file %s is (already) PGP-signed. ".
799 " Note that dgit push needs to modify the .dsc and then".
800 " do the signature itself",
810 my ($file, $desc, $allowsigned) = @_;
811 my $fh = new IO::Handle;
812 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
813 my $c = parsecontrolfh($fh,$desc,$allowsigned);
814 $fh->error and confess "$!";
820 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
821 my $p = new IO::Handle;
822 my @cmd = (qw(dpkg-parsechangelog), @_);
823 open $p, '-|', @cmd or confess "$!";
825 $?=0; $!=0; close $p or failedcmd @cmd;
830 my ($dctrl,$field) = @_;
831 my $v = $dctrl->{$field};
832 return $v if defined $v;
833 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
836 sub parsechangelog_loop ($$$) {
837 my ($clogcmd, $descbase, $fn) = @_;
838 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
839 # calls $fn->($thisstanza, $desc);
840 debugcmd "|",@$clogcmd;
841 open CLOGS, "-|", @$clogcmd or confess "$!";
843 my $stanzatext = do { local $/=""; <CLOGS>; };
844 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
845 last if !defined $stanzatext;
847 my $desc = "$descbase, entry no.$.";
848 open my $stanzafh, "<", \$stanzatext or confess;
849 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
851 $fn->($thisstanza, $desc);
853 confess "$!" if CLOGS->error;
854 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
857 sub make_commit ($$) {
858 my ($parents, $message_paras) = @_;
859 my $tree = cmdoutput qw(git write-tree);
860 my @cmd = (qw(git commit-tree), $tree);
861 push @cmd, qw(-p), $_ foreach @$parents;
862 push @cmd, qw(-m), $_ foreach @$message_paras;
863 return cmdoutput @cmd;
866 sub hash_commit ($) {
868 return cmdoutput qw(git hash-object -w -t commit), $file;
871 sub hash_commit_text ($) {
874 my @cmd = (qw(git hash-object -w -t commit --stdin));
876 print Dumper($text) if $debuglevel > 1;
877 my $child = open2($out, $in, @cmd) or confess "$!";
880 print $in $text or confess "$!";
881 close $in or confess "$!";
883 $h =~ m/^\w+$/ or confess;
885 printdebug "=> $h\n";
888 waitpid $child, 0 == $child or confess "$child $!";
889 $? and failedcmd @cmd;
893 sub reflog_cache_insert ($$$) {
894 my ($ref, $cachekey, $value) = @_;
895 # you must call this in $maindir
896 # you must have called record_maindir
898 # When we no longer need to support squeeze, use --create-reflog
900 my $parent = $ref; $parent =~ s{/[^/]+$}{};
901 ensurepath "$maindir_gitcommon/logs", "$parent";
902 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
905 my $oldcache = git_get_ref $ref;
907 if ($oldcache eq $value) {
908 my $tree = cmdoutput qw(git rev-parse), "$value:";
909 # git update-ref doesn't always update, in this case. *sigh*
910 my $authline = (ucfirst _us()).
911 ' <'._us().'@example.com> 1000000000 +0000';
912 my $dummy = hash_commit_text <<ENDU.(__ <<END);
919 Dummy commit - do not use
921 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
923 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
926 sub reflog_cache_lookup ($$) {
927 my ($ref, $cachekey) = @_;
928 # you may call this in $maindir or in a playtree
929 # you must have called record_maindir
930 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
931 debugcmd "|(probably)",@cmd;
932 my $child = open GC, "-|"; defined $child or confess "$!";
934 chdir $maindir or confess "$!";
935 if (!stat "$maindir_gitcommon/logs/$ref") {
936 $! == ENOENT or confess "$!";
937 printdebug ">(no reflog)\n";
940 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
944 printdebug ">| ", $_, "\n" if $debuglevel > 1;
945 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
949 confess "$!" if GC->error;
950 failedcmd unless close GC;
954 # ========== playground handling ==========
958 # $maindir user's git working tree
959 # playground area in .git/ where we can make files, unpack, etc. etc.
960 # playtree git working tree sharing object store with the user's
961 # inside playground, or identical to it
965 # $local_git_cfg hash of arrays of values: git config from $maindir
967 # expected calling pattern
972 # must be run in directory containing .git
973 # assigns to $maindir if not already set
974 # also calls git_slurp_config_src to record git config
975 # in $local_git_cfg, unless it's already set
977 # fresh_playground SUBDIR_PATH_COMPONENTS
978 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
979 # default SUBDIR_PATH_COMPONENTS is playground_subdir
980 # calls record_maindir
981 # sets up a new playground (destroying any old one)
982 # returns playground pathname
983 # caller may call multiple times with different subdir paths
984 # createing different playgrounds
986 # ensure_a_playground SUBDIR_PATH_COMPONENTS
987 # like fresh_playground except:
988 # merely ensures the directory exists; does not delete an existing one
992 # changedir playground
996 # # ^ call in some (perhaps trivial) subdir of playground
1000 # ----- maindir -----
1004 sub record_maindir () {
1005 if (!defined $maindir) {
1006 $maindir = must_getcwd();
1007 if (!stat "$maindir/.git") {
1008 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
1011 # we fall back to this in case we have a pre-worktree
1012 # git, which may not know git rev-parse --git-common-dir
1013 $maindir_gitdir = "$maindir/.git";
1014 $maindir_gitcommon = "$maindir/.git";
1016 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
1017 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
1020 $local_git_cfg //= git_slurp_config_src 'local';
1023 # ----- playgrounds -----
1025 sub ensure_a_playground_parent ($) {
1028 $spc = "$maindir_gitdir/$spc";
1029 my $parent = dirname $spc;
1030 mkdir $parent or $!==EEXIST or fail f_
1031 "failed to mkdir playground parent %s: %s", $parent, $!;
1035 sub ensure_a_playground ($) {
1037 $spc = ensure_a_playground_parent $spc;
1038 mkdir $spc or $!==EEXIST or fail f_
1039 "failed to mkdir a playground %s: %s", $spc, $!;
1043 sub fresh_playground ($) {
1045 $spc = ensure_a_playground_parent $spc;
1047 mkdir $spc or fail f_
1048 "failed to mkdir the playground %s: %s", $spc, $!;
1052 # ----- playtrees -----
1054 sub playtree_setup () {
1055 # for use in the playtree
1056 # $maindir must be set, eg by calling record_maindir or fresh_playground
1057 # this is confusing: we have
1058 # . playtree, not a worktree, has .git/, our cwd
1059 # $maindir might be a worktree so
1060 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1061 # $maindir_gitcommon the shared stuff, including .objects
1063 # we need to invoke git-playtree-setup via git because
1064 # there may be config options it needs which are only available
1065 # to us, sensibly, in @git
1067 # And, we look for it in @INC too. This is a bit perverse.
1068 # We do this because in the Debian packages we want to have
1069 # a copy of this script in each binary package, rather than
1070 # making yet another .deb or tangling the dependencies.
1071 # @INC is conveniently available.
1072 my $newpath = join ':', +(grep { !m/:/ } @INC),
1073 '/usr/share/dgit', $ENV{PATH};
1074 runcmd qw(env), "PATH=$newpath", @git, qw(playtree-setup .);
1076 ensuredir '.git/info';
1077 open GA, "> .git/info/attributes" or confess "$!";
1078 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1079 close GA or confess "$!";