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 $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 $deliberately_re = "(?:TEST-)?$package_re";
100 our $distro_re = $component_re;
101 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
102 our $branchprefix = 'dgit';
103 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
104 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
105 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
106 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
107 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
108 our $git_null_obj = '0' x 40;
109 our $ffq_refprefix = 'ffq-prev';
110 our $gdrlast_refprefix = 'debrebase-last';
111 our $printdebug_when_debuglevel = 1;
112 our $debugcmd_when_debuglevel = 1;
114 # these three all go together, only valid after record_maindir
117 our $maindir_gitcommon;
119 # policy hook exit status bits
120 # see dgit-repos-server head comment for documentation
121 # 1 is reserved in case something fails with `exit 1' and to spot
122 # dynamic loader, runtime, etc., failures, which report 127 or 255
123 sub NOFFCHECK () { return 0x2; }
124 sub FRESHREPO () { return 0x4; }
125 sub NOCOMMITCHECK () { return 0x8; }
130 our $negate_harmful_gitattrs =
131 "-text -eol -crlf -ident -filter -working-tree-encoding";
132 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
134 our $forkcheck_mainprocess;
136 sub forkcheck_setup () {
137 $forkcheck_mainprocess = $$;
140 sub forkcheck_mainprocess () {
141 # You must have called forkcheck_setup or setup_sigwarn already
142 getppid != $forkcheck_mainprocess;
145 sub setup_sigwarn () {
147 $SIG{__WARN__} = sub {
148 confess $_[0] if forkcheck_mainprocess;
154 open DEBUG, ">/dev/null" or confess "$!";
158 open DEBUG, ">&STDERR" or confess "$!";
163 sub enabledebuglevel ($) {
164 my ($newlevel) = @_; # may be undef (eg from env var)
165 confess if $debuglevel;
168 return unless $newlevel;
169 $debuglevel = $newlevel;
174 # Prints a prefix, and @_, to DEBUG. @_ should normally contain
177 # With no (or only empty) arguments just prints the prefix and
178 # leaves the caller to do more with DEBUG. The caller should make
179 # sure then to call printdebug with something ending in "\n" to
180 # get the prefix right in subsequent calls.
182 return unless $debuglevel >= $printdebug_when_debuglevel;
183 our $printdebug_noprefix;
184 print DEBUG $debugprefix unless $printdebug_noprefix;
185 pop @_ while @_ and !length $_[-1];
187 print DEBUG @_ or confess "$!";
188 $printdebug_noprefix = $_[-1] !~ m{\n$};
191 sub messagequote ($) {
197 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
204 defined or confess __ 'internal error' foreach @_;
207 if (!length || m{[^-=_./:0-9a-z]}i) {
214 return join ' ', @out;
219 my $intro = shift @_;
220 print $fh $intro," " or confess "$!";
221 print $fh shellquote @_ or confess "$!";
222 print $fh "\n" or confess "$!";
226 my $extraprefix = shift @_;
227 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
228 if $debuglevel >= $debugcmd_when_debuglevel;
231 sub dep14_version_mangle ($) {
233 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
235 $v =~ s/\.(?=\.|$|lock$)/.#/g;
239 sub debiantag_new ($$) {
240 my ($v,$distro) = @_;
241 return "archive/$distro/".dep14_version_mangle $v;
244 sub debiantag_maintview ($$) {
245 my ($v,$distro) = @_;
246 return "$distro/".dep14_version_mangle $v;
249 sub debiantags ($$) {
250 my ($version,$distro) = @_;
251 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
260 sub upstreamversion ($) {
266 sub source_file_leafname ($$$) {
267 my ($package,$vsn,$sfx) = @_;
268 return "${package}_".(stripepoch $vsn).$sfx
271 sub is_orig_file_of_p_v ($$$) {
272 my ($f, $package, $upstreamvsn) = @_;
273 my $base = source_file_leafname $package, $upstreamvsn, '';
274 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
278 sub server_branch ($) { return "$branchprefix/$_[0]"; }
279 sub server_ref ($) { return "refs/".server_branch($_[0]); }
281 sub stat_exists ($) {
284 return 0 if $!==&ENOENT;
285 confess "stat $f: $!";
289 $::us // ($0 =~ m#[^/]*$#, $&);
293 my $s = f_ "error: %s\n", "@_";
295 my $prefix = _us().": ";
296 $s =~ s/^/$prefix/gm;
305 my ($dir) = @_; # does not create parents
306 return if mkdir $dir;
307 return if $! == EEXIST;
308 confess "mkdir $dir: $!";
313 defined $d or fail f_ "getcwd failed: %s\n", $!;
317 sub executable_on_path ($) {
319 return 1 if $program =~ m{/};
320 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
321 foreach my $pe (@path) {
322 my $here = "$pe/$program";
323 return $here if stat_exists $here && -x _;
328 our @signames = split / /, $Config{sig_name};
330 sub waitstatusmsg () {
332 return __ "terminated, reporting successful completion";
333 } elsif (!($? & 255)) {
334 return f_ "failed with error exit status %s", WEXITSTATUS($?);
335 } elsif (WIFSIGNALED($?)) {
336 my $signum=WTERMSIG($?);
337 return f_ "died due to fatal signal %s",
338 ($signames[$signum] // "number $signum").
339 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
341 return f_ "failed with unknown wait status %s", $?;
345 sub failedcmd_report_cmd {
346 my $intro = shift @_;
347 $intro //= __ "failed command";
348 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
351 sub failedcmd_waitstatus {
353 return f_ "failed to fork/exec: %s", $!;
355 return f_ "subprocess %s", waitstatusmsg();
357 return __ "subprocess produced invalid output";
362 # Expects $!,$? as set by close - see below.
363 # To use with system(), set $?=-1 first.
365 # Actual behaviour of perl operations:
366 # success $!==0 $?==0 close of piped open
367 # program failed $!==0 $? >0 close of piped open
368 # syscall failure $! >0 $?=-1 close of piped open
369 # failure $! >0 unchanged close of something else
370 # success trashed $?==0 system
371 # program failed trashed $? >0 system
372 # syscall failure $! >0 unchanged system
373 failedcmd_report_cmd undef, @_;
374 fail failedcmd_waitstatus();
380 failedcmd @_ if system @_;
384 my ($first_shell, @cmd) = @_;
385 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
388 sub cmdoutput_errok {
389 confess Dumper(\@_)." ?" if grep { !defined } @_;
390 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
392 open P, "-|", @_ or confess "$_[0] $!";
395 { local $/ = undef; $d = <P>; }
396 confess "$!" if P->error;
397 if (!close P) { printdebug "=>!$?\n"; return undef; }
399 if ($debuglevel > 0) {
402 my $more = (length $' ? '...' : ''); #');
403 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
404 printdebug "=> \`$dd'",$more,"\n";
410 my $d = cmdoutput_errok @_;
411 defined $d or failedcmd @_;
415 sub link_ltarget ($$) {
417 lstat $old or return undef;
419 $old = cmdoutput qw(realpath --), $old;
421 my $r = link $old, $new;
422 $r = symlink $old, $new if !$r && $!==EXDEV;
423 $r or fail "(sym)link $old $new: $!\n";
426 sub rename_link_xf ($$$) {
427 # renames/moves or links/copies $src to $dst,
428 # even if $dst is on a different fs
429 # (May use the filename "$dst.tmp".);
430 # On success, returns true.
431 # On failure, returns false and sets
432 # $@ to a reason message
433 # $! to an errno value, or -1 if not known
434 # having possibly printed something about mv to stderr.
435 # Not safe to use without $keeporig if $dst might be a symlink
436 # to $src, as it might delete $src leaving $dst invalid.
437 my ($keeporig,$src,$dst) = @_;
440 : rename $src, $dst) {
448 $@ = f_ "stat source file: %S", $!;
451 my @src_stat = (stat _)[0..1];
455 @dst_stat = (stat _)[0..1];
456 } elsif ($! == ENOENT) {
458 $@ = f_ "stat destination file: %S", $!;
462 if ("@src_stat" eq "@dst_stat") {
463 # (Symlinks to) the same file. No need for a copy but
464 # we may need to delete the original.
465 printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
468 my @cmd = (qw(cp --), $src, "$dst.tmp");
471 failedcmd_report_cmd undef, @cmd;
472 $@ = failedcmd_waitstatus();
476 if (!rename "$dst.tmp", $dst) {
477 $@ = f_ "finally install file after cp: %S", $!;
483 $@ = f_ "delete old file after cp: %S", $!;
492 my $h = Digest::SHA->new(256);
494 return $h->hexdigest();
497 sub git_rev_parse ($) {
498 return cmdoutput qw(git rev-parse), "$_[0]~0";
501 sub changedir_git_toplevel () {
502 my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
503 length $toplevel or fail __ <<END;
504 not in a git working tree?
505 (git rev-parse --show-toplevel produced no output)
507 chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
510 sub git_cat_file ($;$) {
511 my ($objname, $etype) = @_;
512 # => ($type, $data) or ('missing', undef)
513 # in scalar context, just the data
514 # if $etype defined, dies unless type is $etype or in @$etype
515 our ($gcf_pid, $gcf_i, $gcf_o);
516 local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
518 my ($gtype, $data) = @_;
520 $etype = [$etype] unless ref $etype;
521 confess "$objname expected @$etype but is $gtype"
522 unless grep { $gtype eq $_ } @$etype;
524 return ($gtype, $data);
527 my @cmd = qw(git cat-file --batch);
528 debugcmd "GCF|", @cmd;
529 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
531 printdebug "GCF>| $objname\n";
532 print $gcf_i $objname, "\n" or confess "$!";
534 printdebug "GCF<| ", $x;
535 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
536 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
538 (read $gcf_o, $data, $size) == $size or confess "$objname $!";
540 $x eq "\n" or confess "$objname ($_) $!";
541 return $chk->($type, $data);
544 sub git_get_symref (;$) {
545 my ($symref) = @_; $symref //= 'HEAD';
546 # => undef if not a symref, otherwise refs/...
547 my @cmd = (qw(git symbolic-ref -q HEAD));
548 my $branch = cmdoutput_errok @cmd;
549 if (!defined $branch) {
550 $?==256 or failedcmd @cmd;
557 sub git_for_each_ref ($$;$) {
558 my ($pattern,$func,$gitdir) = @_;
559 # calls $func->($objid,$objtype,$fullrefname,$reftail);
560 # $reftail is RHS of ref after refs/[^/]+/
561 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
562 # $pattern may be an array ref to mean multiple patterns
563 $pattern = [ $pattern ] unless ref $pattern;
564 my @cmd = (qw(git for-each-ref), @$pattern);
565 if (defined $gitdir) {
566 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
568 open GFER, "-|", @cmd or confess "$!";
571 chomp or confess "$_ ?";
572 printdebug "|> ", $_, "\n";
573 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
574 $func->($1,$2,$3,$4);
576 $!=0; $?=0; close GFER or confess "$pattern $? $!";
579 sub git_get_ref ($) {
580 # => '' if no such ref
583 s{^refs/}{[r]efs/} or confess "$refname $_ ?";
584 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
587 sub git_for_each_tag_referring ($$) {
588 my ($objreferring, $func) = @_;
589 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
590 printdebug "git_for_each_tag_referring ",
591 ($objreferring // 'UNDEF'),"\n";
592 git_for_each_ref('refs/tags', sub {
593 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
594 return unless $objtype eq 'tag';
595 my $refobjid = git_rev_parse $tagobjid;
597 !defined $objreferring # caller wants them all
598 or $tagobjid eq $objreferring
599 or $refobjid eq $objreferring;
600 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
604 sub git_check_unmodified () {
605 foreach my $cached (qw(0 1)) {
606 my @cmd = qw(git diff --quiet);
607 push @cmd, qw(--cached) if $cached;
610 $!=0; $?=-1; system @cmd;
615 ? __ "git index contains changes (does not match HEAD)"
616 : __ "working tree is dirty (does not match HEAD)";
623 sub upstream_commitish_search ($$) {
624 my ($upstream_version, $tried) = @_;
625 # todo: at some point maybe use git-deborig to do this
626 foreach my $tagpfx ('', 'v', 'upstream/') {
627 my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
628 my $new_upstream = git_get_ref "refs/tags/$tag";
630 return $new_upstream if length $new_upstream;
634 sub resolve_upstream_version ($$) {
635 my ($new_upstream, $upstream_version) = @_;
637 my $used = $new_upstream;
638 my $message = __ 'using specified upstream commitish';
639 if (!defined $new_upstream) {
641 $new_upstream = upstream_commitish_search $upstream_version, \@tried;
642 if (!length $new_upstream) {
644 "Could not determine appropriate upstream commitish.\n".
645 " (Tried these tags: %s)\n".
646 " Check version, and specify upstream commitish explicitly.",
650 $message = f_ 'using upstream from git tag %s', $used;
652 $new_upstream = git_rev_parse $new_upstream;
654 return ($new_upstream, $used, $message);
655 # used is a human-readable idea of what we found
658 sub is_fast_fwd ($$) {
659 my ($ancestor,$child) = @_;
660 my @cmd = (qw(git merge-base), $ancestor, $child);
661 my $mb = cmdoutput_errok @cmd;
663 return git_rev_parse($mb) eq git_rev_parse($ancestor);
665 $?==256 or failedcmd @cmd;
670 sub git_reflog_action_msg ($) {
672 my $rla = $ENV{GIT_REFLOG_ACTION};
673 $msg = "$rla: $msg" if length $rla;
677 sub git_update_ref_cmd {
678 # returns qw(git update-ref), qw(-m), @_
679 # except that message may be modified to honour GIT_REFLOG_ACTION
681 $msg = git_reflog_action_msg $msg;
682 return qw(git update-ref -m), $msg, @_;
685 sub rm_subdir_cached ($) {
687 runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
690 sub read_tree_subdir ($$) {
691 my ($subdir, $new_tree_object) = @_;
692 rm_subdir_cached $subdir;
693 runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object;
696 sub read_tree_debian ($) {
698 read_tree_subdir 'debian', "$treeish:debian";
699 rm_subdir_cached 'debian/patches';
702 sub read_tree_upstream ($;$$) {
703 my ($treeish, $keep_patches, $tree_with_debian) = @_;
704 # if $tree_with_debian is supplied, will use that for debian/
705 # otherwise will save and restore it.
707 $tree_with_debian ? "$tree_with_debian:debian"
708 : cmdoutput qw(git write-tree --prefix=debian/);
709 runcmd qw(git read-tree), $treeish;
710 read_tree_subdir 'debian', $debian;
711 rm_subdir_cached 'debian/patches' unless $keep_patches;
716 printdebug "CD $newdir\n";
717 chdir $newdir or confess "chdir: $newdir: $!";
720 sub git_slurp_config_src ($) {
722 # returns $r such that $r->{KEY}[] = VALUE
723 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
726 local ($debuglevel) = $debuglevel-2;
730 open GITS, "-|", @cmd or confess "$!";
733 printdebug "=> ", (messagequote $_), "\n";
734 m/\n/ or confess "$_ ?";
735 push @{ $r->{$`} }, $'; #';
739 or ($!==0 && $?==256)
744 sub gdr_ffq_prev_branchinfo ($) {
746 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
748 # branch message is undef
749 # weird-symref } no $symref,
750 # notbranch } no $ffq_prev
751 return ('detached', __ 'detached HEAD') unless defined $symref;
752 return ('weird-symref', __ 'HEAD symref is not to refs/')
753 unless $symref =~ m{^refs/};
754 my $ffq_prev = "refs/$ffq_refprefix/$'";
755 my $gdrlast = "refs/$gdrlast_refprefix/$'";
756 printdebug "ffq_prev_branchinfo branch current $symref\n";
757 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
760 sub parsecontrolfh ($$;$) {
761 my ($fh, $desc, $allowsigned) = @_;
762 our $dpkgcontrolhash_noissigned;
765 my %opts = ('name' => $desc);
766 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
767 $c = Dpkg::Control::Hash->new(%opts);
768 $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
769 last if $allowsigned;
770 last if $dpkgcontrolhash_noissigned;
771 my $issigned= $c->get_option('is_pgp_signed');
772 if (!defined $issigned) {
773 $dpkgcontrolhash_noissigned= 1;
774 seek $fh, 0,0 or confess "seek $desc: $!";
775 } elsif ($issigned) {
777 "control file %s is (already) PGP-signed. ".
778 " Note that dgit push needs to modify the .dsc and then".
779 " do the signature itself",
789 my ($file, $desc, $allowsigned) = @_;
790 my $fh = new IO::Handle;
791 open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
792 my $c = parsecontrolfh($fh,$desc,$allowsigned);
793 $fh->error and confess "$!";
799 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
800 my $p = new IO::Handle;
801 my @cmd = (qw(dpkg-parsechangelog), @_);
802 open $p, '-|', @cmd or confess "$!";
804 $?=0; $!=0; close $p or failedcmd @cmd;
809 my ($dctrl,$field) = @_;
810 my $v = $dctrl->{$field};
811 return $v if defined $v;
812 fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
815 sub parsechangelog_loop ($$$) {
816 my ($clogcmd, $descbase, $fn) = @_;
817 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
818 # calls $fn->($thisstanza, $desc);
819 debugcmd "|",@$clogcmd;
820 open CLOGS, "-|", @$clogcmd or confess "$!";
822 my $stanzatext = do { local $/=""; <CLOGS>; };
823 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
824 last if !defined $stanzatext;
826 my $desc = "$descbase, entry no.$.";
827 open my $stanzafh, "<", \$stanzatext or confess;
828 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
830 $fn->($thisstanza, $desc);
832 confess "$!" if CLOGS->error;
833 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
836 sub make_commit ($$) {
837 my ($parents, $message_paras) = @_;
838 my $tree = cmdoutput qw(git write-tree);
839 my @cmd = (qw(git commit-tree), $tree);
840 push @cmd, qw(-p), $_ foreach @$parents;
841 push @cmd, qw(-m), $_ foreach @$message_paras;
842 return cmdoutput @cmd;
845 sub hash_commit ($) {
847 return cmdoutput qw(git hash-object -w -t commit), $file;
850 sub hash_commit_text ($) {
853 my @cmd = (qw(git hash-object -w -t commit --stdin));
855 print Dumper($text) if $debuglevel > 1;
856 my $child = open2($out, $in, @cmd) or confess "$!";
859 print $in $text or confess "$!";
860 close $in or confess "$!";
862 $h =~ m/^\w+$/ or confess;
864 printdebug "=> $h\n";
867 waitpid $child, 0 == $child or confess "$child $!";
868 $? and failedcmd @cmd;
872 sub reflog_cache_insert ($$$) {
873 my ($ref, $cachekey, $value) = @_;
874 # you must call this in $maindir
875 # you must have called record_maindir
877 # When we no longer need to support squeeze, use --create-reflog
879 my $parent = $ref; $parent =~ s{/[^/]+$}{};
880 ensuredir "$maindir_gitcommon/logs/$parent";
881 my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
884 my $oldcache = git_get_ref $ref;
886 if ($oldcache eq $value) {
887 my $tree = cmdoutput qw(git rev-parse), "$value:";
888 # git update-ref doesn't always update, in this case. *sigh*
889 my $authline = (ucfirst _us()).
890 ' <'._us().'@example.com> 1000000000 +0000';
891 my $dummy = hash_commit_text <<ENDU.(__ <<END);
898 Dummy commit - do not use
900 runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
902 runcmd qw(git update-ref -m), $cachekey, $ref, $value;
905 sub reflog_cache_lookup ($$) {
906 my ($ref, $cachekey) = @_;
907 # you may call this in $maindir or in a playtree
908 # you must have called record_maindir
909 my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
910 debugcmd "|(probably)",@cmd;
911 my $child = open GC, "-|"; defined $child or confess "$!";
913 chdir $maindir or confess "$!";
914 if (!stat "$maindir_gitcommon/logs/$ref") {
915 $! == ENOENT or confess "$!";
916 printdebug ">(no reflog)\n";
919 exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
923 printdebug ">| ", $_, "\n" if $debuglevel > 1;
924 next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
928 confess "$!" if GC->error;
929 failedcmd unless close GC;
933 # ========== playground handling ==========
937 # $maindir user's git working tree
938 # playground area in .git/ where we can make files, unpack, etc. etc.
939 # playtree git working tree sharing object store with the user's
940 # inside playground, or identical to it
944 # $local_git_cfg hash of arrays of values: git config from $maindir
946 # expected calling pattern
951 # must be run in directory containing .git
952 # assigns to $maindir if not already set
953 # also calls git_slurp_config_src to record git config
954 # in $local_git_cfg, unless it's already set
956 # fresh_playground SUBDIR_PATH_COMPONENTS
957 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
958 # default SUBDIR_PATH_COMPONENTS is playground_subdir
959 # calls record_maindir
960 # sets up a new playground (destroying any old one)
961 # returns playground pathname
962 # caller may call multiple times with different subdir paths
963 # createing different playgrounds
965 # ensure_a_playground SUBDIR_PATH_COMPONENTS
966 # like fresh_playground except:
967 # merely ensures the directory exists; does not delete an existing one
971 # changedir playground
974 # playtree_setup $local_git_cfg
975 # # ^ call in some (perhaps trivial) subdir of playground
979 # ----- maindir -----
983 sub record_maindir () {
984 if (!defined $maindir) {
985 $maindir = must_getcwd();
986 if (!stat "$maindir/.git") {
987 fail f_ "cannot stat %s/.git: %s", $maindir, $!;
990 # we fall back to this in case we have a pre-worktree
991 # git, which may not know git rev-parse --git-common-dir
992 $maindir_gitdir = "$maindir/.git";
993 $maindir_gitcommon = "$maindir/.git";
995 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
996 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
999 $local_git_cfg //= git_slurp_config_src 'local';
1002 # ----- playgrounds -----
1004 sub ensure_a_playground_parent ($) {
1007 $spc = "$maindir_gitdir/$spc";
1008 my $parent = dirname $spc;
1009 mkdir $parent or $!==EEXIST or fail f_
1010 "failed to mkdir playground parent %s: %s", $parent, $!;
1014 sub ensure_a_playground ($) {
1016 $spc = ensure_a_playground_parent $spc;
1017 mkdir $spc or $!==EEXIST or fail f_
1018 "failed to mkdir a playground %s: %s", $spc, $!;
1022 sub fresh_playground ($) {
1024 $spc = ensure_a_playground_parent $spc;
1026 mkdir $spc or fail f_
1027 "failed to mkdir the playground %s: %s", $spc, $!;
1031 # ----- playtrees -----
1033 sub playtree_setup (;$) {
1034 my ($t_local_git_cfg) = @_;
1035 $t_local_git_cfg //= $local_git_cfg;
1036 # for use in the playtree
1037 # $maindir must be set, eg by calling record_maindir or fresh_playground
1038 runcmd qw(git init -q);
1039 runcmd qw(git config gc.auto 0);
1040 foreach my $copy (qw(user.email user.name user.useConfigOnly
1041 core.sharedRepository
1042 core.compression core.looseCompression
1043 core.bigFileThreshold core.fsyncObjectFiles)) {
1044 my $v = $t_local_git_cfg->{$copy};
1046 runcmd qw(git config), $copy, $_ foreach @$v;
1048 # this is confusing: we have
1049 # . playtree, not a worktree, has .git/, our cwd
1050 # $maindir might be a worktree so
1051 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
1052 # $maindir_gitcommon the shared stuff, including .objects
1053 rmtree('.git/objects');
1054 symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1055 ensuredir '.git/info';
1056 open GA, "> .git/info/attributes" or confess "$!";
1057 print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1058 close GA or confess "$!";