chiark / gitweb /
Dgit.pm: Move make_commit (git-commit-tree wrapper) from gdr
[dgit.git] / Debian / Dgit.pm
1 # -*- perl -*-
2 # dgit
3 # Debian::Dgit: functions common to dgit and its helpers and servers
4 #
5 # Copyright (C) 2015-2016  Ian Jackson
6 #
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.
11 #
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.
16 #
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/>.
19
20 package Debian::Dgit;
21
22 use strict;
23 use warnings;
24
25 use Carp;
26 use POSIX;
27 use IO::Handle;
28 use Config;
29 use Digest::SHA;
30 use Data::Dumper;
31 use IPC::Open2;
32 use File::Path;
33 use File::Basename;
34 use Dpkg::Control::Hash;
35 use Debian::Dgit::ExitStatus;
36 use Debian::Dgit::I18n;
37
38 BEGIN {
39     use Exporter   ();
40     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
41
42     $VERSION     = 1.00;
43     @ISA         = qw(Exporter);
44     @EXPORT      = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
45                       dep14_version_mangle
46                       debiantags debiantag_new
47                       debiantag_maintview
48                       upstreamversion
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
53                       hashfile
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
61                       git_check_unmodified
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_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
71                       $git_null_obj
72                       $branchprefix
73                       $ffq_refprefix $gdrlast_refprefix
74                       initdebug enabledebug enabledebuglevel
75                       printdebug debugcmd
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
84                       playtree_setup);
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
89                                        fresh_playground
90                                        ensure_a_playground)]);
91     @EXPORT_OK   = ( @{ $EXPORT_TAGS{policyflags} },
92                      @{ $EXPORT_TAGS{playground} } );
93 }
94
95 our @EXPORT_OK;
96
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;
113
114 # these three all go together, only valid after record_maindir
115 our $maindir;
116 our $maindir_gitdir;
117 our $maindir_gitcommon;
118
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; }
126
127 our $debugprefix;
128 our $debuglevel = 0;
129
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
133
134 our $forkcheck_mainprocess;
135
136 sub forkcheck_setup () {
137     $forkcheck_mainprocess = $$;
138 }
139
140 sub forkcheck_mainprocess () {
141     # You must have called forkcheck_setup or setup_sigwarn already
142     getppid != $forkcheck_mainprocess;
143 }
144
145 sub setup_sigwarn () {
146     forkcheck_setup();
147     $SIG{__WARN__} = sub { 
148         confess $_[0] if forkcheck_mainprocess;
149     };
150 }
151
152 sub initdebug ($) { 
153     ($debugprefix) = @_;
154     open DEBUG, ">/dev/null" or confess "$!";
155 }
156
157 sub enabledebug () {
158     open DEBUG, ">&STDERR" or confess "$!";
159     DEBUG->autoflush(1);
160     $debuglevel ||= 1;
161 }
162     
163 sub enabledebuglevel ($) {
164     my ($newlevel) = @_; # may be undef (eg from env var)
165     confess if $debuglevel;
166     $newlevel //= 0;
167     $newlevel += 0;
168     return unless $newlevel;
169     $debuglevel = $newlevel;
170     enabledebug();
171 }
172     
173 sub printdebug {
174     # Prints a prefix, and @_, to DEBUG.  @_ should normally contain
175     # a trailing \n.
176
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.
181
182     return unless $debuglevel >= $printdebug_when_debuglevel;
183     our $printdebug_noprefix;
184     print DEBUG $debugprefix unless $printdebug_noprefix;
185     pop @_ while @_ and !length $_[-1];
186     return unless @_;
187     print DEBUG @_ or confess "$!";
188     $printdebug_noprefix = $_[-1] !~ m{\n$};
189 }
190
191 sub messagequote ($) {
192     local ($_) = @_;
193     s{\\}{\\\\}g;
194     s{\n}{\\n}g;
195     s{\x08}{\\b}g;
196     s{\t}{\\t}g;
197     s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
198     $_;
199 }
200
201 sub shellquote {
202     my @out;
203     local $_;
204     defined or confess __ 'internal error' foreach @_;
205     foreach my $a (@_) {
206         $_ = $a;
207         if (!length || m{[^-=_./:0-9a-z]}i) {
208             s{['\\]}{'\\$&'}g;
209             push @out, "'$_'";
210         } else {
211             push @out, $_;
212         }
213     }
214     return join ' ', @out;
215 }
216
217 sub printcmd {
218     my $fh = shift @_;
219     my $intro = shift @_;
220     print $fh $intro," " or confess "$!";
221     print $fh shellquote @_ or confess "$!";
222     print $fh "\n" or confess "$!";
223 }
224
225 sub debugcmd {
226     my $extraprefix = shift @_;
227     printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
228         if $debuglevel >= $debugcmd_when_debuglevel;
229 }
230
231 sub dep14_version_mangle ($) {
232     my ($v) = @_;
233     # DEP-14 patch proposed 2016-11-09  "Version Mangling"
234     $v =~ y/~:/_%/;
235     $v =~ s/\.(?=\.|$|lock$)/.#/g;
236     return $v;
237 }
238
239 sub debiantag_new ($$) { 
240     my ($v,$distro) = @_;
241     return "archive/$distro/".dep14_version_mangle $v;
242 }
243
244 sub debiantag_maintview ($$) { 
245     my ($v,$distro) = @_;
246     return "$distro/".dep14_version_mangle $v;
247 }
248
249 sub debiantags ($$) {
250     my ($version,$distro) = @_;
251     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
252 }
253
254 sub stripepoch ($) {
255     my ($vsn) = @_;
256     $vsn =~ s/^\d+\://;
257     return $vsn;
258 }
259
260 sub upstreamversion ($) {
261     my ($vsn) = @_;
262     $vsn =~ s/-[^-]+$//;
263     return $vsn;
264 }
265
266 sub source_file_leafname ($$$) {
267     my ($package,$vsn,$sfx) = @_;
268     return "${package}_".(stripepoch $vsn).$sfx
269 }
270
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$/;
275     return 1;
276 }
277
278 sub server_branch ($) { return "$branchprefix/$_[0]"; }
279 sub server_ref ($) { return "refs/".server_branch($_[0]); }
280
281 sub stat_exists ($) {
282     my ($f) = @_;
283     return 1 if stat $f;
284     return 0 if $!==&ENOENT;
285     confess "stat $f: $!";
286 }
287
288 sub _us () {
289     $::us // ($0 =~ m#[^/]*$#, $&);
290 }
291
292 sub failmsg {
293     my $s = f_ "error: %s\n", "@_";
294     $s =~ s/\n\n$/\n/g;
295     my $prefix = _us().": ";
296     $s =~ s/^/$prefix/gm;
297     return "\n".$s;
298 }
299
300 sub fail {
301     die failmsg @_;
302 }
303
304 sub ensuredir ($) {
305     my ($dir) = @_; # does not create parents
306     return if mkdir $dir;
307     return if $! == EEXIST;
308     confess "mkdir $dir: $!";
309 }
310
311 sub must_getcwd () {
312     my $d = getcwd();
313     defined $d or fail f_ "getcwd failed: %s\n", $!;
314     return $d;
315 }
316
317 sub executable_on_path ($) {
318     my ($program) = @_;
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 _;
324     }
325     return undef;
326 }
327
328 our @signames = split / /, $Config{sig_name};
329
330 sub waitstatusmsg () {
331     if (!$?) {
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
340     } else {
341         return f_ "failed with unknown wait status %s", $?;
342     }
343 }
344
345 sub failedcmd_report_cmd {
346     my $intro = shift @_;
347     $intro //= __ "failed command";
348     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
349 }
350
351 sub failedcmd_waitstatus {
352     if ($? < 0) {
353         return f_ "failed to fork/exec: %s", $!;
354     } elsif ($?) {
355         return f_ "subprocess %s", waitstatusmsg();
356     } else {
357         return __ "subprocess produced invalid output";
358     }
359 }
360
361 sub failedcmd {
362     # Expects $!,$? as set by close - see below.
363     # To use with system(), set $?=-1 first.
364     #
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();
375 }
376
377 sub runcmd {
378     debugcmd "+",@_;
379     $!=0; $?=-1;
380     failedcmd @_ if system @_;
381 }
382
383 sub shell_cmd {
384     my ($first_shell, @cmd) = @_;
385     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
386 }
387
388 sub cmdoutput_errok {
389     confess Dumper(\@_)." ?" if grep { !defined } @_;
390     local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
391     debugcmd "|",@_;
392     open P, "-|", @_ or confess "$_[0] $!";
393     my $d;
394     $!=0; $?=0;
395     { local $/ = undef; $d = <P>; }
396     confess "$!" if P->error;
397     if (!close P) { printdebug "=>!$?\n"; return undef; }
398     chomp $d;
399     if ($debuglevel > 0) {
400         $d =~ m/^.*/;
401         my $dd = $&;
402         my $more = (length $' ? '...' : ''); #');
403         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
404         printdebug "=> \`$dd'",$more,"\n";
405     }
406     return $d;
407 }
408
409 sub cmdoutput {
410     my $d = cmdoutput_errok @_;
411     defined $d or failedcmd @_;
412     return $d;
413 }
414
415 sub link_ltarget ($$) {
416     my ($old,$new) = @_;
417     lstat $old or return undef;
418     if (-l _) {
419         $old = cmdoutput qw(realpath  --), $old;
420     }
421     my $r = link $old, $new;
422     $r = symlink $old, $new if !$r && $!==EXDEV;
423     $r or fail "(sym)link $old $new: $!\n";
424 }
425
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) = @_;
438     if ($keeporig
439         ? link   $src, $dst
440         : rename $src, $dst) {
441         return 1;
442     }
443     if ($! != EXDEV) {
444         $@ = "$!";
445         return 0;
446     }
447     if (!stat $src) {
448         $@ = f_ "stat source file: %S", $!;
449         return 0;
450     }
451     my @src_stat = (stat _)[0..1];
452
453     my @dst_stat;
454     if (stat $dst) {
455         @dst_stat = (stat _)[0..1];
456     } elsif ($! == ENOENT) {
457     } else {
458         $@ = f_ "stat destination file: %S", $!;
459         return 0;
460     }
461
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";
466     } else {
467         $!=0; $?=0;
468         my @cmd = (qw(cp --), $src, "$dst.tmp");
469         debugcmd '+',@cmd;
470         if (system @cmd) {
471             failedcmd_report_cmd undef, @cmd;
472             $@ = failedcmd_waitstatus();
473             $! = -1;
474             return 0;
475         }
476         if (!rename "$dst.tmp", $dst) {
477             $@ = f_ "finally install file after cp: %S", $!;
478             return 0;
479         }
480     }
481     if (!$keeporig) {
482         if (!unlink $src) {
483             $@ = f_ "delete old file after cp: %S", $!;
484             return 0;
485         }
486     }
487     return 1;
488 }
489
490 sub hashfile ($) {
491     my ($fn) = @_;
492     my $h = Digest::SHA->new(256);
493     $h->addfile($fn);
494     return $h->hexdigest();
495 }
496
497 sub git_rev_parse ($) {
498     return cmdoutput qw(git rev-parse), "$_[0]~0";
499 }
500
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)
506 END
507     chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
508 }
509
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;
517     my $chk = sub {
518         my ($gtype, $data) = @_;
519         if ($etype) {
520             $etype = [$etype] unless ref $etype;
521             confess "$objname expected @$etype but is $gtype"
522                 unless grep { $gtype eq $_ } @$etype;
523         }
524         return ($gtype, $data);
525     };
526     if (!$gcf_pid) {
527         my @cmd = qw(git cat-file --batch);
528         debugcmd "GCF|", @cmd;
529         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
530     }
531     printdebug "GCF>| $objname\n";
532     print $gcf_i $objname, "\n" or confess "$!";
533     my $x = <$gcf_o>;
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 ?";
537     my $data;
538     (read $gcf_o, $data, $size) == $size or confess "$objname $!";
539     $x = <$gcf_o>;
540     $x eq "\n" or confess "$objname ($_) $!";
541     return $chk->($type, $data);
542 }
543
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;
551     } else {
552         chomp $branch;
553     }
554     return $branch;
555 }
556
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);
567     }
568     open GFER, "-|", @cmd or confess "$!";
569     debugcmd "|", @cmd;
570     while (<GFER>) {
571         chomp or confess "$_ ?";
572         printdebug "|> ", $_, "\n";
573         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
574         $func->($1,$2,$3,$4);
575     }
576     $!=0; $?=0; close GFER or confess "$pattern $? $!";
577 }
578
579 sub git_get_ref ($) {
580     # => '' if no such ref
581     my ($refname) = @_;
582     local $_ = $refname;
583     s{^refs/}{[r]efs/} or confess "$refname $_ ?";
584     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
585 }
586
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;
596         return unless
597             !defined $objreferring # caller wants them all
598             or $tagobjid eq $objreferring
599             or $refobjid eq $objreferring;
600         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
601     });
602 }
603
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;
608         push @cmd, qw(HEAD);
609         debugcmd "+",@cmd;
610         $!=0; $?=-1; system @cmd;
611         return if !$?;
612         if ($?==256) {
613             fail
614                 $cached
615                 ? __ "git index contains changes (does not match HEAD)"
616                 : __ "working tree is dirty (does not match HEAD)";
617         } else {
618             failedcmd @cmd;
619         }
620     }
621 }
622
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";
629         push @$tried, $tag;
630         return $new_upstream if length $new_upstream;
631     }
632 }
633
634 sub resolve_upstream_version ($$) {
635     my ($new_upstream, $upstream_version) = @_;
636
637     my $used = $new_upstream;
638     if (!defined $new_upstream) {
639         my @tried;
640         $new_upstream = upstream_commitish_search $upstream_version, \@tried;
641         if (!length $new_upstream) {
642             fail f_
643                 "Could not determine appropriate upstream commitish.\n".
644                 " (Tried these tags: %s)\n".
645                 " Check version, and specify upstream commitish explicitly.",
646                 "@tried";
647         }
648         $used = $tried[-1];
649     }
650     $new_upstream = git_rev_parse $new_upstream;
651
652     return ($new_upstream, $used);
653     # used is a human-readable idea of what we found
654 }
655
656 sub is_fast_fwd ($$) {
657     my ($ancestor,$child) = @_;
658     my @cmd = (qw(git merge-base), $ancestor, $child);
659     my $mb = cmdoutput_errok @cmd;
660     if (defined $mb) {
661         return git_rev_parse($mb) eq git_rev_parse($ancestor);
662     } else {
663         $?==256 or failedcmd @cmd;
664         return 0;
665     }
666 }
667
668 sub git_reflog_action_msg ($) {
669     my ($msg) = @_;
670     my $rla = $ENV{GIT_REFLOG_ACTION};
671     $msg = "$rla: $msg" if length $rla;
672     return $msg;
673 }
674
675 sub git_update_ref_cmd {
676     # returns  qw(git update-ref), qw(-m), @_
677     # except that message may be modified to honour GIT_REFLOG_ACTION
678     my $msg = shift @_;
679     $msg = git_reflog_action_msg $msg;
680     return qw(git update-ref -m), $msg, @_;
681 }
682
683 sub rm_subdir_cached ($) {
684     my ($subdir) = @_;
685     runcmd qw(git rm --quiet -rf --cached --ignore-unmatch), $subdir;
686 }
687
688 sub read_tree_subdir ($$) {
689     my ($subdir, $new_tree_object) = @_;
690     rm_subdir_cached $subdir;
691     runcmd qw(git read-tree), "--prefix=$subdir/", $new_tree_object;
692 }
693
694 sub read_tree_debian ($) {
695     my ($treeish) = @_;
696     read_tree_subdir 'debian', "$treeish:debian";
697     rm_subdir_cached 'debian/patches';
698 }
699
700 sub read_tree_upstream ($;$$) {
701     my ($treeish, $keep_patches, $tree_with_debian) = @_;
702     # if $tree_with_debian is supplied, will use that for debian/
703     # otherwise will save and restore it.
704     my $debian =
705         $tree_with_debian ? "$tree_with_debian:debian"
706         : cmdoutput qw(git write-tree --prefix=debian/);
707     runcmd qw(git read-tree), $treeish;
708     read_tree_subdir 'debian', $debian;
709     rm_subdir_cached 'debian/patches' unless $keep_patches;
710 }
711
712 sub changedir ($) {
713     my ($newdir) = @_;
714     printdebug "CD $newdir\n";
715     chdir $newdir or confess "chdir: $newdir: $!";
716 }
717
718 sub git_slurp_config_src ($) {
719     my ($src) = @_;
720     # returns $r such that $r->{KEY}[] = VALUE
721     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
722     debugcmd "|",@cmd;
723
724     local ($debuglevel) = $debuglevel-2;
725     local $/="\0";
726
727     my $r = { };
728     open GITS, "-|", @cmd or confess "$!";
729     while (<GITS>) {
730         chomp or confess;
731         printdebug "=> ", (messagequote $_), "\n";
732         m/\n/ or confess "$_ ?";
733         push @{ $r->{$`} }, $'; #';
734     }
735     $!=0; $?=0;
736     close GITS
737         or ($!==0 && $?==256)
738         or failedcmd @cmd;
739     return $r;
740 }
741
742 sub gdr_ffq_prev_branchinfo ($) {
743     my ($symref) = @_;
744     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
745     # 'status' may be
746     #    branch         message is undef
747     #    weird-symref   } no $symref,
748     #    notbranch      }  no $ffq_prev
749     return ('detached', __ 'detached HEAD') unless defined $symref;
750     return ('weird-symref', __ 'HEAD symref is not to refs/')
751         unless $symref =~ m{^refs/};
752     my $ffq_prev = "refs/$ffq_refprefix/$'";
753     my $gdrlast = "refs/$gdrlast_refprefix/$'";
754     printdebug "ffq_prev_branchinfo branch current $symref\n";
755     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
756 }
757
758 sub parsecontrolfh ($$;$) {
759     my ($fh, $desc, $allowsigned) = @_;
760     our $dpkgcontrolhash_noissigned;
761     my $c;
762     for (;;) {
763         my %opts = ('name' => $desc);
764         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
765         $c = Dpkg::Control::Hash->new(%opts);
766         $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
767         last if $allowsigned;
768         last if $dpkgcontrolhash_noissigned;
769         my $issigned= $c->get_option('is_pgp_signed');
770         if (!defined $issigned) {
771             $dpkgcontrolhash_noissigned= 1;
772             seek $fh, 0,0 or confess "seek $desc: $!";
773         } elsif ($issigned) {
774             fail f_
775                 "control file %s is (already) PGP-signed. ".
776                 " Note that dgit push needs to modify the .dsc and then".
777                 " do the signature itself",
778                 $desc;
779         } else {
780             last;
781         }
782     }
783     return $c;
784 }
785
786 sub parsecontrol {
787     my ($file, $desc, $allowsigned) = @_;
788     my $fh = new IO::Handle;
789     open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
790     my $c = parsecontrolfh($fh,$desc,$allowsigned);
791     $fh->error and confess "$!";
792     close $fh;
793     return $c;
794 }
795
796 sub parsechangelog {
797     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
798     my $p = new IO::Handle;
799     my @cmd = (qw(dpkg-parsechangelog), @_);
800     open $p, '-|', @cmd or confess "$!";
801     $c->parse($p);
802     $?=0; $!=0; close $p or failedcmd @cmd;
803     return $c;
804 }
805
806 sub getfield ($$) {
807     my ($dctrl,$field) = @_;
808     my $v = $dctrl->{$field};
809     return $v if defined $v;
810     fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
811 }
812
813 sub parsechangelog_loop ($$$) {
814     my ($clogcmd, $descbase, $fn) = @_;
815     # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
816     # calls $fn->($thisstanza, $desc);
817     debugcmd "|",@$clogcmd;
818     open CLOGS, "-|", @$clogcmd or confess "$!";
819     for (;;) {
820         my $stanzatext = do { local $/=""; <CLOGS>; };
821         printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
822         last if !defined $stanzatext;
823
824         my $desc = "$descbase, entry no.$.";
825         open my $stanzafh, "<", \$stanzatext or confess;
826         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
827
828         $fn->($thisstanza, $desc);
829     }
830     confess "$!" if CLOGS->error;
831     close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
832 }       
833
834 sub make_commit ($$) {
835     my ($parents, $message_paras) = @_;
836     my $tree = cmdoutput qw(git write-tree);
837     my @cmd = (qw(git commit-tree), $tree);
838     push @cmd, qw(-p), $_ foreach @$parents;
839     push @cmd, qw(-m), $_ foreach @$message_paras;
840     return cmdoutput @cmd;
841 }
842
843 sub hash_commit_text ($) {
844     my ($text) = @_;
845     my ($out, $in);
846     my @cmd = (qw(git hash-object -w -t commit --stdin));
847     debugcmd "|",@cmd;
848     print Dumper($text) if $debuglevel > 1;
849     my $child = open2($out, $in, @cmd) or confess "$!";
850     my $h;
851     eval {
852         print $in $text or confess "$!";
853         close $in or confess "$!";
854         $h = <$out>;
855         $h =~ m/^\w+$/ or confess;
856         $h = $&;
857         printdebug "=> $h\n";
858     };
859     close $out;
860     waitpid $child, 0 == $child or confess "$child $!";
861     $? and failedcmd @cmd;
862     return $h;
863 }
864
865 sub reflog_cache_insert ($$$) {
866     my ($ref, $cachekey, $value) = @_;
867     # you must call this in $maindir
868     # you must have called record_maindir
869
870     # When we no longer need to support squeeze, use --create-reflog
871     # instead of this:
872     my $parent = $ref; $parent =~ s{/[^/]+$}{};
873     ensuredir "$maindir_gitcommon/logs/$parent";
874     my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
875       or confess "$!";
876
877     my $oldcache = git_get_ref $ref;
878
879     if ($oldcache eq $value) {
880         my $tree = cmdoutput qw(git rev-parse), "$value:";
881         # git update-ref doesn't always update, in this case.  *sigh*
882         my $authline = (ucfirst _us()).
883             ' <'._us().'@example.com> 1000000000 +0000';
884         my $dummy = hash_commit_text <<ENDU.(__ <<END);
885 tree $tree
886 parent $value
887 author $authline
888 committer $authline
889
890 ENDU
891 Dummy commit - do not use
892 END
893         runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
894     }
895     runcmd qw(git update-ref -m), $cachekey, $ref, $value;
896 }
897
898 sub reflog_cache_lookup ($$) {
899     my ($ref, $cachekey) = @_;
900     # you may call this in $maindir or in a playtree
901     # you must have called record_maindir
902     my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
903     debugcmd "|(probably)",@cmd;
904     my $child = open GC, "-|";  defined $child or confess "$!";
905     if (!$child) {
906         chdir $maindir or confess "$!";
907         if (!stat "$maindir_gitcommon/logs/$ref") {
908             $! == ENOENT or confess "$!";
909             printdebug ">(no reflog)\n";
910             finish 0;
911         }
912         exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
913     }
914     while (<GC>) {
915         chomp;
916         printdebug ">| ", $_, "\n" if $debuglevel > 1;
917         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
918         close GC;
919         return $1;
920     }
921     confess "$!" if GC->error;
922     failedcmd unless close GC;
923     return undef;
924 }
925
926 # ========== playground handling ==========
927
928 # terminology:
929 #
930 #   $maindir      user's git working tree
931 #   playground    area in .git/ where we can make files, unpack, etc. etc.
932 #   playtree      git working tree sharing object store with the user's
933 #                 inside playground, or identical to it
934 #
935 # other globals
936 #
937 #   $local_git_cfg    hash of arrays of values: git config from $maindir
938 #
939 # expected calling pattern
940 #
941 #  firstly
942 #
943 #    [record_maindir]
944 #      must be run in directory containing .git
945 #      assigns to $maindir if not already set
946 #      also calls git_slurp_config_src to record git config
947 #        in $local_git_cfg, unless it's already set
948 #
949 #    fresh_playground SUBDIR_PATH_COMPONENTS
950 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
951 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
952 #      calls record_maindir
953 #      sets up a new playground (destroying any old one)
954 #      returns playground pathname
955 #      caller may call multiple times with different subdir paths
956 #       createing different playgrounds
957 #
958 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
959 #      like fresh_playground except:
960 #      merely ensures the directory exists; does not delete an existing one
961 #
962 #  then can use
963 #
964 #    changedir playground
965 #    changedir $maindir
966 #
967 #    playtree_setup $local_git_cfg
968 #            # ^ call in some (perhaps trivial) subdir of playground
969 #
970 #    rmtree playground
971
972 # ----- maindir -----
973
974 our $local_git_cfg;
975
976 sub record_maindir () {
977     if (!defined $maindir) {
978         $maindir = must_getcwd();
979         if (!stat "$maindir/.git") {
980             fail f_ "cannot stat %s/.git: %s", $maindir, $!;
981         }
982         if (-d _) {
983             # we fall back to this in case we have a pre-worktree
984             # git, which may not know git rev-parse --git-common-dir
985             $maindir_gitdir    = "$maindir/.git";
986             $maindir_gitcommon = "$maindir/.git";
987         } else {
988             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
989             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
990         }
991     }
992     $local_git_cfg //= git_slurp_config_src 'local';
993 }
994
995 # ----- playgrounds -----
996
997 sub ensure_a_playground_parent ($) {
998     my ($spc) = @_;
999     record_maindir();
1000     $spc = "$maindir_gitdir/$spc";
1001     my $parent = dirname $spc;
1002     mkdir $parent or $!==EEXIST or fail f_
1003         "failed to mkdir playground parent %s: %s", $parent, $!;
1004     return $spc;
1005 }    
1006
1007 sub ensure_a_playground ($) {
1008     my ($spc) = @_;
1009     $spc = ensure_a_playground_parent $spc;
1010     mkdir $spc or $!==EEXIST or fail f_
1011         "failed to mkdir a playground %s: %s", $spc, $!;
1012     return $spc;
1013 }    
1014
1015 sub fresh_playground ($) {
1016     my ($spc) = @_;
1017     $spc = ensure_a_playground_parent $spc;
1018     rmtree $spc;
1019     mkdir $spc or fail f_
1020         "failed to mkdir the playground %s: %s", $spc, $!;
1021     return $spc;
1022 }
1023
1024 # ----- playtrees -----
1025
1026 sub playtree_setup (;$) {
1027     my ($t_local_git_cfg) = @_;
1028     $t_local_git_cfg //= $local_git_cfg;
1029     # for use in the playtree
1030     # $maindir must be set, eg by calling record_maindir or fresh_playground
1031     runcmd qw(git init -q);
1032     runcmd qw(git config gc.auto 0);
1033     foreach my $copy (qw(user.email user.name user.useConfigOnly
1034                          core.sharedRepository
1035                          core.compression core.looseCompression
1036                          core.bigFileThreshold core.fsyncObjectFiles)) {
1037         my $v = $t_local_git_cfg->{$copy};
1038         next unless $v;
1039         runcmd qw(git config), $copy, $_ foreach @$v;
1040     }
1041     # this is confusing: we have
1042     #   .                   playtree, not a worktree, has .git/, our cwd
1043     #   $maindir            might be a worktree so
1044     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
1045     #   $maindir_gitcommon  the shared stuff, including .objects
1046     rmtree('.git/objects');
1047     symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1048     ensuredir '.git/info';
1049     open GA, "> .git/info/attributes" or confess "$!";
1050     print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1051     close GA or confess "$!";
1052 }
1053
1054 1;