chiark / gitweb /
912a524567a735e27b82aef3957d726248e9f6ae
[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                       make_commit_text
64                       reflog_cache_insert reflog_cache_lookup
65                       $package_re $component_re $deliberately_re
66                       $distro_re $versiontag_re $series_filename_re
67                       $orig_f_comp_re $orig_f_sig_re $orig_f_tail_re
68                       $extra_orig_namepart_re
69                       $git_null_obj
70                       $branchprefix
71                       $ffq_refprefix $gdrlast_refprefix
72                       initdebug enabledebug enabledebuglevel
73                       printdebug debugcmd
74                       $printdebug_when_debuglevel $debugcmd_when_debuglevel
75                       $debugprefix *debuglevel *DEBUG
76                       shellquote printcmd messagequote
77                       $negate_harmful_gitattrs
78                       changedir git_slurp_config_src
79                       gdr_ffq_prev_branchinfo
80                       parsecontrolfh parsecontrol parsechangelog
81                       getfield parsechangelog_loop
82                       playtree_setup);
83     # implicitly uses $main::us
84     %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
85                      playground => [qw(record_maindir $maindir $local_git_cfg
86                                        $maindir_gitdir $maindir_gitcommon
87                                        fresh_playground
88                                        ensure_a_playground)]);
89     @EXPORT_OK   = ( @{ $EXPORT_TAGS{policyflags} },
90                      @{ $EXPORT_TAGS{playground} } );
91 }
92
93 our @EXPORT_OK;
94
95 our $package_re = '[0-9a-z][-+.0-9a-z]*';
96 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
97 our $deliberately_re = "(?:TEST-)?$package_re";
98 our $distro_re = $component_re;
99 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
100 our $branchprefix = 'dgit';
101 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
102 our $extra_orig_namepart_re = qr{[-0-9a-zA-Z]+};
103 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
104 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
105 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
106 our $git_null_obj = '0' x 40;
107 our $ffq_refprefix = 'ffq-prev';
108 our $gdrlast_refprefix = 'debrebase-last';
109 our $printdebug_when_debuglevel = 1;
110 our $debugcmd_when_debuglevel = 1;
111
112 # these three all go together, only valid after record_maindir
113 our $maindir;
114 our $maindir_gitdir;
115 our $maindir_gitcommon;
116
117 # policy hook exit status bits
118 # see dgit-repos-server head comment for documentation
119 # 1 is reserved in case something fails with `exit 1' and to spot
120 # dynamic loader, runtime, etc., failures, which report 127 or 255
121 sub NOFFCHECK () { return 0x2; }
122 sub FRESHREPO () { return 0x4; }
123 sub NOCOMMITCHECK () { return 0x8; }
124
125 our $debugprefix;
126 our $debuglevel = 0;
127
128 our $negate_harmful_gitattrs =
129     "-text -eol -crlf -ident -filter -working-tree-encoding";
130     # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
131
132 our $forkcheck_mainprocess;
133
134 sub forkcheck_setup () {
135     $forkcheck_mainprocess = $$;
136 }
137
138 sub forkcheck_mainprocess () {
139     # You must have called forkcheck_setup or setup_sigwarn already
140     getppid != $forkcheck_mainprocess;
141 }
142
143 sub setup_sigwarn () {
144     forkcheck_setup();
145     $SIG{__WARN__} = sub { 
146         confess $_[0] if forkcheck_mainprocess;
147     };
148 }
149
150 sub initdebug ($) { 
151     ($debugprefix) = @_;
152     open DEBUG, ">/dev/null" or confess "$!";
153 }
154
155 sub enabledebug () {
156     open DEBUG, ">&STDERR" or confess "$!";
157     DEBUG->autoflush(1);
158     $debuglevel ||= 1;
159 }
160     
161 sub enabledebuglevel ($) {
162     my ($newlevel) = @_; # may be undef (eg from env var)
163     confess if $debuglevel;
164     $newlevel //= 0;
165     $newlevel += 0;
166     return unless $newlevel;
167     $debuglevel = $newlevel;
168     enabledebug();
169 }
170     
171 sub printdebug {
172     # Prints a prefix, and @_, to DEBUG.  @_ should normally contain
173     # a trailing \n.
174
175     # With no (or only empty) arguments just prints the prefix and
176     # leaves the caller to do more with DEBUG.  The caller should make
177     # sure then to call printdebug with something ending in "\n" to
178     # get the prefix right in subsequent calls.
179
180     return unless $debuglevel >= $printdebug_when_debuglevel;
181     our $printdebug_noprefix;
182     print DEBUG $debugprefix unless $printdebug_noprefix;
183     pop @_ while @_ and !length $_[-1];
184     return unless @_;
185     print DEBUG @_ or confess "$!";
186     $printdebug_noprefix = $_[-1] !~ m{\n$};
187 }
188
189 sub messagequote ($) {
190     local ($_) = @_;
191     s{\\}{\\\\}g;
192     s{\n}{\\n}g;
193     s{\x08}{\\b}g;
194     s{\t}{\\t}g;
195     s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
196     $_;
197 }
198
199 sub shellquote {
200     my @out;
201     local $_;
202     defined or confess __ 'internal error' foreach @_;
203     foreach my $a (@_) {
204         $_ = $a;
205         if (!length || m{[^-=_./:0-9a-z]}i) {
206             s{['\\]}{'\\$&'}g;
207             push @out, "'$_'";
208         } else {
209             push @out, $_;
210         }
211     }
212     return join ' ', @out;
213 }
214
215 sub printcmd {
216     my $fh = shift @_;
217     my $intro = shift @_;
218     print $fh $intro," " or confess "$!";
219     print $fh shellquote @_ or confess "$!";
220     print $fh "\n" or confess "$!";
221 }
222
223 sub debugcmd {
224     my $extraprefix = shift @_;
225     printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
226         if $debuglevel >= $debugcmd_when_debuglevel;
227 }
228
229 sub dep14_version_mangle ($) {
230     my ($v) = @_;
231     # DEP-14 patch proposed 2016-11-09  "Version Mangling"
232     $v =~ y/~:/_%/;
233     $v =~ s/\.(?=\.|$|lock$)/.#/g;
234     return $v;
235 }
236
237 sub debiantag_new ($$) { 
238     my ($v,$distro) = @_;
239     return "archive/$distro/".dep14_version_mangle $v;
240 }
241
242 sub debiantag_maintview ($$) { 
243     my ($v,$distro) = @_;
244     return "$distro/".dep14_version_mangle $v;
245 }
246
247 sub debiantags ($$) {
248     my ($version,$distro) = @_;
249     map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_maintview);
250 }
251
252 sub stripepoch ($) {
253     my ($vsn) = @_;
254     $vsn =~ s/^\d+\://;
255     return $vsn;
256 }
257
258 sub upstreamversion ($) {
259     my ($vsn) = @_;
260     $vsn =~ s/-[^-]+$//;
261     return $vsn;
262 }
263
264 sub source_file_leafname ($$$) {
265     my ($package,$vsn,$sfx) = @_;
266     return "${package}_".(stripepoch $vsn).$sfx
267 }
268
269 sub is_orig_file_of_p_v ($$$) {
270     my ($f, $package, $upstreamvsn) = @_;
271     my $base = source_file_leafname $package, $upstreamvsn, '';
272     return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
273     return 1;
274 }
275
276 sub server_branch ($) { return "$branchprefix/$_[0]"; }
277 sub server_ref ($) { return "refs/".server_branch($_[0]); }
278
279 sub stat_exists ($) {
280     my ($f) = @_;
281     return 1 if stat $f;
282     return 0 if $!==&ENOENT;
283     confess "stat $f: $!";
284 }
285
286 sub _us () {
287     $::us // ($0 =~ m#[^/]*$#, $&);
288 }
289
290 sub failmsg {
291     my $s = f_ "error: %s\n", "@_";
292     $s =~ s/\n\n$/\n/g;
293     my $prefix = _us().": ";
294     $s =~ s/^/$prefix/gm;
295     return "\n".$s;
296 }
297
298 sub fail {
299     die failmsg @_;
300 }
301
302 sub ensuredir ($) {
303     my ($dir) = @_; # does not create parents
304     return if mkdir $dir;
305     return if $! == EEXIST;
306     confess "mkdir $dir: $!";
307 }
308
309 sub must_getcwd () {
310     my $d = getcwd();
311     defined $d or fail f_ "getcwd failed: %s\n", $!;
312     return $d;
313 }
314
315 sub executable_on_path ($) {
316     my ($program) = @_;
317     return 1 if $program =~ m{/};
318     my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
319     foreach my $pe (@path) {
320         my $here = "$pe/$program";
321         return $here if stat_exists $here && -x _;
322     }
323     return undef;
324 }
325
326 our @signames = split / /, $Config{sig_name};
327
328 sub waitstatusmsg () {
329     if (!$?) {
330         return __ "terminated, reporting successful completion";
331     } elsif (!($? & 255)) {
332         return f_ "failed with error exit status %s", WEXITSTATUS($?);
333     } elsif (WIFSIGNALED($?)) {
334         my $signum=WTERMSIG($?);
335         return f_ "died due to fatal signal %s",
336             ($signames[$signum] // "number $signum").
337             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
338     } else {
339         return f_ "failed with unknown wait status %s", $?;
340     }
341 }
342
343 sub failedcmd_report_cmd {
344     my $intro = shift @_;
345     $intro //= __ "failed command";
346     { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
347 }
348
349 sub failedcmd_waitstatus {
350     if ($? < 0) {
351         return f_ "failed to fork/exec: %s", $!;
352     } elsif ($?) {
353         return f_ "subprocess %s", waitstatusmsg();
354     } else {
355         return __ "subprocess produced invalid output";
356     }
357 }
358
359 sub failedcmd {
360     # Expects $!,$? as set by close - see below.
361     # To use with system(), set $?=-1 first.
362     #
363     # Actual behaviour of perl operations:
364     #   success              $!==0       $?==0       close of piped open
365     #   program failed       $!==0       $? >0       close of piped open
366     #   syscall failure      $! >0       $?=-1       close of piped open
367     #   failure              $! >0       unchanged   close of something else
368     #   success              trashed     $?==0       system
369     #   program failed       trashed     $? >0       system
370     #   syscall failure      $! >0       unchanged   system
371     failedcmd_report_cmd undef, @_;
372     fail failedcmd_waitstatus();
373 }
374
375 sub runcmd {
376     debugcmd "+",@_;
377     $!=0; $?=-1;
378     failedcmd @_ if system @_;
379 }
380
381 sub shell_cmd {
382     my ($first_shell, @cmd) = @_;
383     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
384 }
385
386 sub cmdoutput_errok {
387     confess Dumper(\@_)." ?" if grep { !defined } @_;
388     local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
389     debugcmd "|",@_;
390     open P, "-|", @_ or confess "$_[0] $!";
391     my $d;
392     $!=0; $?=0;
393     { local $/ = undef; $d = <P>; }
394     confess "$!" if P->error;
395     if (!close P) { printdebug "=>!$?\n"; return undef; }
396     chomp $d;
397     if ($debuglevel > 0) {
398         $d =~ m/^.*/;
399         my $dd = $&;
400         my $more = (length $' ? '...' : ''); #');
401         $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
402         printdebug "=> \`$dd'",$more,"\n";
403     }
404     return $d;
405 }
406
407 sub cmdoutput {
408     my $d = cmdoutput_errok @_;
409     defined $d or failedcmd @_;
410     return $d;
411 }
412
413 sub link_ltarget ($$) {
414     my ($old,$new) = @_;
415     lstat $old or return undef;
416     if (-l _) {
417         $old = cmdoutput qw(realpath  --), $old;
418     }
419     my $r = link $old, $new;
420     $r = symlink $old, $new if !$r && $!==EXDEV;
421     $r or fail "(sym)link $old $new: $!\n";
422 }
423
424 sub rename_link_xf ($$$) {
425     # renames/moves or links/copies $src to $dst,
426     # even if $dst is on a different fs
427     # (May use the filename "$dst.tmp".);
428     # On success, returns true.
429     # On failure, returns false and sets
430     #    $@ to a reason message
431     #    $! to an errno value, or -1 if not known
432     # having possibly printed something about mv to stderr.
433     # Not safe to use without $keeporig if $dst might be a symlink
434     # to $src, as it might delete $src leaving $dst invalid.
435     my ($keeporig,$src,$dst) = @_;
436     if ($keeporig
437         ? link   $src, $dst
438         : rename $src, $dst) {
439         return 1;
440     }
441     if ($! != EXDEV) {
442         $@ = "$!";
443         return 0;
444     }
445     if (!stat $src) {
446         $@ = f_ "stat source file: %S", $!;
447         return 0;
448     }
449     my @src_stat = (stat _)[0..1];
450
451     my @dst_stat;
452     if (stat $dst) {
453         @dst_stat = (stat _)[0..1];
454     } elsif ($! == ENOENT) {
455     } else {
456         $@ = f_ "stat destination file: %S", $!;
457         return 0;
458     }
459
460     if ("@src_stat" eq "@dst_stat") {
461         # (Symlinks to) the same file.  No need for a copy but
462         # we may need to delete the original.
463         printdebug "rename_link_xf $keeporig $src $dst EXDEV but same\n";
464     } else {
465         $!=0; $?=0;
466         my @cmd = (qw(cp --), $src, "$dst.tmp");
467         debugcmd '+',@cmd;
468         if (system @cmd) {
469             failedcmd_report_cmd undef, @cmd;
470             $@ = failedcmd_waitstatus();
471             $! = -1;
472             return 0;
473         }
474         if (!rename "$dst.tmp", $dst) {
475             $@ = f_ "finally install file after cp: %S", $!;
476             return 0;
477         }
478     }
479     if (!$keeporig) {
480         if (!unlink $src) {
481             $@ = f_ "delete old file after cp: %S", $!;
482             return 0;
483         }
484     }
485     return 1;
486 }
487
488 sub hashfile ($) {
489     my ($fn) = @_;
490     my $h = Digest::SHA->new(256);
491     $h->addfile($fn);
492     return $h->hexdigest();
493 }
494
495 sub git_rev_parse ($) {
496     return cmdoutput qw(git rev-parse), "$_[0]~0";
497 }
498
499 sub changedir_git_toplevel () {
500     my $toplevel = cmdoutput qw(git rev-parse --show-toplevel);
501     length $toplevel or fail __ <<END;
502 not in a git working tree?
503 (git rev-parse --show-toplevel produced no output)
504 END
505     chdir $toplevel or fail f_ "chdir toplevel %s: %s\n", $toplevel, $!;
506 }
507
508 sub git_cat_file ($;$) {
509     my ($objname, $etype) = @_;
510     # => ($type, $data) or ('missing', undef)
511     # in scalar context, just the data
512     # if $etype defined, dies unless type is $etype or in @$etype
513     our ($gcf_pid, $gcf_i, $gcf_o);
514     local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
515     my $chk = sub {
516         my ($gtype, $data) = @_;
517         if ($etype) {
518             $etype = [$etype] unless ref $etype;
519             confess "$objname expected @$etype but is $gtype"
520                 unless grep { $gtype eq $_ } @$etype;
521         }
522         return ($gtype, $data);
523     };
524     if (!$gcf_pid) {
525         my @cmd = qw(git cat-file --batch);
526         debugcmd "GCF|", @cmd;
527         $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or confess "$!";
528     }
529     printdebug "GCF>| $objname\n";
530     print $gcf_i $objname, "\n" or confess "$!";
531     my $x = <$gcf_o>;
532     printdebug "GCF<| ", $x;
533     if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
534     my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or confess "$objname ?";
535     my $data;
536     (read $gcf_o, $data, $size) == $size or confess "$objname $!";
537     $x = <$gcf_o>;
538     $x eq "\n" or confess "$objname ($_) $!";
539     return $chk->($type, $data);
540 }
541
542 sub git_get_symref (;$) {
543     my ($symref) = @_;  $symref //= 'HEAD';
544     # => undef if not a symref, otherwise refs/...
545     my @cmd = (qw(git symbolic-ref -q HEAD));
546     my $branch = cmdoutput_errok @cmd;
547     if (!defined $branch) {
548         $?==256 or failedcmd @cmd;
549     } else {
550         chomp $branch;
551     }
552     return $branch;
553 }
554
555 sub git_for_each_ref ($$;$) {
556     my ($pattern,$func,$gitdir) = @_;
557     # calls $func->($objid,$objtype,$fullrefname,$reftail);
558     # $reftail is RHS of ref after refs/[^/]+/
559     # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
560     # $pattern may be an array ref to mean multiple patterns
561     $pattern = [ $pattern ] unless ref $pattern;
562     my @cmd = (qw(git for-each-ref), @$pattern);
563     if (defined $gitdir) {
564         @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
565     }
566     open GFER, "-|", @cmd or confess "$!";
567     debugcmd "|", @cmd;
568     while (<GFER>) {
569         chomp or confess "$_ ?";
570         printdebug "|> ", $_, "\n";
571         m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
572         $func->($1,$2,$3,$4);
573     }
574     $!=0; $?=0; close GFER or confess "$pattern $? $!";
575 }
576
577 sub git_get_ref ($) {
578     # => '' if no such ref
579     my ($refname) = @_;
580     local $_ = $refname;
581     s{^refs/}{[r]efs/} or confess "$refname $_ ?";
582     return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
583 }
584
585 sub git_for_each_tag_referring ($$) {
586     my ($objreferring, $func) = @_;
587     # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
588     printdebug "git_for_each_tag_referring ",
589         ($objreferring // 'UNDEF'),"\n";
590     git_for_each_ref('refs/tags', sub {
591         my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
592         return unless $objtype eq 'tag';
593         my $refobjid = git_rev_parse $tagobjid;
594         return unless
595             !defined $objreferring # caller wants them all
596             or $tagobjid eq $objreferring
597             or $refobjid eq $objreferring;
598         $func->($tagobjid,$refobjid,$fullrefname,$tagname);
599     });
600 }
601
602 sub git_check_unmodified () {
603     foreach my $cached (qw(0 1)) {
604         my @cmd = qw(git diff --quiet);
605         push @cmd, qw(--cached) if $cached;
606         push @cmd, qw(HEAD);
607         debugcmd "+",@cmd;
608         $!=0; $?=-1; system @cmd;
609         return if !$?;
610         if ($?==256) {
611             fail
612                 $cached
613                 ? __ "git index contains changes (does not match HEAD)"
614                 : __ "working tree is dirty (does not match HEAD)";
615         } else {
616             failedcmd @cmd;
617         }
618     }
619 }
620
621 sub upstream_commitish_search ($$) {
622     my ($upstream_version, $tried) = @_;
623     # todo: at some point maybe use git-deborig to do this
624     foreach my $tagpfx ('', 'v', 'upstream/') {
625         my $tag = $tagpfx.(dep14_version_mangle $upstream_version);
626         my $new_upstream = git_get_ref "refs/tags/$tag";
627         push @$tried, $tag;
628         return $new_upstream if length $new_upstream;
629     }
630 }
631
632 sub resolve_upstream_version ($$) {
633     my ($new_upstream, $upstream_version) = @_;
634
635     my $used = $new_upstream;
636     if (!defined $new_upstream) {
637         my @tried;
638         $new_upstream = upstream_commitish_search $upstream_version, \@tried;
639         if (!length $new_upstream) {
640             fail f_
641                 "Could not determine appropriate upstream commitish.\n".
642                 " (Tried these tags: %s)\n".
643                 " Check version, and specify upstream commitish explicitly.",
644                 "@tried";
645         }
646         $used = $tried[-1];
647     }
648     $new_upstream = git_rev_parse $new_upstream;
649
650     return ($new_upstream, $used);
651     # used is a human-readable idea of what we found
652 }
653
654 sub is_fast_fwd ($$) {
655     my ($ancestor,$child) = @_;
656     my @cmd = (qw(git merge-base), $ancestor, $child);
657     my $mb = cmdoutput_errok @cmd;
658     if (defined $mb) {
659         return git_rev_parse($mb) eq git_rev_parse($ancestor);
660     } else {
661         $?==256 or failedcmd @cmd;
662         return 0;
663     }
664 }
665
666 sub git_reflog_action_msg ($) {
667     my ($msg) = @_;
668     my $rla = $ENV{GIT_REFLOG_ACTION};
669     $msg = "$rla: $msg" if length $rla;
670     return $msg;
671 }
672
673 sub git_update_ref_cmd {
674     # returns  qw(git update-ref), qw(-m), @_
675     # except that message may be modified to honour GIT_REFLOG_ACTION
676     my $msg = shift @_;
677     $msg = git_reflog_action_msg $msg;
678     return qw(git update-ref -m), $msg, @_;
679 }
680
681 sub changedir ($) {
682     my ($newdir) = @_;
683     printdebug "CD $newdir\n";
684     chdir $newdir or confess "chdir: $newdir: $!";
685 }
686
687 sub git_slurp_config_src ($) {
688     my ($src) = @_;
689     # returns $r such that $r->{KEY}[] = VALUE
690     my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
691     debugcmd "|",@cmd;
692
693     local ($debuglevel) = $debuglevel-2;
694     local $/="\0";
695
696     my $r = { };
697     open GITS, "-|", @cmd or confess "$!";
698     while (<GITS>) {
699         chomp or confess;
700         printdebug "=> ", (messagequote $_), "\n";
701         m/\n/ or confess "$_ ?";
702         push @{ $r->{$`} }, $'; #';
703     }
704     $!=0; $?=0;
705     close GITS
706         or ($!==0 && $?==256)
707         or failedcmd @cmd;
708     return $r;
709 }
710
711 sub gdr_ffq_prev_branchinfo ($) {
712     my ($symref) = @_;
713     # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
714     # 'status' may be
715     #    branch         message is undef
716     #    weird-symref   } no $symref,
717     #    notbranch      }  no $ffq_prev
718     return ('detached', __ 'detached HEAD') unless defined $symref;
719     return ('weird-symref', __ 'HEAD symref is not to refs/')
720         unless $symref =~ m{^refs/};
721     my $ffq_prev = "refs/$ffq_refprefix/$'";
722     my $gdrlast = "refs/$gdrlast_refprefix/$'";
723     printdebug "ffq_prev_branchinfo branch current $symref\n";
724     return ('branch', undef, $symref, $ffq_prev, $gdrlast);
725 }
726
727 sub parsecontrolfh ($$;$) {
728     my ($fh, $desc, $allowsigned) = @_;
729     our $dpkgcontrolhash_noissigned;
730     my $c;
731     for (;;) {
732         my %opts = ('name' => $desc);
733         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
734         $c = Dpkg::Control::Hash->new(%opts);
735         $c->parse($fh,$desc) or fail f_ "parsing of %s failed", $desc;
736         last if $allowsigned;
737         last if $dpkgcontrolhash_noissigned;
738         my $issigned= $c->get_option('is_pgp_signed');
739         if (!defined $issigned) {
740             $dpkgcontrolhash_noissigned= 1;
741             seek $fh, 0,0 or confess "seek $desc: $!";
742         } elsif ($issigned) {
743             fail f_
744                 "control file %s is (already) PGP-signed. ".
745                 " Note that dgit push needs to modify the .dsc and then".
746                 " do the signature itself",
747                 $desc;
748         } else {
749             last;
750         }
751     }
752     return $c;
753 }
754
755 sub parsecontrol {
756     my ($file, $desc, $allowsigned) = @_;
757     my $fh = new IO::Handle;
758     open $fh, '<', $file or fail f_ "open %s (%s): %s", $file, $desc, $!;
759     my $c = parsecontrolfh($fh,$desc,$allowsigned);
760     $fh->error and confess "$!";
761     close $fh;
762     return $c;
763 }
764
765 sub parsechangelog {
766     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
767     my $p = new IO::Handle;
768     my @cmd = (qw(dpkg-parsechangelog), @_);
769     open $p, '-|', @cmd or confess "$!";
770     $c->parse($p);
771     $?=0; $!=0; close $p or failedcmd @cmd;
772     return $c;
773 }
774
775 sub getfield ($$) {
776     my ($dctrl,$field) = @_;
777     my $v = $dctrl->{$field};
778     return $v if defined $v;
779     fail f_ "missing field %s in %s", $field, $dctrl->get_option('name');
780 }
781
782 sub parsechangelog_loop ($$$) {
783     my ($clogcmd, $descbase, $fn) = @_;
784     # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
785     # calls $fn->($thisstanza, $desc);
786     debugcmd "|",@$clogcmd;
787     open CLOGS, "-|", @$clogcmd or confess "$!";
788     for (;;) {
789         my $stanzatext = do { local $/=""; <CLOGS>; };
790         printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
791         last if !defined $stanzatext;
792
793         my $desc = "$descbase, entry no.$.";
794         open my $stanzafh, "<", \$stanzatext or confess;
795         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
796
797         $fn->($thisstanza, $desc);
798     }
799     confess "$!" if CLOGS->error;
800     close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
801 }       
802
803 sub make_commit_text ($) {
804     my ($text) = @_;
805     my ($out, $in);
806     my @cmd = (qw(git hash-object -w -t commit --stdin));
807     debugcmd "|",@cmd;
808     print Dumper($text) if $debuglevel > 1;
809     my $child = open2($out, $in, @cmd) or confess "$!";
810     my $h;
811     eval {
812         print $in $text or confess "$!";
813         close $in or confess "$!";
814         $h = <$out>;
815         $h =~ m/^\w+$/ or confess;
816         $h = $&;
817         printdebug "=> $h\n";
818     };
819     close $out;
820     waitpid $child, 0 == $child or confess "$child $!";
821     $? and failedcmd @cmd;
822     return $h;
823 }
824
825 sub reflog_cache_insert ($$$) {
826     my ($ref, $cachekey, $value) = @_;
827     # you must call this in $maindir
828     # you must have called record_maindir
829
830     # When we no longer need to support squeeze, use --create-reflog
831     # instead of this:
832     my $parent = $ref; $parent =~ s{/[^/]+$}{};
833     ensuredir "$maindir_gitcommon/logs/$parent";
834     my $makelogfh = new IO::File "$maindir_gitcommon/logs/$ref", '>>'
835       or confess "$!";
836
837     my $oldcache = git_get_ref $ref;
838
839     if ($oldcache eq $value) {
840         my $tree = cmdoutput qw(git rev-parse), "$value:";
841         # git update-ref doesn't always update, in this case.  *sigh*
842         my $authline = (ucfirst _us()).
843             ' <'._us().'@example.com> 1000000000 +0000';
844         my $dummy = make_commit_text <<ENDU.(__ <<END);
845 tree $tree
846 parent $value
847 author $authline
848 committer $authline
849
850 ENDU
851 Dummy commit - do not use
852 END
853         runcmd qw(git update-ref -m), _us()." - dummy", $ref, $dummy;
854     }
855     runcmd qw(git update-ref -m), $cachekey, $ref, $value;
856 }
857
858 sub reflog_cache_lookup ($$) {
859     my ($ref, $cachekey) = @_;
860     # you may call this in $maindir or in a playtree
861     # you must have called record_maindir
862     my @cmd = (qw(git log -g), '--pretty=format:%H %gs', $ref);
863     debugcmd "|(probably)",@cmd;
864     my $child = open GC, "-|";  defined $child or confess "$!";
865     if (!$child) {
866         chdir $maindir or confess "$!";
867         if (!stat "$maindir_gitcommon/logs/$ref") {
868             $! == ENOENT or confess "$!";
869             printdebug ">(no reflog)\n";
870             finish 0;
871         }
872         exec @cmd; die f_ "exec %s: %s\n", $cmd[0], $!;
873     }
874     while (<GC>) {
875         chomp;
876         printdebug ">| ", $_, "\n" if $debuglevel > 1;
877         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $cachekey;
878         close GC;
879         return $1;
880     }
881     confess "$!" if GC->error;
882     failedcmd unless close GC;
883     return undef;
884 }
885
886 # ========== playground handling ==========
887
888 # terminology:
889 #
890 #   $maindir      user's git working tree
891 #   playground    area in .git/ where we can make files, unpack, etc. etc.
892 #   playtree      git working tree sharing object store with the user's
893 #                 inside playground, or identical to it
894 #
895 # other globals
896 #
897 #   $local_git_cfg    hash of arrays of values: git config from $maindir
898 #
899 # expected calling pattern
900 #
901 #  firstly
902 #
903 #    [record_maindir]
904 #      must be run in directory containing .git
905 #      assigns to $maindir if not already set
906 #      also calls git_slurp_config_src to record git config
907 #        in $local_git_cfg, unless it's already set
908 #
909 #    fresh_playground SUBDIR_PATH_COMPONENTS
910 #      e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
911 #      default SUBDIR_PATH_COMPONENTS is playground_subdir
912 #      calls record_maindir
913 #      sets up a new playground (destroying any old one)
914 #      returns playground pathname
915 #      caller may call multiple times with different subdir paths
916 #       createing different playgrounds
917 #
918 #    ensure_a_playground SUBDIR_PATH_COMPONENTS
919 #      like fresh_playground except:
920 #      merely ensures the directory exists; does not delete an existing one
921 #
922 #  then can use
923 #
924 #    changedir playground
925 #    changedir $maindir
926 #
927 #    playtree_setup $local_git_cfg
928 #            # ^ call in some (perhaps trivial) subdir of playground
929 #
930 #    rmtree playground
931
932 # ----- maindir -----
933
934 our $local_git_cfg;
935
936 sub record_maindir () {
937     if (!defined $maindir) {
938         $maindir = must_getcwd();
939         if (!stat "$maindir/.git") {
940             fail f_ "cannot stat %s/.git: %s", $maindir, $!;
941         }
942         if (-d _) {
943             # we fall back to this in case we have a pre-worktree
944             # git, which may not know git rev-parse --git-common-dir
945             $maindir_gitdir    = "$maindir/.git";
946             $maindir_gitcommon = "$maindir/.git";
947         } else {
948             $maindir_gitdir    = cmdoutput qw(git rev-parse --git-dir);
949             $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
950         }
951     }
952     $local_git_cfg //= git_slurp_config_src 'local';
953 }
954
955 # ----- playgrounds -----
956
957 sub ensure_a_playground_parent ($) {
958     my ($spc) = @_;
959     record_maindir();
960     $spc = "$maindir_gitdir/$spc";
961     my $parent = dirname $spc;
962     mkdir $parent or $!==EEXIST or fail f_
963         "failed to mkdir playground parent %s: %s", $parent, $!;
964     return $spc;
965 }    
966
967 sub ensure_a_playground ($) {
968     my ($spc) = @_;
969     $spc = ensure_a_playground_parent $spc;
970     mkdir $spc or $!==EEXIST or fail f_
971         "failed to mkdir a playground %s: %s", $spc, $!;
972     return $spc;
973 }    
974
975 sub fresh_playground ($) {
976     my ($spc) = @_;
977     $spc = ensure_a_playground_parent $spc;
978     rmtree $spc;
979     mkdir $spc or fail f_
980         "failed to mkdir the playground %s: %s", $spc, $!;
981     return $spc;
982 }
983
984 # ----- playtrees -----
985
986 sub playtree_setup (;$) {
987     my ($t_local_git_cfg) = @_;
988     $t_local_git_cfg //= $local_git_cfg;
989     # for use in the playtree
990     # $maindir must be set, eg by calling record_maindir or fresh_playground
991     runcmd qw(git init -q);
992     runcmd qw(git config gc.auto 0);
993     foreach my $copy (qw(user.email user.name user.useConfigOnly
994                          core.sharedRepository
995                          core.compression core.looseCompression
996                          core.bigFileThreshold core.fsyncObjectFiles)) {
997         my $v = $t_local_git_cfg->{$copy};
998         next unless $v;
999         runcmd qw(git config), $copy, $_ foreach @$v;
1000     }
1001     # this is confusing: we have
1002     #   .                   playtree, not a worktree, has .git/, our cwd
1003     #   $maindir            might be a worktree so
1004     #   $maindir_gitdir     contains our main working "dgit", HEAD, etc.
1005     #   $maindir_gitcommon  the shared stuff, including .objects
1006     rmtree('.git/objects');
1007     symlink "$maindir_gitcommon/objects",'.git/objects' or confess "$!";
1008     ensuredir '.git/info';
1009     open GA, "> .git/info/attributes" or confess "$!";
1010     print GA "* $negate_harmful_gitattrs\n" or confess "$!";
1011     close GA or confess "$!";
1012 }
1013
1014 1;