chiark / gitweb /
Do not fail when cloning a package containing dangling symlinks.
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013-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 use strict;
21
22 use Debian::Dgit;
23 setup_sigwarn();
24
25 use IO::Handle;
26 use Data::Dumper;
27 use LWP::UserAgent;
28 use Dpkg::Control::Hash;
29 use File::Path;
30 use File::Temp qw(tempdir);
31 use File::Basename;
32 use Dpkg::Version;
33 use POSIX;
34 use IPC::Open2;
35 use Digest::SHA;
36 use Digest::MD5;
37 use List::Util qw(any);
38 use List::MoreUtils qw(pairwise);
39 use Text::Glob qw(match_glob);
40 use Fcntl qw(:DEFAULT :flock);
41 use Carp;
42
43 use Debian::Dgit;
44
45 our $our_version = 'UNRELEASED'; ###substituted###
46 our $absurdity = undef; ###substituted###
47
48 our @rpushprotovsn_support = qw(4 3 2); # 4 is new tag format
49 our $protovsn;
50
51 our $isuite = 'unstable';
52 our $idistro;
53 our $package;
54 our @ropts;
55
56 our $sign = 1;
57 our $dryrun_level = 0;
58 our $changesfile;
59 our $buildproductsdir = '..';
60 our $new_package = 0;
61 our $ignoredirty = 0;
62 our $rmonerror = 1;
63 our @deliberatelies;
64 our %previously;
65 our $existing_package = 'dpkg';
66 our $cleanmode;
67 our $changes_since_version;
68 our $rmchanges;
69 our $overwrite_version; # undef: not specified; '': check changelog
70 our $quilt_mode;
71 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|dpm|unapplied';
72 our $dodep14tag;
73 our $dodep14tag_re = 'want|no|always';
74 our $split_brain_save;
75 our $we_are_responder;
76 our $initiator_tempdir;
77 our $patches_applied_dirtily = 00;
78 our $tagformat_want;
79 our $tagformat;
80 our $tagformatfn;
81
82 our %forceopts = map { $_=>0 }
83     qw(unrepresentable unsupported-source-format
84        dsc-changes-mismatch changes-origs-exactly
85        import-gitapply-absurd
86        import-gitapply-no-absurd
87        import-dsc-with-dgit-field);
88
89 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
90
91 our $suite_re = '[-+.0-9a-z]+';
92 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
93 our $orig_f_comp_re = 'orig(?:-[-0-9a-z]+)?';
94 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
95 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
96
97 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
98 our $splitbraincache = 'dgit-intern/quilt-cache';
99
100 our (@git) = qw(git);
101 our (@dget) = qw(dget);
102 our (@curl) = qw(curl);
103 our (@dput) = qw(dput);
104 our (@debsign) = qw(debsign);
105 our (@gpg) = qw(gpg);
106 our (@sbuild) = qw(sbuild);
107 our (@ssh) = 'ssh';
108 our (@dgit) = qw(dgit);
109 our (@aptget) = qw(apt-get);
110 our (@aptcache) = qw(apt-cache);
111 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
112 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
113 our (@dpkggenchanges) = qw(dpkg-genchanges);
114 our (@mergechanges) = qw(mergechanges -f);
115 our (@gbp_build) = ('');
116 our (@gbp_pq) = ('gbp pq');
117 our (@changesopts) = ('');
118
119 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
120                      'curl' => \@curl,
121                      'dput' => \@dput,
122                      'debsign' => \@debsign,
123                      'gpg' => \@gpg,
124                      'sbuild' => \@sbuild,
125                      'ssh' => \@ssh,
126                      'dgit' => \@dgit,
127                      'git' => \@git,
128                      'apt-get' => \@aptget,
129                      'apt-cache' => \@aptcache,
130                      'dpkg-source' => \@dpkgsource,
131                      'dpkg-buildpackage' => \@dpkgbuildpackage,
132                      'dpkg-genchanges' => \@dpkggenchanges,
133                      'gbp-build' => \@gbp_build,
134                      'gbp-pq' => \@gbp_pq,
135                      'ch' => \@changesopts,
136                      'mergechanges' => \@mergechanges);
137
138 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
139 our %opts_cfg_insertpos = map {
140     $_,
141     scalar @{ $opts_opt_map{$_} }
142 } keys %opts_opt_map;
143
144 sub finalise_opts_opts();
145
146 our $keyid;
147
148 autoflush STDOUT 1;
149
150 our $supplementary_message = '';
151 our $need_split_build_invocation = 0;
152 our $split_brain = 0;
153
154 END {
155     local ($@, $?);
156     print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
157 }
158
159 our $remotename = 'dgit';
160 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
161 our $csuite;
162 our $instead_distro;
163
164 if (!defined $absurdity) {
165     $absurdity = $0;
166     $absurdity =~ s{/[^/]+$}{/absurd} or die;
167 }
168
169 sub debiantag ($$) {
170     my ($v,$distro) = @_;
171     return $tagformatfn->($v, $distro);
172 }
173
174 sub debiantag_maintview ($$) { 
175     my ($v,$distro) = @_;
176     return "$distro/".dep14_version_mangle $v;
177 }
178
179 sub madformat ($) { $_[0] eq '3.0 (quilt)' }
180
181 sub lbranch () { return "$branchprefix/$csuite"; }
182 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
183 sub lref () { return "refs/heads/".lbranch(); }
184 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
185 sub rrref () { return server_ref($csuite); }
186
187 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
188 sub lrfetchref () { return lrfetchrefs.'/'.server_branch($csuite); }
189
190 # We fetch some parts of lrfetchrefs/*.  Ideally we delete these
191 # locally fetched refs because they have unhelpful names and clutter
192 # up gitk etc.  So we track whether we have "used up" head ref (ie,
193 # whether we have made another local ref which refers to this object).
194 #
195 # (If we deleted them unconditionally, then we might end up
196 # re-fetching the same git objects each time dgit fetch was run.)
197 #
198 # So, leach use of lrfetchrefs needs to be accompanied by arrangements
199 # in git_fetch_us to fetch the refs in question, and possibly a call
200 # to lrfetchref_used.
201
202 our (%lrfetchrefs_f, %lrfetchrefs_d);
203 # $lrfetchrefs_X{lrfetchrefs."/heads/whatever"} = $objid
204
205 sub lrfetchref_used ($) {
206     my ($fullrefname) = @_;
207     my $objid = $lrfetchrefs_f{$fullrefname};
208     $lrfetchrefs_d{$fullrefname} = $objid if defined $objid;
209 }
210
211 sub stripepoch ($) {
212     my ($vsn) = @_;
213     $vsn =~ s/^\d+\://;
214     return $vsn;
215 }
216
217 sub srcfn ($$) {
218     my ($vsn,$sfx) = @_;
219     return "${package}_".(stripepoch $vsn).$sfx
220 }
221
222 sub dscfn ($) {
223     my ($vsn) = @_;
224     return srcfn($vsn,".dsc");
225 }
226
227 sub changespat ($;$) {
228     my ($vsn, $arch) = @_;
229     return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
230 }
231
232 sub upstreamversion ($) {
233     my ($vsn) = @_;
234     $vsn =~ s/-[^-]+$//;
235     return $vsn;
236 }
237
238 our $us = 'dgit';
239 initdebug('');
240
241 our @end;
242 END { 
243     local ($?);
244     foreach my $f (@end) {
245         eval { $f->(); };
246         print STDERR "$us: cleanup: $@" if length $@;
247     }
248 };
249
250 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
251
252 sub forceable_fail ($$) {
253     my ($forceoptsl, $msg) = @_;
254     fail $msg unless grep { $forceopts{$_} } @$forceoptsl;
255     print STDERR "warning: overriding problem due to --force:\n". $msg;
256 }
257
258 sub forceing ($) {
259     my ($forceoptsl) = @_;
260     my @got = grep { $forceopts{$_} } @$forceoptsl;
261     return 0 unless @got;
262     print STDERR
263  "warning: skipping checks or functionality due to --force-$got[0]\n";
264 }
265
266 sub no_such_package () {
267     print STDERR "$us: package $package does not exist in suite $isuite\n";
268     exit 4;
269 }
270
271 sub changedir ($) {
272     my ($newdir) = @_;
273     printdebug "CD $newdir\n";
274     chdir $newdir or confess "chdir: $newdir: $!";
275 }
276
277 sub deliberately ($) {
278     my ($enquiry) = @_;
279     return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
280 }
281
282 sub deliberately_not_fast_forward () {
283     foreach (qw(not-fast-forward fresh-repo)) {
284         return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
285     }
286 }
287
288 sub quiltmode_splitbrain () {
289     $quilt_mode =~ m/gbp|dpm|unapplied/;
290 }
291
292 sub opts_opt_multi_cmd {
293     my @cmd;
294     push @cmd, split /\s+/, shift @_;
295     push @cmd, @_;
296     @cmd;
297 }
298
299 sub gbp_pq {
300     return opts_opt_multi_cmd @gbp_pq;
301 }
302
303 #---------- remote protocol support, common ----------
304
305 # remote push initiator/responder protocol:
306 #  $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
307 #  where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
308 #  < dgit-remote-push-ready <actual-proto-vsn>
309 #
310 # occasionally:
311 #
312 #  > progress NBYTES
313 #  [NBYTES message]
314 #
315 #  > supplementary-message NBYTES          # $protovsn >= 3
316 #  [NBYTES message]
317 #
318 # main sequence:
319 #
320 #  > file parsed-changelog
321 #  [indicates that output of dpkg-parsechangelog follows]
322 #  > data-block NBYTES
323 #  > [NBYTES bytes of data (no newline)]
324 #  [maybe some more blocks]
325 #  > data-end
326 #
327 #  > file dsc
328 #  [etc]
329 #
330 #  > file changes
331 #  [etc]
332 #
333 #  > param head DGIT-VIEW-HEAD
334 #  > param csuite SUITE
335 #  > param tagformat old|new
336 #  > param maint-view MAINT-VIEW-HEAD
337 #
338 #  > previously REFNAME=OBJNAME       # if --deliberately-not-fast-forward
339 #                                     # goes into tag, for replay prevention
340 #
341 #  > want signed-tag
342 #  [indicates that signed tag is wanted]
343 #  < data-block NBYTES
344 #  < [NBYTES bytes of data (no newline)]
345 #  [maybe some more blocks]
346 #  < data-end
347 #  < files-end
348 #
349 #  > want signed-dsc-changes
350 #  < data-block NBYTES    [transfer of signed dsc]
351 #  [etc]
352 #  < data-block NBYTES    [transfer of signed changes]
353 #  [etc]
354 #  < files-end
355 #
356 #  > complete
357
358 our $i_child_pid;
359
360 sub i_child_report () {
361     # Sees if our child has died, and reap it if so.  Returns a string
362     # describing how it died if it failed, or undef otherwise.
363     return undef unless $i_child_pid;
364     my $got = waitpid $i_child_pid, WNOHANG;
365     return undef if $got <= 0;
366     die unless $got == $i_child_pid;
367     $i_child_pid = undef;
368     return undef unless $?;
369     return "build host child ".waitstatusmsg();
370 }
371
372 sub badproto ($$) {
373     my ($fh, $m) = @_;
374     fail "connection lost: $!" if $fh->error;
375     fail "protocol violation; $m not expected";
376 }
377
378 sub badproto_badread ($$) {
379     my ($fh, $wh) = @_;
380     fail "connection lost: $!" if $!;
381     my $report = i_child_report();
382     fail $report if defined $report;
383     badproto $fh, "eof (reading $wh)";
384 }
385
386 sub protocol_expect (&$) {
387     my ($match, $fh) = @_;
388     local $_;
389     $_ = <$fh>;
390     defined && chomp or badproto_badread $fh, "protocol message";
391     if (wantarray) {
392         my @r = &$match;
393         return @r if @r;
394     } else {
395         my $r = &$match;
396         return $r if $r;
397     }
398     badproto $fh, "\`$_'";
399 }
400
401 sub protocol_send_file ($$) {
402     my ($fh, $ourfn) = @_;
403     open PF, "<", $ourfn or die "$ourfn: $!";
404     for (;;) {
405         my $d;
406         my $got = read PF, $d, 65536;
407         die "$ourfn: $!" unless defined $got;
408         last if !$got;
409         print $fh "data-block ".length($d)."\n" or die $!;
410         print $fh $d or die $!;
411     }
412     PF->error and die "$ourfn $!";
413     print $fh "data-end\n" or die $!;
414     close PF;
415 }
416
417 sub protocol_read_bytes ($$) {
418     my ($fh, $nbytes) = @_;
419     $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
420     my $d;
421     my $got = read $fh, $d, $nbytes;
422     $got==$nbytes or badproto_badread $fh, "data block";
423     return $d;
424 }
425
426 sub protocol_receive_file ($$) {
427     my ($fh, $ourfn) = @_;
428     printdebug "() $ourfn\n";
429     open PF, ">", $ourfn or die "$ourfn: $!";
430     for (;;) {
431         my ($y,$l) = protocol_expect {
432             m/^data-block (.*)$/ ? (1,$1) :
433             m/^data-end$/ ? (0,) :
434             ();
435         } $fh;
436         last unless $y;
437         my $d = protocol_read_bytes $fh, $l;
438         print PF $d or die $!;
439     }
440     close PF or die $!;
441 }
442
443 #---------- remote protocol support, responder ----------
444
445 sub responder_send_command ($) {
446     my ($command) = @_;
447     return unless $we_are_responder;
448     # called even without $we_are_responder
449     printdebug ">> $command\n";
450     print PO $command, "\n" or die $!;
451 }    
452
453 sub responder_send_file ($$) {
454     my ($keyword, $ourfn) = @_;
455     return unless $we_are_responder;
456     printdebug "]] $keyword $ourfn\n";
457     responder_send_command "file $keyword";
458     protocol_send_file \*PO, $ourfn;
459 }
460
461 sub responder_receive_files ($@) {
462     my ($keyword, @ourfns) = @_;
463     die unless $we_are_responder;
464     printdebug "[[ $keyword @ourfns\n";
465     responder_send_command "want $keyword";
466     foreach my $fn (@ourfns) {
467         protocol_receive_file \*PI, $fn;
468     }
469     printdebug "[[\$\n";
470     protocol_expect { m/^files-end$/ } \*PI;
471 }
472
473 #---------- remote protocol support, initiator ----------
474
475 sub initiator_expect (&) {
476     my ($match) = @_;
477     protocol_expect { &$match } \*RO;
478 }
479
480 #---------- end remote code ----------
481
482 sub progress {
483     if ($we_are_responder) {
484         my $m = join '', @_;
485         responder_send_command "progress ".length($m) or die $!;
486         print PO $m or die $!;
487     } else {
488         print @_, "\n";
489     }
490 }
491
492 our $ua;
493
494 sub url_get {
495     if (!$ua) {
496         $ua = LWP::UserAgent->new();
497         $ua->env_proxy;
498     }
499     my $what = $_[$#_];
500     progress "downloading $what...";
501     my $r = $ua->get(@_) or die $!;
502     return undef if $r->code == 404;
503     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
504     return $r->decoded_content(charset => 'none');
505 }
506
507 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
508
509 sub runcmd {
510     debugcmd "+",@_;
511     $!=0; $?=-1;
512     failedcmd @_ if system @_;
513 }
514
515 sub act_local () { return $dryrun_level <= 1; }
516 sub act_scary () { return !$dryrun_level; }
517
518 sub printdone {
519     if (!$dryrun_level) {
520         progress "$us ok: @_";
521     } else {
522         progress "would be ok: @_ (but dry run only)";
523     }
524 }
525
526 sub dryrun_report {
527     printcmd(\*STDERR,$debugprefix."#",@_);
528 }
529
530 sub runcmd_ordryrun {
531     if (act_scary()) {
532         runcmd @_;
533     } else {
534         dryrun_report @_;
535     }
536 }
537
538 sub runcmd_ordryrun_local {
539     if (act_local()) {
540         runcmd @_;
541     } else {
542         dryrun_report @_;
543     }
544 }
545
546 sub shell_cmd {
547     my ($first_shell, @cmd) = @_;
548     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
549 }
550
551 our $helpmsg = <<END;
552 main usages:
553   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
554   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
555   dgit [dgit-opts] build [dpkg-buildpackage-opts]
556   dgit [dgit-opts] sbuild [sbuild-opts]
557   dgit [dgit-opts] push [dgit-opts] [suite]
558   dgit [dgit-opts] rpush build-host:build-dir ...
559 important dgit options:
560   -k<keyid>           sign tag and package with <keyid> instead of default
561   --dry-run -n        do not change anything, but go through the motions
562   --damp-run -L       like --dry-run but make local changes, without signing
563   --new -N            allow introducing a new package
564   --debug -D          increase debug level
565   -c<name>=<value>    set git config option (used directly by dgit too)
566 END
567
568 our $later_warning_msg = <<END;
569 Perhaps the upload is stuck in incoming.  Using the version from git.
570 END
571
572 sub badusage {
573     print STDERR "$us: @_\n", $helpmsg or die $!;
574     exit 8;
575 }
576
577 sub nextarg {
578     @ARGV or badusage "too few arguments";
579     return scalar shift @ARGV;
580 }
581
582 sub cmd_help () {
583     print $helpmsg or die $!;
584     exit 0;
585 }
586
587 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
588
589 our %defcfg = ('dgit.default.distro' => 'debian',
590                'dgit-suite.*-security.distro' => 'debian-security',
591                'dgit.default.username' => '',
592                'dgit.default.archive-query-default-component' => 'main',
593                'dgit.default.ssh' => 'ssh',
594                'dgit.default.archive-query' => 'madison:',
595                'dgit.default.sshpsql-dbname' => 'service=projectb',
596                'dgit.default.aptget-components' => 'main',
597                'dgit.default.dgit-tag-format' => 'new,old,maint',
598                # old means "repo server accepts pushes with old dgit tags"
599                # new means "repo server accepts pushes with new dgit tags"
600                # maint means "repo server accepts split brain pushes"
601                # hist means "repo server may have old pushes without new tag"
602                #   ("hist" is implied by "old")
603                'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
604                'dgit-distro.debian.git-check' => 'url',
605                'dgit-distro.debian.git-check-suffix' => '/info/refs',
606                'dgit-distro.debian.new-private-pushers' => 't',
607                'dgit-distro.debian/push.git-url' => '',
608                'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
609                'dgit-distro.debian/push.git-user-force' => 'dgit',
610                'dgit-distro.debian/push.git-proto' => 'git+ssh://',
611                'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
612                'dgit-distro.debian/push.git-create' => 'true',
613                'dgit-distro.debian/push.git-check' => 'ssh-cmd',
614  'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
615 # 'dgit-distro.debian.archive-query-tls-key',
616 #    '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
617 # ^ this does not work because curl is broken nowadays
618 # Fixing #790093 properly will involve providing providing the key
619 # in some pacagke and maybe updating these paths.
620 #
621 # 'dgit-distro.debian.archive-query-tls-curl-args',
622 #   '--ca-path=/etc/ssl/ca-debian',
623 # ^ this is a workaround but works (only) on DSA-administered machines
624                'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
625                'dgit-distro.debian.git-url-suffix' => '',
626                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
627                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
628  'dgit-distro.debian-security.archive-query' => 'aptget:',
629  'dgit-distro.debian-security.mirror' => 'http://security.debian.org/debian-security/',
630  'dgit-distro.debian-security.aptget-suite-map' => 's#-security$#/updates#',
631  'dgit-distro.debian-security.aptget-suite-rmap' => 's#$#-security#',
632  'dgit-distro.debian-security.nominal-distro' => 'debian',
633  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
634  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
635                'dgit-distro.ubuntu.git-check' => 'false',
636  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
637                'dgit-distro.test-dummy.ssh' => "$td/ssh",
638                'dgit-distro.test-dummy.username' => "alice",
639                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
640                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
641                'dgit-distro.test-dummy.git-url' => "$td/git",
642                'dgit-distro.test-dummy.git-host' => "git",
643                'dgit-distro.test-dummy.git-path' => "$td/git",
644                'dgit-distro.test-dummy.archive-query' => "dummycatapi:",
645                'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
646                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
647                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
648                );
649
650 our %gitcfgs;
651 our @gitcfgsources = qw(cmdline local global system);
652
653 sub git_slurp_config () {
654     local ($debuglevel) = $debuglevel-2;
655     local $/="\0";
656
657     # This algoritm is a bit subtle, but this is needed so that for
658     # options which we want to be single-valued, we allow the
659     # different config sources to override properly.  See #835858.
660     foreach my $src (@gitcfgsources) {
661         next if $src eq 'cmdline';
662         # we do this ourselves since git doesn't handle it
663         
664         my @cmd = (@git, qw(config -z --get-regexp), "--$src", qw(.*));
665         debugcmd "|",@cmd;
666
667         open GITS, "-|", @cmd or die $!;
668         while (<GITS>) {
669             chomp or die;
670             printdebug "=> ", (messagequote $_), "\n";
671             m/\n/ or die "$_ ?";
672             push @{ $gitcfgs{$src}{$`} }, $'; #';
673         }
674         $!=0; $?=0;
675         close GITS
676             or ($!==0 && $?==256)
677             or failedcmd @cmd;
678     }
679 }
680
681 sub git_get_config ($) {
682     my ($c) = @_;
683     foreach my $src (@gitcfgsources) {
684         my $l = $gitcfgs{$src}{$c};
685         printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
686             if $debuglevel >= 4;
687         $l or next;
688         @$l==1 or badcfg "multiple values for $c".
689             " (in $src git config)" if @$l > 1;
690         return $l->[0];
691     }
692     return undef;
693 }
694
695 sub cfg {
696     foreach my $c (@_) {
697         return undef if $c =~ /RETURN-UNDEF/;
698         my $v = git_get_config($c);
699         return $v if defined $v;
700         my $dv = $defcfg{$c};
701         return $dv if defined $dv;
702     }
703     badcfg "need value for one of: @_\n".
704         "$us: distro or suite appears not to be (properly) supported";
705 }
706
707 sub access_basedistro () {
708     if (defined $idistro) {
709         return $idistro;
710     } else {    
711         my $def = cfg("dgit-suite.$isuite.distro", 'RETURN-UNDEF');
712         return $def if defined $def;
713         foreach my $src (@gitcfgsources, 'internal') {
714             my $kl = $src eq 'internal' ? \%defcfg : $gitcfgs{$src};
715             next unless $kl;
716             foreach my $k (keys %$kl) {
717                 next unless $k =~ m#^dgit-suite\.(.*)\.distro$#;
718                 my $dpat = $1;
719                 next unless match_glob $dpat, $isuite;
720                 return $kl->{$k};
721             }
722         }
723         return cfg("dgit.default.distro");
724     }
725 }
726
727 sub access_nomdistro () {
728     my $base = access_basedistro();
729     return cfg("dgit-distro.$base.nominal-distro",'RETURN-UNDEF') // $base;
730 }
731
732 sub access_quirk () {
733     # returns (quirk name, distro to use instead or undef, quirk-specific info)
734     my $basedistro = access_basedistro();
735     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
736                               'RETURN-UNDEF');
737     if (defined $backports_quirk) {
738         my $re = $backports_quirk;
739         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
740         $re =~ s/\*/.*/g;
741         $re =~ s/\%/([-0-9a-z_]+)/
742             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
743         if ($isuite =~ m/^$re$/) {
744             return ('backports',"$basedistro-backports",$1);
745         }
746     }
747     return ('none',undef);
748 }
749
750 our $access_forpush;
751
752 sub parse_cfg_bool ($$$) {
753     my ($what,$def,$v) = @_;
754     $v //= $def;
755     return
756         $v =~ m/^[ty1]/ ? 1 :
757         $v =~ m/^[fn0]/ ? 0 :
758         badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
759 }       
760
761 sub access_forpush_config () {
762     my $d = access_basedistro();
763
764     return 1 if
765         $new_package &&
766         parse_cfg_bool('new-private-pushers', 0,
767                        cfg("dgit-distro.$d.new-private-pushers",
768                            'RETURN-UNDEF'));
769
770     my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
771     $v //= 'a';
772     return
773         $v =~ m/^[ty1]/ ? 0 : # force readonly,    forpush = 0
774         $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
775         $v =~ m/^[a]/  ? '' : # auto,              forpush = ''
776         badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
777 }
778
779 sub access_forpush () {
780     $access_forpush //= access_forpush_config();
781     return $access_forpush;
782 }
783
784 sub pushing () {
785     die "$access_forpush ?" if ($access_forpush // 1) ne 1;
786     badcfg "pushing but distro is configured readonly"
787         if access_forpush_config() eq '0';
788     $access_forpush = 1;
789     $supplementary_message = <<'END' unless $we_are_responder;
790 Push failed, before we got started.
791 You can retry the push, after fixing the problem, if you like.
792 END
793     finalise_opts_opts();
794 }
795
796 sub notpushing () {
797     finalise_opts_opts();
798 }
799
800 sub supplementary_message ($) {
801     my ($msg) = @_;
802     if (!$we_are_responder) {
803         $supplementary_message = $msg;
804         return;
805     } elsif ($protovsn >= 3) {
806         responder_send_command "supplementary-message ".length($msg)
807             or die $!;
808         print PO $msg or die $!;
809     }
810 }
811
812 sub access_distros () {
813     # Returns list of distros to try, in order
814     #
815     # We want to try:
816     #    0. `instead of' distro name(s) we have been pointed to
817     #    1. the access_quirk distro, if any
818     #    2a. the user's specified distro, or failing that  } basedistro
819     #    2b. the distro calculated from the suite          }
820     my @l = access_basedistro();
821
822     my (undef,$quirkdistro) = access_quirk();
823     unshift @l, $quirkdistro;
824     unshift @l, $instead_distro;
825     @l = grep { defined } @l;
826
827     push @l, access_nomdistro();
828
829     if (access_forpush()) {
830         @l = map { ("$_/push", $_) } @l;
831     }
832     @l;
833 }
834
835 sub access_cfg_cfgs (@) {
836     my (@keys) = @_;
837     my @cfgs;
838     # The nesting of these loops determines the search order.  We put
839     # the key loop on the outside so that we search all the distros
840     # for each key, before going on to the next key.  That means that
841     # if access_cfg is called with a more specific, and then a less
842     # specific, key, an earlier distro can override the less specific
843     # without necessarily overriding any more specific keys.  (If the
844     # distro wants to override the more specific keys it can simply do
845     # so; whereas if we did the loop the other way around, it would be
846     # impossible to for an earlier distro to override a less specific
847     # key but not the more specific ones without restating the unknown
848     # values of the more specific keys.
849     my @realkeys;
850     my @rundef;
851     # We have to deal with RETURN-UNDEF specially, so that we don't
852     # terminate the search prematurely.
853     foreach (@keys) {
854         if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
855         push @realkeys, $_
856     }
857     foreach my $d (access_distros()) {
858         push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
859     }
860     push @cfgs, map { "dgit.default.$_" } @realkeys;
861     push @cfgs, @rundef;
862     return @cfgs;
863 }
864
865 sub access_cfg (@) {
866     my (@keys) = @_;
867     my (@cfgs) = access_cfg_cfgs(@keys);
868     my $value = cfg(@cfgs);
869     return $value;
870 }
871
872 sub access_cfg_bool ($$) {
873     my ($def, @keys) = @_;
874     parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
875 }
876
877 sub string_to_ssh ($) {
878     my ($spec) = @_;
879     if ($spec =~ m/\s/) {
880         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
881     } else {
882         return ($spec);
883     }
884 }
885
886 sub access_cfg_ssh () {
887     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
888     if (!defined $gitssh) {
889         return @ssh;
890     } else {
891         return string_to_ssh $gitssh;
892     }
893 }
894
895 sub access_runeinfo ($) {
896     my ($info) = @_;
897     return ": dgit ".access_basedistro()." $info ;";
898 }
899
900 sub access_someuserhost ($) {
901     my ($some) = @_;
902     my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
903     defined($user) && length($user) or
904         $user = access_cfg("$some-user",'username');
905     my $host = access_cfg("$some-host");
906     return length($user) ? "$user\@$host" : $host;
907 }
908
909 sub access_gituserhost () {
910     return access_someuserhost('git');
911 }
912
913 sub access_giturl (;$) {
914     my ($optional) = @_;
915     my $url = access_cfg('git-url','RETURN-UNDEF');
916     my $suffix;
917     if (!length $url) {
918         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
919         return undef unless defined $proto;
920         $url =
921             $proto.
922             access_gituserhost().
923             access_cfg('git-path');
924     } else {
925         $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
926     }
927     $suffix //= '.git';
928     return "$url/$package$suffix";
929 }              
930
931 sub parsecontrolfh ($$;$) {
932     my ($fh, $desc, $allowsigned) = @_;
933     our $dpkgcontrolhash_noissigned;
934     my $c;
935     for (;;) {
936         my %opts = ('name' => $desc);
937         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
938         $c = Dpkg::Control::Hash->new(%opts);
939         $c->parse($fh,$desc) or die "parsing of $desc failed";
940         last if $allowsigned;
941         last if $dpkgcontrolhash_noissigned;
942         my $issigned= $c->get_option('is_pgp_signed');
943         if (!defined $issigned) {
944             $dpkgcontrolhash_noissigned= 1;
945             seek $fh, 0,0 or die "seek $desc: $!";
946         } elsif ($issigned) {
947             fail "control file $desc is (already) PGP-signed. ".
948                 " Note that dgit push needs to modify the .dsc and then".
949                 " do the signature itself";
950         } else {
951             last;
952         }
953     }
954     return $c;
955 }
956
957 sub parsecontrol {
958     my ($file, $desc, $allowsigned) = @_;
959     my $fh = new IO::Handle;
960     open $fh, '<', $file or die "$file: $!";
961     my $c = parsecontrolfh($fh,$desc,$allowsigned);
962     $fh->error and die $!;
963     close $fh;
964     return $c;
965 }
966
967 sub getfield ($$) {
968     my ($dctrl,$field) = @_;
969     my $v = $dctrl->{$field};
970     return $v if defined $v;
971     fail "missing field $field in ".$dctrl->get_option('name');
972 }
973
974 sub parsechangelog {
975     my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
976     my $p = new IO::Handle;
977     my @cmd = (qw(dpkg-parsechangelog), @_);
978     open $p, '-|', @cmd or die $!;
979     $c->parse($p);
980     $?=0; $!=0; close $p or failedcmd @cmd;
981     return $c;
982 }
983
984 sub commit_getclogp ($) {
985     # Returns the parsed changelog hashref for a particular commit
986     my ($objid) = @_;
987     our %commit_getclogp_memo;
988     my $memo = $commit_getclogp_memo{$objid};
989     return $memo if $memo;
990     mkpath '.git/dgit';
991     my $mclog = ".git/dgit/clog-$objid";
992     runcmd shell_cmd "exec >$mclog", @git, qw(cat-file blob),
993         "$objid:debian/changelog";
994     $commit_getclogp_memo{$objid} = parsechangelog("-l$mclog");
995 }
996
997 sub must_getcwd () {
998     my $d = getcwd();
999     defined $d or fail "getcwd failed: $!";
1000     return $d;
1001 }
1002
1003 sub parse_dscdata () {
1004     my $dscfh = new IO::File \$dscdata, '<' or die $!;
1005     printdebug Dumper($dscdata) if $debuglevel>1;
1006     $dsc = parsecontrolfh($dscfh,$dscurl,1);
1007     printdebug Dumper($dsc) if $debuglevel>1;
1008 }
1009
1010 our %rmad;
1011
1012 sub archive_query ($;@) {
1013     my ($method) = shift @_;
1014     fail "this operation does not support multiple comma-separated suites"
1015         if $isuite =~ m/,/;
1016     my $query = access_cfg('archive-query','RETURN-UNDEF');
1017     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
1018     my $proto = $1;
1019     my $data = $'; #';
1020     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data,@_); }
1021 }
1022
1023 sub archive_query_prepend_mirror {
1024     my $m = access_cfg('mirror');
1025     return map { [ $_->[0], $m.$_->[1], @$_[2..$#$_] ] } @_;
1026 }
1027
1028 sub pool_dsc_subpath ($$) {
1029     my ($vsn,$component) = @_; # $package is implict arg
1030     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
1031     return "/pool/$component/$prefix/$package/".dscfn($vsn);
1032 }
1033
1034 sub cfg_apply_map ($$$) {
1035     my ($varref, $what, $mapspec) = @_;
1036     return unless $mapspec;
1037
1038     printdebug "config $what EVAL{ $mapspec; }\n";
1039     $_ = $$varref;
1040     eval "package Dgit::Config; $mapspec;";
1041     die $@ if $@;
1042     $$varref = $_;
1043 }
1044
1045 #---------- `ftpmasterapi' archive query method (nascent) ----------
1046
1047 sub archive_api_query_cmd ($) {
1048     my ($subpath) = @_;
1049     my @cmd = (@curl, qw(-sS));
1050     my $url = access_cfg('archive-query-url');
1051     if ($url =~ m#^https://([-.0-9a-z]+)/#) {
1052         my $host = $1;
1053         my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
1054         foreach my $key (split /\:/, $keys) {
1055             $key =~ s/\%HOST\%/$host/g;
1056             if (!stat $key) {
1057                 fail "for $url: stat $key: $!" unless $!==ENOENT;
1058                 next;
1059             }
1060             fail "config requested specific TLS key but do not know".
1061                 " how to get curl to use exactly that EE key ($key)";
1062 #           push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
1063 #           # Sadly the above line does not work because of changes
1064 #           # to gnutls.   The real fix for #790093 may involve
1065 #           # new curl options.
1066             last;
1067         }
1068         # Fixing #790093 properly will involve providing a value
1069         # for this on clients.
1070         my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
1071         push @cmd, split / /, $kargs if defined $kargs;
1072     }
1073     push @cmd, $url.$subpath;
1074     return @cmd;
1075 }
1076
1077 sub api_query ($$;$) {
1078     use JSON;
1079     my ($data, $subpath, $ok404) = @_;
1080     badcfg "ftpmasterapi archive query method takes no data part"
1081         if length $data;
1082     my @cmd = archive_api_query_cmd($subpath);
1083     my $url = $cmd[$#cmd];
1084     push @cmd, qw(-w %{http_code});
1085     my $json = cmdoutput @cmd;
1086     unless ($json =~ s/\d+\d+\d$//) {
1087         failedcmd_report_cmd undef, @cmd;
1088         fail "curl failed to print 3-digit HTTP code";
1089     }
1090     my $code = $&;
1091     return undef if $code eq '404' && $ok404;
1092     fail "fetch of $url gave HTTP code $code"
1093         unless $url =~ m#^file://# or $code =~ m/^2/;
1094     return decode_json($json);
1095 }
1096
1097 sub canonicalise_suite_ftpmasterapi {
1098     my ($proto,$data) = @_;
1099     my $suites = api_query($data, 'suites');
1100     my @matched;
1101     foreach my $entry (@$suites) {
1102         next unless grep { 
1103             my $v = $entry->{$_};
1104             defined $v && $v eq $isuite;
1105         } qw(codename name);
1106         push @matched, $entry;
1107     }
1108     fail "unknown suite $isuite" unless @matched;
1109     my $cn;
1110     eval {
1111         @matched==1 or die "multiple matches for suite $isuite\n";
1112         $cn = "$matched[0]{codename}";
1113         defined $cn or die "suite $isuite info has no codename\n";
1114         $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
1115     };
1116     die "bad ftpmaster api response: $@\n".Dumper(\@matched)
1117         if length $@;
1118     return $cn;
1119 }
1120
1121 sub archive_query_ftpmasterapi {
1122     my ($proto,$data) = @_;
1123     my $info = api_query($data, "dsc_in_suite/$isuite/$package");
1124     my @rows;
1125     my $digester = Digest::SHA->new(256);
1126     foreach my $entry (@$info) {
1127         eval {
1128             my $vsn = "$entry->{version}";
1129             my ($ok,$msg) = version_check $vsn;
1130             die "bad version: $msg\n" unless $ok;
1131             my $component = "$entry->{component}";
1132             $component =~ m/^$component_re$/ or die "bad component";
1133             my $filename = "$entry->{filename}";
1134             $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
1135                 or die "bad filename";
1136             my $sha256sum = "$entry->{sha256sum}";
1137             $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
1138             push @rows, [ $vsn, "/pool/$component/$filename",
1139                           $digester, $sha256sum ];
1140         };
1141         die "bad ftpmaster api response: $@\n".Dumper($entry)
1142             if length $@;
1143     }
1144     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1145     return archive_query_prepend_mirror @rows;
1146 }
1147
1148 sub file_in_archive_ftpmasterapi {
1149     my ($proto,$data,$filename) = @_;
1150     my $pat = $filename;
1151     $pat =~ s/_/\\_/g;
1152     $pat = "%/$pat";
1153     $pat =~ s#[^-+_.0-9a-z/]# sprintf '%%%02x', ord $& #ge;
1154     my $info = api_query($data, "file_in_archive/$pat", 1);
1155 }
1156
1157 #---------- `aptget' archive query method ----------
1158
1159 our $aptget_base;
1160 our $aptget_releasefile;
1161 our $aptget_configpath;
1162
1163 sub aptget_aptget   () { return @aptget,   qw(-c), $aptget_configpath; }
1164 sub aptget_aptcache () { return @aptcache, qw(-c), $aptget_configpath; }
1165
1166 sub aptget_cache_clean {
1167     runcmd_ordryrun_local qw(sh -ec),
1168         'cd "$1"; find -atime +30 -type f -print0 | xargs -0r rm --',
1169         'x', $aptget_base;
1170 }
1171
1172 sub aptget_lock_acquire () {
1173     my $lockfile = "$aptget_base/lock";
1174     open APTGET_LOCK, '>', $lockfile or die "open $lockfile: $!";
1175     flock APTGET_LOCK, LOCK_EX or die "lock $lockfile: $!";
1176 }
1177
1178 sub aptget_prep ($) {
1179     my ($data) = @_;
1180     return if defined $aptget_base;
1181
1182     badcfg "aptget archive query method takes no data part"
1183         if length $data;
1184
1185     my $cache = $ENV{XDG_CACHE_DIR} // "$ENV{HOME}/.cache";
1186
1187     ensuredir $cache;
1188     ensuredir "$cache/dgit";
1189     my $cachekey =
1190         access_cfg('aptget-cachekey','RETURN-UNDEF')
1191         // access_nomdistro();
1192
1193     $aptget_base = "$cache/dgit/aptget";
1194     ensuredir $aptget_base;
1195
1196     my $quoted_base = $aptget_base;
1197     die "$quoted_base contains bad chars, cannot continue"
1198         if $quoted_base =~ m/["\\]/; # apt.conf(5) says no escaping :-/
1199
1200     ensuredir $aptget_base;
1201
1202     aptget_lock_acquire();
1203
1204     aptget_cache_clean();
1205
1206     $aptget_configpath = "$aptget_base/apt.conf#$cachekey";
1207     my $sourceslist = "source.list#$cachekey";
1208
1209     my $aptsuites = $isuite;
1210     cfg_apply_map(\$aptsuites, 'suite map',
1211                   access_cfg('aptget-suite-map', 'RETURN-UNDEF'));
1212
1213     open SRCS, ">", "$aptget_base/$sourceslist" or die $!;
1214     printf SRCS "deb-src %s %s %s\n",
1215         access_cfg('mirror'),
1216         $aptsuites,
1217         access_cfg('aptget-components')
1218         or die $!;
1219
1220     ensuredir "$aptget_base/cache";
1221     ensuredir "$aptget_base/lists";
1222
1223     open CONF, ">", $aptget_configpath or die $!;
1224     print CONF <<END;
1225 Debug::NoLocking "true";
1226 APT::Get::List-Cleanup "false";
1227 #clear APT::Update::Post-Invoke-Success;
1228 Dir::Etc::SourceList "$quoted_base/$sourceslist";
1229 Dir::State::Lists "$quoted_base/lists";
1230 Dir::Etc::preferences "$quoted_base/preferences";
1231 Dir::Cache::srcpkgcache "$quoted_base/cache/srcs#$cachekey";
1232 Dir::Cache::pkgcache "$quoted_base/cache/pkgs#$cachekey";
1233 END
1234
1235     foreach my $key (qw(
1236                         Dir::Cache
1237                         Dir::State
1238                         Dir::Cache::Archives
1239                         Dir::Etc::SourceParts
1240                         Dir::Etc::preferencesparts
1241                       )) {
1242         ensuredir "$aptget_base/$key";
1243         print CONF "$key \"$quoted_base/$key\";\n" or die $!;
1244     };
1245
1246     my $oldatime = (time // die $!) - 1;
1247     foreach my $oldlist (<$aptget_base/lists/*Release>) {
1248         next unless stat_exists $oldlist;
1249         my ($mtime) = (stat _)[9];
1250         utime $oldatime, $mtime, $oldlist or die "$oldlist $!";
1251     }
1252
1253     runcmd_ordryrun_local aptget_aptget(), qw(update);
1254
1255     my @releasefiles;
1256     foreach my $oldlist (<$aptget_base/lists/*Release>) {
1257         next unless stat_exists $oldlist;
1258         my ($atime) = (stat _)[8];
1259         next if $atime == $oldatime;
1260         push @releasefiles, $oldlist;
1261     }
1262     my @inreleasefiles = grep { m#/InRelease$# } @releasefiles;
1263     @releasefiles = @inreleasefiles if @inreleasefiles;
1264     die "apt updated wrong number of Release files (@releasefiles), erk"
1265         unless @releasefiles == 1;
1266
1267     ($aptget_releasefile) = @releasefiles;
1268 }
1269
1270 sub canonicalise_suite_aptget {
1271     my ($proto,$data) = @_;
1272     aptget_prep($data);
1273
1274     my $release = parsecontrol $aptget_releasefile, "Release file", 1;
1275
1276     foreach my $name (qw(Codename Suite)) {
1277         my $val = $release->{$name};
1278         if (defined $val) {
1279             printdebug "release file $name: $val\n";
1280             $val =~ m/^$suite_re$/o or fail
1281  "Release file ($aptget_releasefile) specifies intolerable $name";
1282             cfg_apply_map(\$val, 'suite rmap',
1283                           access_cfg('aptget-suite-rmap', 'RETURN-UNDEF'));
1284             return $val
1285         }
1286     }
1287     return $isuite;
1288 }
1289
1290 sub archive_query_aptget {
1291     my ($proto,$data) = @_;
1292     aptget_prep($data);
1293
1294     ensuredir "$aptget_base/source";
1295     foreach my $old (<$aptget_base/source/*.dsc>) {
1296         unlink $old or die "$old: $!";
1297     }
1298
1299     my $showsrc = cmdoutput aptget_aptcache(), qw(showsrc), $package;
1300     return () unless $showsrc =~ m/^package:\s*\Q$package\E\s*$/mi;
1301     # avoids apt-get source failing with ambiguous error code
1302
1303     runcmd_ordryrun_local
1304         shell_cmd 'cd "$1"/source; shift', $aptget_base,
1305         aptget_aptget(), qw(--download-only --only-source source), $package;
1306
1307     my @dscs = <$aptget_base/source/*.dsc>;
1308     fail "apt-get source did not produce a .dsc" unless @dscs;
1309     fail "apt-get source produced several .dscs (@dscs)" unless @dscs==1;
1310
1311     my $pre_dsc = parsecontrol $dscs[0], $dscs[0], 1;
1312
1313     use URI::Escape;
1314     my $uri = "file://". uri_escape $dscs[0];
1315     $uri =~ s{\%2f}{/}gi;
1316     return [ (getfield $pre_dsc, 'Version'), $uri ];
1317 }
1318
1319 #---------- `dummyapicat' archive query method ----------
1320
1321 sub archive_query_dummycatapi { archive_query_ftpmasterapi @_; }
1322 sub canonicalise_suite_dummycatapi { canonicalise_suite_ftpmasterapi @_; }
1323
1324 sub file_in_archive_dummycatapi ($$$) {
1325     my ($proto,$data,$filename) = @_;
1326     my $mirror = access_cfg('mirror');
1327     $mirror =~ s#^file://#/# or die "$mirror ?";
1328     my @out;
1329     my @cmd = (qw(sh -ec), '
1330             cd "$1"
1331             find -name "$2" -print0 |
1332             xargs -0r sha256sum
1333         ', qw(x), $mirror, $filename);
1334     debugcmd "-|", @cmd;
1335     open FIA, "-|", @cmd or die $!;
1336     while (<FIA>) {
1337         chomp or die;
1338         printdebug "| $_\n";
1339         m/^(\w+)  (\S+)$/ or die "$_ ?";
1340         push @out, { sha256sum => $1, filename => $2 };
1341     }
1342     close FIA or die failedcmd @cmd;
1343     return \@out;
1344 }
1345
1346 #---------- `madison' archive query method ----------
1347
1348 sub archive_query_madison {
1349     return archive_query_prepend_mirror
1350         map { [ @$_[0..1] ] } madison_get_parse(@_);
1351 }
1352
1353 sub madison_get_parse {
1354     my ($proto,$data) = @_;
1355     die unless $proto eq 'madison';
1356     if (!length $data) {
1357         $data= access_cfg('madison-distro','RETURN-UNDEF');
1358         $data //= access_basedistro();
1359     }
1360     $rmad{$proto,$data,$package} ||= cmdoutput
1361         qw(rmadison -asource),"-s$isuite","-u$data",$package;
1362     my $rmad = $rmad{$proto,$data,$package};
1363
1364     my @out;
1365     foreach my $l (split /\n/, $rmad) {
1366         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
1367                   \s*( [^ \t|]+ )\s* \|
1368                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
1369                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
1370         $1 eq $package or die "$rmad $package ?";
1371         my $vsn = $2;
1372         my $newsuite = $3;
1373         my $component;
1374         if (defined $4) {
1375             $component = $4;
1376         } else {
1377             $component = access_cfg('archive-query-default-component');
1378         }
1379         $5 eq 'source' or die "$rmad ?";
1380         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1381     }
1382     return sort { -version_compare($a->[0],$b->[0]); } @out;
1383 }
1384
1385 sub canonicalise_suite_madison {
1386     # madison canonicalises for us
1387     my @r = madison_get_parse(@_);
1388     @r or fail
1389         "unable to canonicalise suite using package $package".
1390         " which does not appear to exist in suite $isuite;".
1391         " --existing-package may help";
1392     return $r[0][2];
1393 }
1394
1395 sub file_in_archive_madison { return undef; }
1396
1397 #---------- `sshpsql' archive query method ----------
1398
1399 sub sshpsql ($$$) {
1400     my ($data,$runeinfo,$sql) = @_;
1401     if (!length $data) {
1402         $data= access_someuserhost('sshpsql').':'.
1403             access_cfg('sshpsql-dbname');
1404     }
1405     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1406     my ($userhost,$dbname) = ($`,$'); #';
1407     my @rows;
1408     my @cmd = (access_cfg_ssh, $userhost,
1409                access_runeinfo("ssh-psql $runeinfo").
1410                " export LC_MESSAGES=C; export LC_CTYPE=C;".
1411                " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1412     debugcmd "|",@cmd;
1413     open P, "-|", @cmd or die $!;
1414     while (<P>) {
1415         chomp or die;
1416         printdebug(">|$_|\n");
1417         push @rows, $_;
1418     }
1419     $!=0; $?=0; close P or failedcmd @cmd;
1420     @rows or die;
1421     my $nrows = pop @rows;
1422     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1423     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1424     @rows = map { [ split /\|/, $_ ] } @rows;
1425     my $ncols = scalar @{ shift @rows };
1426     die if grep { scalar @$_ != $ncols } @rows;
1427     return @rows;
1428 }
1429
1430 sub sql_injection_check {
1431     foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1432 }
1433
1434 sub archive_query_sshpsql ($$) {
1435     my ($proto,$data) = @_;
1436     sql_injection_check $isuite, $package;
1437     my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1438         SELECT source.version, component.name, files.filename, files.sha256sum
1439           FROM source
1440           JOIN src_associations ON source.id = src_associations.source
1441           JOIN suite ON suite.id = src_associations.suite
1442           JOIN dsc_files ON dsc_files.source = source.id
1443           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1444           JOIN component ON component.id = files_archive_map.component_id
1445           JOIN files ON files.id = dsc_files.file
1446          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1447            AND source.source='$package'
1448            AND files.filename LIKE '%.dsc';
1449 END
1450     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1451     my $digester = Digest::SHA->new(256);
1452     @rows = map {
1453         my ($vsn,$component,$filename,$sha256sum) = @$_;
1454         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1455     } @rows;
1456     return archive_query_prepend_mirror @rows;
1457 }
1458
1459 sub canonicalise_suite_sshpsql ($$) {
1460     my ($proto,$data) = @_;
1461     sql_injection_check $isuite;
1462     my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1463         SELECT suite.codename
1464           FROM suite where suite_name='$isuite' or codename='$isuite';
1465 END
1466     @rows = map { $_->[0] } @rows;
1467     fail "unknown suite $isuite" unless @rows;
1468     die "ambiguous $isuite: @rows ?" if @rows>1;
1469     return $rows[0];
1470 }
1471
1472 sub file_in_archive_sshpsql ($$$) { return undef; }
1473
1474 #---------- `dummycat' archive query method ----------
1475
1476 sub canonicalise_suite_dummycat ($$) {
1477     my ($proto,$data) = @_;
1478     my $dpath = "$data/suite.$isuite";
1479     if (!open C, "<", $dpath) {
1480         $!==ENOENT or die "$dpath: $!";
1481         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1482         return $isuite;
1483     }
1484     $!=0; $_ = <C>;
1485     chomp or die "$dpath: $!";
1486     close C;
1487     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1488     return $_;
1489 }
1490
1491 sub archive_query_dummycat ($$) {
1492     my ($proto,$data) = @_;
1493     canonicalise_suite();
1494     my $dpath = "$data/package.$csuite.$package";
1495     if (!open C, "<", $dpath) {
1496         $!==ENOENT or die "$dpath: $!";
1497         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1498         return ();
1499     }
1500     my @rows;
1501     while (<C>) {
1502         next if m/^\#/;
1503         next unless m/\S/;
1504         die unless chomp;
1505         printdebug "dummycat query $csuite $package $dpath | $_\n";
1506         my @row = split /\s+/, $_;
1507         @row==2 or die "$dpath: $_ ?";
1508         push @rows, \@row;
1509     }
1510     C->error and die "$dpath: $!";
1511     close C;
1512     return archive_query_prepend_mirror
1513         sort { -version_compare($a->[0],$b->[0]); } @rows;
1514 }
1515
1516 sub file_in_archive_dummycat () { return undef; }
1517
1518 #---------- tag format handling ----------
1519
1520 sub access_cfg_tagformats () {
1521     split /\,/, access_cfg('dgit-tag-format');
1522 }
1523
1524 sub access_cfg_tagformats_can_splitbrain () {
1525     my %y = map { $_ => 1 } access_cfg_tagformats;
1526     foreach my $needtf (qw(new maint)) {
1527         next if $y{$needtf};
1528         return 0;
1529     }
1530     return 1;
1531 }
1532
1533 sub need_tagformat ($$) {
1534     my ($fmt, $why) = @_;
1535     fail "need to use tag format $fmt ($why) but also need".
1536         " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1537         " - no way to proceed"
1538         if $tagformat_want && $tagformat_want->[0] ne $fmt;
1539     $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1540 }
1541
1542 sub select_tagformat () {
1543     # sets $tagformatfn
1544     return if $tagformatfn && !$tagformat_want;
1545     die 'bug' if $tagformatfn && $tagformat_want;
1546     # ... $tagformat_want assigned after previous select_tagformat
1547
1548     my (@supported) = grep { $_ =~ m/^(?:old|new)$/ } access_cfg_tagformats();
1549     printdebug "select_tagformat supported @supported\n";
1550
1551     $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1552     printdebug "select_tagformat specified @$tagformat_want\n";
1553
1554     my ($fmt,$why,$override) = @$tagformat_want;
1555
1556     fail "target distro supports tag formats @supported".
1557         " but have to use $fmt ($why)"
1558         unless $override
1559             or grep { $_ eq $fmt } @supported;
1560
1561     $tagformat_want = undef;
1562     $tagformat = $fmt;
1563     $tagformatfn = ${*::}{"debiantag_$fmt"};
1564
1565     fail "trying to use unknown tag format \`$fmt' ($why) !"
1566         unless $tagformatfn;
1567 }
1568
1569 #---------- archive query entrypoints and rest of program ----------
1570
1571 sub canonicalise_suite () {
1572     return if defined $csuite;
1573     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1574     $csuite = archive_query('canonicalise_suite');
1575     if ($isuite ne $csuite) {
1576         progress "canonical suite name for $isuite is $csuite";
1577     } else {
1578         progress "canonical suite name is $csuite";
1579     }
1580 }
1581
1582 sub get_archive_dsc () {
1583     canonicalise_suite();
1584     my @vsns = archive_query('archive_query');
1585     foreach my $vinfo (@vsns) {
1586         my ($vsn,$vsn_dscurl,$digester,$digest) = @$vinfo;
1587         $dscurl = $vsn_dscurl;
1588         $dscdata = url_get($dscurl);
1589         if (!$dscdata) {
1590             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1591             next;
1592         }
1593         if ($digester) {
1594             $digester->reset();
1595             $digester->add($dscdata);
1596             my $got = $digester->hexdigest();
1597             $got eq $digest or
1598                 fail "$dscurl has hash $got but".
1599                     " archive told us to expect $digest";
1600         }
1601         parse_dscdata();
1602         my $fmt = getfield $dsc, 'Format';
1603         $format_ok{$fmt} or forceable_fail [qw(unsupported-source-format)],
1604             "unsupported source format $fmt, sorry";
1605             
1606         $dsc_checked = !!$digester;
1607         printdebug "get_archive_dsc: Version ".(getfield $dsc, 'Version')."\n";
1608         return;
1609     }
1610     $dsc = undef;
1611     printdebug "get_archive_dsc: nothing in archive, returning undef\n";
1612 }
1613
1614 sub check_for_git ();
1615 sub check_for_git () {
1616     # returns 0 or 1
1617     my $how = access_cfg('git-check');
1618     if ($how eq 'ssh-cmd') {
1619         my @cmd =
1620             (access_cfg_ssh, access_gituserhost(),
1621              access_runeinfo("git-check $package").
1622              " set -e; cd ".access_cfg('git-path').";".
1623              " if test -d $package.git; then echo 1; else echo 0; fi");
1624         my $r= cmdoutput @cmd;
1625         if (defined $r and $r =~ m/^divert (\w+)$/) {
1626             my $divert=$1;
1627             my ($usedistro,) = access_distros();
1628             # NB that if we are pushing, $usedistro will be $distro/push
1629             $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1630             $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1631             progress "diverting to $divert (using config for $instead_distro)";
1632             return check_for_git();
1633         }
1634         failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1635         return $r+0;
1636     } elsif ($how eq 'url') {
1637         my $prefix = access_cfg('git-check-url','git-url');
1638         my $suffix = access_cfg('git-check-suffix','git-suffix',
1639                                 'RETURN-UNDEF') // '.git';
1640         my $url = "$prefix/$package$suffix";
1641         my @cmd = (@curl, qw(-sS -I), $url);
1642         my $result = cmdoutput @cmd;
1643         $result =~ s/^\S+ 200 .*\n\r?\n//;
1644         # curl -sS -I with https_proxy prints
1645         # HTTP/1.0 200 Connection established
1646         $result =~ m/^\S+ (404|200) /s or
1647             fail "unexpected results from git check query - ".
1648                 Dumper($prefix, $result);
1649         my $code = $1;
1650         if ($code eq '404') {
1651             return 0;
1652         } elsif ($code eq '200') {
1653             return 1;
1654         } else {
1655             die;
1656         }
1657     } elsif ($how eq 'true') {
1658         return 1;
1659     } elsif ($how eq 'false') {
1660         return 0;
1661     } else {
1662         badcfg "unknown git-check \`$how'";
1663     }
1664 }
1665
1666 sub create_remote_git_repo () {
1667     my $how = access_cfg('git-create');
1668     if ($how eq 'ssh-cmd') {
1669         runcmd_ordryrun
1670             (access_cfg_ssh, access_gituserhost(),
1671              access_runeinfo("git-create $package").
1672              "set -e; cd ".access_cfg('git-path').";".
1673              " cp -a _template $package.git");
1674     } elsif ($how eq 'true') {
1675         # nothing to do
1676     } else {
1677         badcfg "unknown git-create \`$how'";
1678     }
1679 }
1680
1681 our ($dsc_hash,$lastpush_mergeinput);
1682
1683 our $ud = '.git/dgit/unpack';
1684
1685 sub prep_ud (;$) {
1686     my ($d) = @_;
1687     $d //= $ud;
1688     rmtree($d);
1689     mkpath '.git/dgit';
1690     mkdir $d or die $!;
1691 }
1692
1693 sub mktree_in_ud_here () {
1694     runcmd qw(git init -q);
1695     runcmd qw(git config gc.auto 0);
1696     rmtree('.git/objects');
1697     symlink '../../../../objects','.git/objects' or die $!;
1698 }
1699
1700 sub git_write_tree () {
1701     my $tree = cmdoutput @git, qw(write-tree);
1702     $tree =~ m/^\w+$/ or die "$tree ?";
1703     return $tree;
1704 }
1705
1706 sub git_add_write_tree () {
1707     runcmd @git, qw(add -Af .);
1708     return git_write_tree();
1709 }
1710
1711 sub remove_stray_gits ($) {
1712     my ($what) = @_;
1713     my @gitscmd = qw(find -name .git -prune -print0);
1714     debugcmd "|",@gitscmd;
1715     open GITS, "-|", @gitscmd or die $!;
1716     {
1717         local $/="\0";
1718         while (<GITS>) {
1719             chomp or die;
1720             print STDERR "$us: warning: removing from $what: ",
1721                 (messagequote $_), "\n";
1722             rmtree $_;
1723         }
1724     }
1725     $!=0; $?=0; close GITS or failedcmd @gitscmd;
1726 }
1727
1728 sub mktree_in_ud_from_only_subdir ($;$) {
1729     my ($what,$raw) = @_;
1730
1731     # changes into the subdir
1732     my (@dirs) = <*/.>;
1733     die "expected one subdir but found @dirs ?" unless @dirs==1;
1734     $dirs[0] =~ m#^([^/]+)/\.$# or die;
1735     my $dir = $1;
1736     changedir $dir;
1737
1738     remove_stray_gits($what);
1739     mktree_in_ud_here();
1740     if (!$raw) {
1741         my ($format, $fopts) = get_source_format();
1742         if (madformat($format)) {
1743             rmtree '.pc';
1744         }
1745     }
1746
1747     my $tree=git_add_write_tree();
1748     return ($tree,$dir);
1749 }
1750
1751 our @files_csum_info_fields = 
1752     (['Checksums-Sha256','Digest::SHA', 'new(256)', 'sha256sum'],
1753      ['Checksums-Sha1',  'Digest::SHA', 'new(1)',   'sha1sum'],
1754      ['Files',           'Digest::MD5', 'new()',    'md5sum']);
1755
1756 sub dsc_files_info () {
1757     foreach my $csumi (@files_csum_info_fields) {
1758         my ($fname, $module, $method) = @$csumi;
1759         my $field = $dsc->{$fname};
1760         next unless defined $field;
1761         eval "use $module; 1;" or die $@;
1762         my @out;
1763         foreach (split /\n/, $field) {
1764             next unless m/\S/;
1765             m/^(\w+) (\d+) (\S+)$/ or
1766                 fail "could not parse .dsc $fname line \`$_'";
1767             my $digester = eval "$module"."->$method;" or die $@;
1768             push @out, {
1769                 Hash => $1,
1770                 Bytes => $2,
1771                 Filename => $3,
1772                 Digester => $digester,
1773             };
1774         }
1775         return @out;
1776     }
1777     fail "missing any supported Checksums-* or Files field in ".
1778         $dsc->get_option('name');
1779 }
1780
1781 sub dsc_files () {
1782     map { $_->{Filename} } dsc_files_info();
1783 }
1784
1785 sub files_compare_inputs (@) {
1786     my $inputs = \@_;
1787     my %record;
1788     my %fchecked;
1789
1790     my $showinputs = sub {
1791         return join "; ", map { $_->get_option('name') } @$inputs;
1792     };
1793
1794     foreach my $in (@$inputs) {
1795         my $expected_files;
1796         my $in_name = $in->get_option('name');
1797
1798         printdebug "files_compare_inputs $in_name\n";
1799
1800         foreach my $csumi (@files_csum_info_fields) {
1801             my ($fname) = @$csumi;
1802             printdebug "files_compare_inputs $in_name $fname\n";
1803
1804             my $field = $in->{$fname};
1805             next unless defined $field;
1806
1807             my @files;
1808             foreach (split /\n/, $field) {
1809                 next unless m/\S/;
1810
1811                 my ($info, $f) = m/^(\w+ \d+) (?:\S+ \S+ )?(\S+)$/ or
1812                     fail "could not parse $in_name $fname line \`$_'";
1813
1814                 printdebug "files_compare_inputs $in_name $fname $f\n";
1815
1816                 push @files, $f;
1817
1818                 my $re = \ $record{$f}{$fname};
1819                 if (defined $$re) {
1820                     $fchecked{$f}{$in_name} = 1;
1821                     $$re eq $info or
1822                         fail "hash or size of $f varies in $fname fields".
1823                         " (between: ".$showinputs->().")";
1824                 } else {
1825                     $$re = $info;
1826                 }
1827             }
1828             @files = sort @files;
1829             $expected_files //= \@files;
1830             "@$expected_files" eq "@files" or
1831                 fail "file list in $in_name varies between hash fields!";
1832         }
1833         $expected_files or
1834             fail "$in_name has no files list field(s)";
1835     }
1836     printdebug "files_compare_inputs ".Dumper(\%fchecked, \%record)
1837         if $debuglevel>=2;
1838
1839     grep { keys %$_ == @$inputs-1 } values %fchecked
1840         or fail "no file appears in all file lists".
1841         " (looked in: ".$showinputs->().")";
1842 }
1843
1844 sub is_orig_file_in_dsc ($$) {
1845     my ($f, $dsc_files_info) = @_;
1846     return 0 if @$dsc_files_info <= 1;
1847     # One file means no origs, and the filename doesn't have a "what
1848     # part of dsc" component.  (Consider versions ending `.orig'.)
1849     return 0 unless $f =~ m/\.$orig_f_tail_re$/o;
1850     return 1;
1851 }
1852
1853 sub is_orig_file_of_vsn ($$) {
1854     my ($f, $upstreamvsn) = @_;
1855     my $base = srcfn $upstreamvsn, '';
1856     return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
1857     return 1;
1858 }
1859
1860 sub changes_update_origs_from_dsc ($$$$) {
1861     my ($dsc, $changes, $upstreamvsn, $changesfile) = @_;
1862     my %changes_f;
1863     printdebug "checking origs needed ($upstreamvsn)...\n";
1864     $_ = getfield $changes, 'Files';
1865     m/^\w+ \d+ (\S+ \S+) \S+$/m or
1866         fail "cannot find section/priority from .changes Files field";
1867     my $placementinfo = $1;
1868     my %changed;
1869     printdebug "checking origs needed placement '$placementinfo'...\n";
1870     foreach my $l (split /\n/, getfield $dsc, 'Files') {
1871         $l =~ m/\S+$/ or next;
1872         my $file = $&;
1873         printdebug "origs $file | $l\n";
1874         next unless is_orig_file_of_vsn $file, $upstreamvsn;
1875         printdebug "origs $file is_orig\n";
1876         my $have = archive_query('file_in_archive', $file);
1877         if (!defined $have) {
1878             print STDERR <<END;
1879 archive does not support .orig check; hope you used --ch:--sa/-sd if needed
1880 END
1881             return;
1882         }
1883         my $found_same = 0;
1884         my @found_differ;
1885         printdebug "origs $file \$#\$have=$#$have\n";
1886         foreach my $h (@$have) {
1887             my $same = 0;
1888             my @differ;
1889             foreach my $csumi (@files_csum_info_fields) {
1890                 my ($fname, $module, $method, $archivefield) = @$csumi;
1891                 next unless defined $h->{$archivefield};
1892                 $_ = $dsc->{$fname};
1893                 next unless defined;
1894                 m/^(\w+) .* \Q$file\E$/m or
1895                     fail ".dsc $fname missing entry for $file";
1896                 if ($h->{$archivefield} eq $1) {
1897                     $same++;
1898                 } else {
1899                     push @differ,
1900  "$archivefield: $h->{$archivefield} (archive) != $1 (local .dsc)";
1901                 }
1902             }
1903             die "$file ".Dumper($h)." ?!" if $same && @differ;
1904             $found_same++
1905                 if $same;
1906             push @found_differ, "archive $h->{filename}: ".join "; ", @differ
1907                 if @differ;
1908         }
1909         printdebug "origs $file f.same=$found_same".
1910             " #f._differ=$#found_differ\n";
1911         if (@found_differ && !$found_same) {
1912             fail join "\n",
1913                 "archive contains $file with different checksum",
1914                 @found_differ;
1915         }
1916         # Now we edit the changes file to add or remove it
1917         foreach my $csumi (@files_csum_info_fields) {
1918             my ($fname, $module, $method, $archivefield) = @$csumi;
1919             next unless defined $changes->{$fname};
1920             if ($found_same) {
1921                 # in archive, delete from .changes if it's there
1922                 $changed{$file} = "removed" if
1923                     $changes->{$fname} =~ s/^.* \Q$file\E$(?:)\n//m;
1924             } elsif ($changes->{$fname} =~ m/^.* \Q$file\E$(?:)\n/m) {
1925                 # not in archive, but it's here in the .changes
1926             } else {
1927                 my $dsc_data = getfield $dsc, $fname;
1928                 $dsc_data =~ m/^(.* \Q$file\E$)\n/m or die "$dsc_data $file ?";
1929                 my $extra = $1;
1930                 $extra =~ s/ \d+ /$&$placementinfo /
1931                     or die "$fname $extra >$dsc_data< ?"
1932                     if $fname eq 'Files';
1933                 $changes->{$fname} .= "\n". $extra;
1934                 $changed{$file} = "added";
1935             }
1936         }
1937     }
1938     if (%changed) {
1939         foreach my $file (keys %changed) {
1940             progress sprintf
1941                 "edited .changes for archive .orig contents: %s %s",
1942                 $changed{$file}, $file;
1943         }
1944         my $chtmp = "$changesfile.tmp";
1945         $changes->save($chtmp);
1946         if (act_local()) {
1947             rename $chtmp,$changesfile or die "$changesfile $!";
1948         } else {
1949             progress "[new .changes left in $changesfile]";
1950         }
1951     } else {
1952         progress "$changesfile already has appropriate .orig(s) (if any)";
1953     }
1954 }
1955
1956 sub make_commit ($) {
1957     my ($file) = @_;
1958     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1959 }
1960
1961 sub make_commit_text ($) {
1962     my ($text) = @_;
1963     my ($out, $in);
1964     my @cmd = (@git, qw(hash-object -w -t commit --stdin));
1965     debugcmd "|",@cmd;
1966     print Dumper($text) if $debuglevel > 1;
1967     my $child = open2($out, $in, @cmd) or die $!;
1968     my $h;
1969     eval {
1970         print $in $text or die $!;
1971         close $in or die $!;
1972         $h = <$out>;
1973         $h =~ m/^\w+$/ or die;
1974         $h = $&;
1975         printdebug "=> $h\n";
1976     };
1977     close $out;
1978     waitpid $child, 0 == $child or die "$child $!";
1979     $? and failedcmd @cmd;
1980     return $h;
1981 }
1982
1983 sub clogp_authline ($) {
1984     my ($clogp) = @_;
1985     my $author = getfield $clogp, 'Maintainer';
1986     $author =~ s#,.*##ms;
1987     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1988     my $authline = "$author $date";
1989     $authline =~ m/$git_authline_re/o or
1990         fail "unexpected commit author line format \`$authline'".
1991         " (was generated from changelog Maintainer field)";
1992     return ($1,$2,$3) if wantarray;
1993     return $authline;
1994 }
1995
1996 sub vendor_patches_distro ($$) {
1997     my ($checkdistro, $what) = @_;
1998     return unless defined $checkdistro;
1999
2000     my $series = "debian/patches/\L$checkdistro\E.series";
2001     printdebug "checking for vendor-specific $series ($what)\n";
2002
2003     if (!open SERIES, "<", $series) {
2004         die "$series $!" unless $!==ENOENT;
2005         return;
2006     }
2007     while (<SERIES>) {
2008         next unless m/\S/;
2009         next if m/^\s+\#/;
2010
2011         print STDERR <<END;
2012
2013 Unfortunately, this source package uses a feature of dpkg-source where
2014 the same source package unpacks to different source code on different
2015 distros.  dgit cannot safely operate on such packages on affected
2016 distros, because the meaning of source packages is not stable.
2017
2018 Please ask the distro/maintainer to remove the distro-specific series
2019 files and use a different technique (if necessary, uploading actually
2020 different packages, if different distros are supposed to have
2021 different code).
2022
2023 END
2024         fail "Found active distro-specific series file for".
2025             " $checkdistro ($what): $series, cannot continue";
2026     }
2027     die "$series $!" if SERIES->error;
2028     close SERIES;
2029 }
2030
2031 sub check_for_vendor_patches () {
2032     # This dpkg-source feature doesn't seem to be documented anywhere!
2033     # But it can be found in the changelog (reformatted):
2034
2035     #   commit  4fa01b70df1dc4458daee306cfa1f987b69da58c
2036     #   Author: Raphael Hertzog <hertzog@debian.org>
2037     #   Date: Sun  Oct  3  09:36:48  2010 +0200
2038
2039     #   dpkg-source: correctly create .pc/.quilt_series with alternate
2040     #   series files
2041     #   
2042     #   If you have debian/patches/ubuntu.series and you were
2043     #   unpacking the source package on ubuntu, quilt was still
2044     #   directed to debian/patches/series instead of
2045     #   debian/patches/ubuntu.series.
2046     #   
2047     #   debian/changelog                        |    3 +++
2048     #   scripts/Dpkg/Source/Package/V3/quilt.pm |    4 +++-
2049     #   2 files changed, 6 insertions(+), 1 deletion(-)
2050
2051     use Dpkg::Vendor;
2052     vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
2053     vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
2054                          "Dpkg::Vendor \`current vendor'");
2055     vendor_patches_distro(access_basedistro(),
2056                           "(base) distro being accessed");
2057     vendor_patches_distro(access_nomdistro(),
2058                           "(nominal) distro being accessed");
2059 }
2060
2061 sub generate_commits_from_dsc () {
2062     # See big comment in fetch_from_archive, below.
2063     # See also README.dsc-import.
2064     prep_ud();
2065     changedir $ud;
2066
2067     my @dfi = dsc_files_info();
2068     foreach my $fi (@dfi) {
2069         my $f = $fi->{Filename};
2070         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
2071
2072         printdebug "considering linking $f: ";
2073
2074         link_ltarget "../../../../$f", $f
2075             or ((printdebug "($!) "), 0)
2076             or $!==&ENOENT
2077             or die "$f $!";
2078
2079         printdebug "linked.\n";
2080
2081         complete_file_from_dsc('.', $fi)
2082             or next;
2083
2084         if (is_orig_file_in_dsc($f, \@dfi)) {
2085             link $f, "../../../../$f"
2086                 or $!==&EEXIST
2087                 or die "$f $!";
2088         }
2089     }
2090
2091     # We unpack and record the orig tarballs first, so that we only
2092     # need disk space for one private copy of the unpacked source.
2093     # But we can't make them into commits until we have the metadata
2094     # from the debian/changelog, so we record the tree objects now and
2095     # make them into commits later.
2096     my @tartrees;
2097     my $upstreamv = upstreamversion $dsc->{version};
2098     my $orig_f_base = srcfn $upstreamv, '';
2099
2100     foreach my $fi (@dfi) {
2101         # We actually import, and record as a commit, every tarball
2102         # (unless there is only one file, in which case there seems
2103         # little point.
2104
2105         my $f = $fi->{Filename};
2106         printdebug "import considering $f ";
2107         (printdebug "only one dfi\n"), next if @dfi == 1;
2108         (printdebug "not tar\n"), next unless $f =~ m/\.tar(\.\w+)?$/;
2109         (printdebug "signature\n"), next if $f =~ m/$orig_f_sig_re$/o;
2110         my $compr_ext = $1;
2111
2112         my ($orig_f_part) =
2113             $f =~ m/^\Q$orig_f_base\E\.([^._]+)?\.tar(?:\.\w+)?$/;
2114
2115         printdebug "Y ", (join ' ', map { $_//"(none)" }
2116                           $compr_ext, $orig_f_part
2117                          ), "\n";
2118
2119         my $input = new IO::File $f, '<' or die "$f $!";
2120         my $compr_pid;
2121         my @compr_cmd;
2122
2123         if (defined $compr_ext) {
2124             my $cname =
2125                 Dpkg::Compression::compression_guess_from_filename $f;
2126             fail "Dpkg::Compression cannot handle file $f in source package"
2127                 if defined $compr_ext && !defined $cname;
2128             my $compr_proc =
2129                 new Dpkg::Compression::Process compression => $cname;
2130             my @compr_cmd = $compr_proc->get_uncompress_cmdline();
2131             my $compr_fh = new IO::Handle;
2132             my $compr_pid = open $compr_fh, "-|" // die $!;
2133             if (!$compr_pid) {
2134                 open STDIN, "<&", $input or die $!;
2135                 exec @compr_cmd;
2136                 die "dgit (child): exec $compr_cmd[0]: $!\n";
2137             }
2138             $input = $compr_fh;
2139         }
2140
2141         rmtree "_unpack-tar";
2142         mkdir "_unpack-tar" or die $!;
2143         my @tarcmd = qw(tar -x -f -
2144                         --no-same-owner --no-same-permissions
2145                         --no-acls --no-xattrs --no-selinux);
2146         my $tar_pid = fork // die $!;
2147         if (!$tar_pid) {
2148             chdir "_unpack-tar" or die $!;
2149             open STDIN, "<&", $input or die $!;
2150             exec @tarcmd;
2151             die "dgit (child): exec $tarcmd[0]: $!";
2152         }
2153         $!=0; (waitpid $tar_pid, 0) == $tar_pid or die $!;
2154         !$? or failedcmd @tarcmd;
2155
2156         close $input or
2157             (@compr_cmd ? failedcmd @compr_cmd
2158              : die $!);
2159         # finally, we have the results in "tarball", but maybe
2160         # with the wrong permissions
2161
2162         runcmd qw(chmod -R +rwX _unpack-tar);
2163         changedir "_unpack-tar";
2164         remove_stray_gits($f);
2165         mktree_in_ud_here();
2166         
2167         my ($tree) = git_add_write_tree();
2168         my $tentries = cmdoutput @git, qw(ls-tree -z), $tree;
2169         if ($tentries =~ m/^\d+ tree (\w+)\t[^\000]+\000$/s) {
2170             $tree = $1;
2171             printdebug "one subtree $1\n";
2172         } else {
2173             printdebug "multiple subtrees\n";
2174         }
2175         changedir "..";
2176         rmtree "_unpack-tar";
2177
2178         my $ent = [ $f, $tree ];
2179         push @tartrees, {
2180             Orig => !!$orig_f_part,
2181             Sort => (!$orig_f_part         ? 2 :
2182                      $orig_f_part =~ m/-/g ? 1 :
2183                                              0),
2184             F => $f,
2185             Tree => $tree,
2186         };
2187     }
2188
2189     @tartrees = sort {
2190         # put any without "_" first (spec is not clear whether files
2191         # are always in the usual order).  Tarballs without "_" are
2192         # the main orig or the debian tarball.
2193         $a->{Sort} <=> $b->{Sort} or
2194         $a->{F}    cmp $b->{F}
2195     } @tartrees;
2196
2197     my $any_orig = grep { $_->{Orig} } @tartrees;
2198
2199     my $dscfn = "$package.dsc";
2200
2201     my $treeimporthow = 'package';
2202
2203     open D, ">", $dscfn or die "$dscfn: $!";
2204     print D $dscdata or die "$dscfn: $!";
2205     close D or die "$dscfn: $!";
2206     my @cmd = qw(dpkg-source);
2207     push @cmd, '--no-check' if $dsc_checked;
2208     if (madformat $dsc->{format}) {
2209         push @cmd, '--skip-patches';
2210         $treeimporthow = 'unpatched';
2211     }
2212     push @cmd, qw(-x --), $dscfn;
2213     runcmd @cmd;
2214
2215     my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
2216     if (madformat $dsc->{format}) { 
2217         check_for_vendor_patches();
2218     }
2219
2220     my $dappliedtree;
2221     if (madformat $dsc->{format}) {
2222         my @pcmd = qw(dpkg-source --before-build .);
2223         runcmd shell_cmd 'exec >/dev/null', @pcmd;
2224         rmtree '.pc';
2225         $dappliedtree = git_add_write_tree();
2226     }
2227
2228     my @clogcmd = qw(dpkg-parsechangelog --format rfc822 --all);
2229     debugcmd "|",@clogcmd;
2230     open CLOGS, "-|", @clogcmd or die $!;
2231
2232     my $clogp;
2233     my $r1clogp;
2234
2235     printdebug "import clog search...\n";
2236
2237     for (;;) {
2238         my $stanzatext = do { local $/=""; <CLOGS>; };
2239         printdebug "import clogp ".Dumper($stanzatext) if $debuglevel>1;
2240         last if !defined $stanzatext;
2241
2242         my $desc = "package changelog, entry no.$.";
2243         open my $stanzafh, "<", \$stanzatext or die;
2244         my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
2245         $clogp //= $thisstanza;
2246
2247         printdebug "import clog $thisstanza->{version} $desc...\n";
2248
2249         last if !$any_orig; # we don't need $r1clogp
2250
2251         # We look for the first (most recent) changelog entry whose
2252         # version number is lower than the upstream version of this
2253         # package.  Then the last (least recent) previous changelog
2254         # entry is treated as the one which introduced this upstream
2255         # version and used for the synthetic commits for the upstream
2256         # tarballs.
2257
2258         # One might think that a more sophisticated algorithm would be
2259         # necessary.  But: we do not want to scan the whole changelog
2260         # file.  Stopping when we see an earlier version, which
2261         # necessarily then is an earlier upstream version, is the only
2262         # realistic way to do that.  Then, either the earliest
2263         # changelog entry we have seen so far is indeed the earliest
2264         # upload of this upstream version; or there are only changelog
2265         # entries relating to later upstream versions (which is not
2266         # possible unless the changelog and .dsc disagree about the
2267         # version).  Then it remains to choose between the physically
2268         # last entry in the file, and the one with the lowest version
2269         # number.  If these are not the same, we guess that the
2270         # versions were created in a non-monotic order rather than
2271         # that the changelog entries have been misordered.
2272
2273         printdebug "import clog $thisstanza->{version} vs $upstreamv...\n";
2274
2275         last if version_compare($thisstanza->{version}, $upstreamv) < 0;
2276         $r1clogp = $thisstanza;
2277
2278         printdebug "import clog $r1clogp->{version} becomes r1\n";
2279     }
2280     die $! if CLOGS->error;
2281     close CLOGS or $?==SIGPIPE or failedcmd @clogcmd;
2282
2283     $clogp or fail "package changelog has no entries!";
2284
2285     my $authline = clogp_authline $clogp;
2286     my $changes = getfield $clogp, 'Changes';
2287     my $cversion = getfield $clogp, 'Version';
2288
2289     if (@tartrees) {
2290         $r1clogp //= $clogp; # maybe there's only one entry;
2291         my $r1authline = clogp_authline $r1clogp;
2292         # Strictly, r1authline might now be wrong if it's going to be
2293         # unused because !$any_orig.  Whatever.
2294
2295         printdebug "import tartrees authline   $authline\n";
2296         printdebug "import tartrees r1authline $r1authline\n";
2297
2298         foreach my $tt (@tartrees) {
2299             printdebug "import tartree $tt->{F} $tt->{Tree}\n";
2300
2301             $tt->{Commit} = make_commit_text($tt->{Orig} ? <<END_O : <<END_T);
2302 tree $tt->{Tree}
2303 author $r1authline
2304 committer $r1authline
2305
2306 Import $tt->{F}
2307
2308 [dgit import orig $tt->{F}]
2309 END_O
2310 tree $tt->{Tree}
2311 author $authline
2312 committer $authline
2313
2314 Import $tt->{F}
2315
2316 [dgit import tarball $package $cversion $tt->{F}]
2317 END_T
2318         }
2319     }
2320
2321     printdebug "import main commit\n";
2322
2323     open C, ">../commit.tmp" or die $!;
2324     print C <<END or die $!;
2325 tree $tree
2326 END
2327     print C <<END or die $! foreach @tartrees;
2328 parent $_->{Commit}
2329 END
2330     print C <<END or die $!;
2331 author $authline
2332 committer $authline
2333
2334 $changes
2335
2336 [dgit import $treeimporthow $package $cversion]
2337 END
2338
2339     close C or die $!;
2340     my $rawimport_hash = make_commit qw(../commit.tmp);
2341
2342     if (madformat $dsc->{format}) {
2343         printdebug "import apply patches...\n";
2344
2345         # regularise the state of the working tree so that
2346         # the checkout of $rawimport_hash works nicely.
2347         my $dappliedcommit = make_commit_text(<<END);
2348 tree $dappliedtree
2349 author $authline
2350 committer $authline
2351
2352 [dgit dummy commit]
2353 END
2354         runcmd @git, qw(checkout -q -b dapplied), $dappliedcommit;
2355
2356         runcmd @git, qw(checkout -q -b unpa), $rawimport_hash;
2357
2358         # We need the answers to be reproducible
2359         my @authline = clogp_authline($clogp);
2360         local $ENV{GIT_COMMITTER_NAME} =  $authline[0];
2361         local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2362         local $ENV{GIT_COMMITTER_DATE} =  $authline[2];
2363         local $ENV{GIT_AUTHOR_NAME} =  $authline[0];
2364         local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
2365         local $ENV{GIT_AUTHOR_DATE} =  $authline[2];
2366
2367         my $path = $ENV{PATH} or die;
2368
2369         foreach my $use_absurd (qw(0 1)) {
2370             local $ENV{PATH} = $path;
2371             if ($use_absurd) {
2372                 chomp $@;
2373                 progress "warning: $@";
2374                 $path = "$absurdity:$path";
2375                 progress "$us: trying slow absurd-git-apply...";
2376                 rename "../../gbp-pq-output","../../gbp-pq-output.0"
2377                     or $!==ENOENT
2378                     or die $!;
2379             }
2380             eval {
2381                 die "forbid absurd git-apply\n" if $use_absurd
2382                     && forceing [qw(import-gitapply-no-absurd)];
2383                 die "only absurd git-apply!\n" if !$use_absurd
2384                     && forceing [qw(import-gitapply-absurd)];
2385
2386                 local $ENV{PATH} = $path if $use_absurd;
2387
2388                 my @showcmd = (gbp_pq, qw(import));
2389                 my @realcmd = shell_cmd
2390                     'exec >/dev/null 2>../../gbp-pq-output', @showcmd;
2391                 debugcmd "+",@realcmd;
2392                 if (system @realcmd) {
2393                     die +(shellquote @showcmd).
2394                         " failed: ".
2395                         failedcmd_waitstatus()."\n";
2396                 }
2397
2398                 my $gapplied = git_rev_parse('HEAD');
2399                 my $gappliedtree = cmdoutput @git, qw(rev-parse HEAD:);
2400                 $gappliedtree eq $dappliedtree or
2401                     fail <<END;
2402 gbp-pq import and dpkg-source disagree!
2403  gbp-pq import gave commit $gapplied
2404  gbp-pq import gave tree $gappliedtree
2405  dpkg-source --before-build gave tree $dappliedtree
2406 END
2407                 $rawimport_hash = $gapplied;
2408             };
2409             last unless $@;
2410         }
2411         if ($@) {
2412             { local $@; eval { runcmd qw(cat ../../gbp-pq-output); }; }
2413             die $@;
2414         }
2415     }
2416
2417     progress "synthesised git commit from .dsc $cversion";
2418
2419     my $rawimport_mergeinput = {
2420         Commit => $rawimport_hash,
2421         Info => "Import of source package",
2422     };
2423     my @output = ($rawimport_mergeinput);
2424
2425     if ($lastpush_mergeinput) {
2426         my $oldclogp = mergeinfo_getclogp($lastpush_mergeinput);
2427         my $oversion = getfield $oldclogp, 'Version';
2428         my $vcmp =
2429             version_compare($oversion, $cversion);
2430         if ($vcmp < 0) {
2431             @output = ($rawimport_mergeinput, $lastpush_mergeinput,
2432                 { Message => <<END, ReverseParents => 1 });
2433 Record $package ($cversion) in archive suite $csuite
2434 END
2435         } elsif ($vcmp > 0) {
2436             print STDERR <<END or die $!;
2437
2438 Version actually in archive:   $cversion (older)
2439 Last version pushed with dgit: $oversion (newer or same)
2440 $later_warning_msg
2441 END
2442             @output = $lastpush_mergeinput;
2443         } else {
2444             # Same version.  Use what's in the server git branch,
2445             # discarding our own import.  (This could happen if the
2446             # server automatically imports all packages into git.)
2447             @output = $lastpush_mergeinput;
2448         }
2449     }
2450     changedir '../../../..';
2451     rmtree($ud);
2452     return @output;
2453 }
2454
2455 sub complete_file_from_dsc ($$) {
2456     our ($dstdir, $fi) = @_;
2457     # Ensures that we have, in $dir, the file $fi, with the correct
2458     # contents.  (Downloading it from alongside $dscurl if necessary.)
2459
2460     my $f = $fi->{Filename};
2461     my $tf = "$dstdir/$f";
2462     my $downloaded = 0;
2463
2464     if (stat_exists $tf) {
2465         progress "using existing $f";
2466     } else {
2467         printdebug "$tf does not exist, need to fetch\n";
2468         my $furl = $dscurl;
2469         $furl =~ s{/[^/]+$}{};
2470         $furl .= "/$f";
2471         die "$f ?" unless $f =~ m/^\Q${package}\E_/;
2472         die "$f ?" if $f =~ m#/#;
2473         runcmd_ordryrun_local @curl,qw(-f -o),$tf,'--',"$furl";
2474         return 0 if !act_local();
2475         $downloaded = 1;
2476     }
2477
2478     open F, "<", "$tf" or die "$tf: $!";
2479     $fi->{Digester}->reset();
2480     $fi->{Digester}->addfile(*F);
2481     F->error and die $!;
2482     my $got = $fi->{Digester}->hexdigest();
2483     $got eq $fi->{Hash} or
2484         fail "file $f has hash $got but .dsc".
2485             " demands hash $fi->{Hash} ".
2486             ($downloaded ? "(got wrong file from archive!)"
2487              : "(perhaps you should delete this file?)");
2488
2489     return 1;
2490 }
2491
2492 sub ensure_we_have_orig () {
2493     my @dfi = dsc_files_info();
2494     foreach my $fi (@dfi) {
2495         my $f = $fi->{Filename};
2496         next unless is_orig_file_in_dsc($f, \@dfi);
2497         complete_file_from_dsc('..', $fi)
2498             or next;
2499     }
2500 }
2501
2502 sub git_fetch_us () {
2503     # Want to fetch only what we are going to use, unless
2504     # deliberately-not-ff, in which case we must fetch everything.
2505
2506     my @specs = deliberately_not_fast_forward ? qw(tags/*) :
2507         map { "tags/$_" }
2508         (quiltmode_splitbrain
2509          ? (map { $_->('*',access_nomdistro) }
2510             \&debiantag_new, \&debiantag_maintview)
2511          : debiantags('*',access_nomdistro));
2512     push @specs, server_branch($csuite);
2513     push @specs, qw(heads/*) if deliberately_not_fast_forward;
2514
2515     # This is rather miserable:
2516     # When git fetch --prune is passed a fetchspec ending with a *,
2517     # it does a plausible thing.  If there is no * then:
2518     # - it matches subpaths too, even if the supplied refspec
2519     #   starts refs, and behaves completely madly if the source
2520     #   has refs/refs/something.  (See, for example, Debian #NNNN.)
2521     # - if there is no matching remote ref, it bombs out the whole
2522     #   fetch.
2523     # We want to fetch a fixed ref, and we don't know in advance
2524     # if it exists, so this is not suitable.
2525     #
2526     # Our workaround is to use git ls-remote.  git ls-remote has its
2527     # own qairks.  Notably, it has the absurd multi-tail-matching
2528     # behaviour: git ls-remote R refs/foo can report refs/foo AND
2529     # refs/refs/foo etc.
2530     #
2531     # Also, we want an idempotent snapshot, but we have to make two
2532     # calls to the remote: one to git ls-remote and to git fetch.  The
2533     # solution is use git ls-remote to obtain a target state, and
2534     # git fetch to try to generate it.  If we don't manage to generate
2535     # the target state, we try again.
2536
2537     printdebug "git_fetch_us specs @specs\n";
2538
2539     my $specre = join '|', map {
2540         my $x = $_;
2541         $x =~ s/\W/\\$&/g;
2542         $x =~ s/\\\*$/.*/;
2543         "(?:refs/$x)";
2544     } @specs;
2545     printdebug "git_fetch_us specre=$specre\n";
2546     my $wanted_rref = sub {
2547         local ($_) = @_;
2548         return m/^(?:$specre)$/o;
2549     };
2550
2551     my $fetch_iteration = 0;
2552     FETCH_ITERATION:
2553     for (;;) {
2554         printdebug "git_fetch_us iteration $fetch_iteration\n";
2555         if (++$fetch_iteration > 10) {
2556             fail "too many iterations trying to get sane fetch!";
2557         }
2558
2559         my @look = map { "refs/$_" } @specs;
2560         my @lcmd = (@git, qw(ls-remote -q --refs), access_giturl(), @look);
2561         debugcmd "|",@lcmd;
2562
2563         my %wantr;
2564         open GITLS, "-|", @lcmd or die $!;
2565         while (<GITLS>) {
2566             printdebug "=> ", $_;
2567             m/^(\w+)\s+(\S+)\n/ or die "ls-remote $_ ?";
2568             my ($objid,$rrefname) = ($1,$2);
2569             if (!$wanted_rref->($rrefname)) {
2570                 print STDERR <<END;
2571 warning: git ls-remote @look reported $rrefname; this is silly, ignoring it.
2572 END
2573                 next;
2574             }
2575             $wantr{$rrefname} = $objid;
2576         }
2577         $!=0; $?=0;
2578         close GITLS or failedcmd @lcmd;
2579
2580         # OK, now %want is exactly what we want for refs in @specs
2581         my @fspecs = map {
2582             !m/\*$/ && !exists $wantr{"refs/$_"} ? () :
2583             "+refs/$_:".lrfetchrefs."/$_";
2584         } @specs;
2585
2586         printdebug "git_fetch_us fspecs @fspecs\n";
2587
2588         my @fcmd = (@git, qw(fetch -p -n -q), access_giturl(), @fspecs);
2589         runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(),
2590             @fspecs;
2591
2592         %lrfetchrefs_f = ();
2593         my %objgot;
2594
2595         git_for_each_ref(lrfetchrefs, sub {
2596             my ($objid,$objtype,$lrefname,$reftail) = @_;
2597             $lrfetchrefs_f{$lrefname} = $objid;
2598             $objgot{$objid} = 1;
2599         });
2600
2601         foreach my $lrefname (sort keys %lrfetchrefs_f) {
2602             my $rrefname = 'refs'.substr($lrefname, length lrfetchrefs);
2603             if (!exists $wantr{$rrefname}) {
2604                 if ($wanted_rref->($rrefname)) {
2605                     printdebug <<END;
2606 git-fetch @fspecs created $lrefname which git ls-remote @look didn't list.
2607 END
2608                 } else {
2609                     print STDERR <<END
2610 warning: git fetch @fspecs created $lrefname; this is silly, deleting it.
2611 END
2612                 }
2613                 runcmd_ordryrun_local @git, qw(update-ref -d), $lrefname;
2614                 delete $lrfetchrefs_f{$lrefname};
2615                 next;
2616             }
2617         }
2618         foreach my $rrefname (sort keys %wantr) {
2619             my $lrefname = lrfetchrefs.substr($rrefname, 4);
2620             my $got = $lrfetchrefs_f{$lrefname} // '<none>';
2621             my $want = $wantr{$rrefname};
2622             next if $got eq $want;
2623             if (!defined $objgot{$want}) {
2624                 print STDERR <<END;
2625 warning: git ls-remote suggests we want $lrefname
2626 warning:  and it should refer to $want
2627 warning:  but git fetch didn't fetch that object to any relevant ref.
2628 warning:  This may be due to a race with someone updating the server.
2629 warning:  Will try again...
2630 END
2631                 next FETCH_ITERATION;
2632             }
2633             printdebug <<END;
2634 git-fetch @fspecs made $lrefname=$got but want git ls-remote @look says $want
2635 END
2636             runcmd_ordryrun_local @git, qw(update-ref -m),
2637                 "dgit fetch git fetch fixup", $lrefname, $want;
2638             $lrfetchrefs_f{$lrefname} = $want;
2639         }
2640         last;
2641     }
2642     printdebug "git_fetch_us: git fetch --no-insane emulation complete\n",
2643         Dumper(\%lrfetchrefs_f);
2644
2645     my %here;
2646     my @tagpats = debiantags('*',access_nomdistro);
2647
2648     git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
2649         my ($objid,$objtype,$fullrefname,$reftail) = @_;
2650         printdebug "currently $fullrefname=$objid\n";
2651         $here{$fullrefname} = $objid;
2652     });
2653     git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
2654         my ($objid,$objtype,$fullrefname,$reftail) = @_;
2655         my $lref = "refs".substr($fullrefname, length(lrfetchrefs));
2656         printdebug "offered $lref=$objid\n";
2657         if (!defined $here{$lref}) {
2658             my @upd = (@git, qw(update-ref), $lref, $objid, '');
2659             runcmd_ordryrun_local @upd;
2660             lrfetchref_used $fullrefname;
2661         } elsif ($here{$lref} eq $objid) {
2662             lrfetchref_used $fullrefname;
2663         } else {
2664             print STDERR \
2665                 "Not updateting $lref from $here{$lref} to $objid.\n";
2666         }
2667     });
2668 }
2669
2670 sub mergeinfo_getclogp ($) {
2671     # Ensures thit $mi->{Clogp} exists and returns it
2672     my ($mi) = @_;
2673     $mi->{Clogp} = commit_getclogp($mi->{Commit});
2674 }
2675
2676 sub mergeinfo_version ($) {
2677     return getfield( (mergeinfo_getclogp $_[0]), 'Version' );
2678 }
2679
2680 sub fetch_from_archive_record_1 ($) {
2681     my ($hash) = @_;
2682     runcmd @git, qw(update-ref -m), "dgit fetch $csuite",
2683             'DGIT_ARCHIVE', $hash;
2684     cmdoutput @git, qw(log -n2), $hash;
2685     # ... gives git a chance to complain if our commit is malformed
2686 }
2687
2688 sub fetch_from_archive_record_2 ($) {
2689     my ($hash) = @_;
2690     my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
2691     if (act_local()) {
2692         cmdoutput @upd_cmd;
2693     } else {
2694         dryrun_report @upd_cmd;
2695     }
2696 }
2697
2698 sub fetch_from_archive () {
2699     ensure_setup_existing_tree();
2700
2701     # Ensures that lrref() is what is actually in the archive, one way
2702     # or another, according to us - ie this client's
2703     # appropritaely-updated archive view.  Also returns the commit id.
2704     # If there is nothing in the archive, leaves lrref alone and
2705     # returns undef.  git_fetch_us must have already been called.
2706     get_archive_dsc();
2707
2708     if ($dsc) {
2709         foreach my $field (@ourdscfield) {
2710             $dsc_hash = $dsc->{$field};
2711             last if defined $dsc_hash;
2712         }
2713         if (defined $dsc_hash) {
2714             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
2715             $dsc_hash = $&;
2716             progress "last upload to archive specified git hash";
2717         } else {
2718             progress "last upload to archive has NO git hash";
2719         }
2720     } else {
2721         progress "no version available from the archive";
2722     }
2723
2724     # If the archive's .dsc has a Dgit field, there are three
2725     # relevant git commitids we need to choose between and/or merge
2726     # together:
2727     #   1. $dsc_hash: the Dgit field from the archive
2728     #   2. $lastpush_hash: the suite branch on the dgit git server
2729     #   3. $lastfetch_hash: our local tracking brach for the suite
2730     #
2731     # These may all be distinct and need not be in any fast forward
2732     # relationship:
2733     #
2734     # If the dsc was pushed to this suite, then the server suite
2735     # branch will have been updated; but it might have been pushed to
2736     # a different suite and copied by the archive.  Conversely a more
2737     # recent version may have been pushed with dgit but not appeared
2738     # in the archive (yet).
2739     #
2740     # $lastfetch_hash may be awkward because archive imports
2741     # (particularly, imports of Dgit-less .dscs) are performed only as
2742     # needed on individual clients, so different clients may perform a
2743     # different subset of them - and these imports are only made
2744     # public during push.  So $lastfetch_hash may represent a set of
2745     # imports different to a subsequent upload by a different dgit
2746     # client.
2747     #
2748     # Our approach is as follows:
2749     #
2750     # As between $dsc_hash and $lastpush_hash: if $lastpush_hash is a
2751     # descendant of $dsc_hash, then it was pushed by a dgit user who
2752     # had based their work on $dsc_hash, so we should prefer it.
2753     # Otherwise, $dsc_hash was installed into this suite in the
2754     # archive other than by a dgit push, and (necessarily) after the
2755     # last dgit push into that suite (since a dgit push would have
2756     # been descended from the dgit server git branch); thus, in that
2757     # case, we prefer the archive's version (and produce a
2758     # pseudo-merge to overwrite the dgit server git branch).
2759     #
2760     # (If there is no Dgit field in the archive's .dsc then
2761     # generate_commit_from_dsc uses the version numbers to decide
2762     # whether the suite branch or the archive is newer.  If the suite
2763     # branch is newer it ignores the archive's .dsc; otherwise it
2764     # generates an import of the .dsc, and produces a pseudo-merge to
2765     # overwrite the suite branch with the archive contents.)
2766     #
2767     # The outcome of that part of the algorithm is the `public view',
2768     # and is same for all dgit clients: it does not depend on any
2769     # unpublished history in the local tracking branch.
2770     #
2771     # As between the public view and the local tracking branch: The
2772     # local tracking branch is only updated by dgit fetch, and
2773     # whenever dgit fetch runs it includes the public view in the
2774     # local tracking branch.  Therefore if the public view is not
2775     # descended from the local tracking branch, the local tracking
2776     # branch must contain history which was imported from the archive
2777     # but never pushed; and, its tip is now out of date.  So, we make
2778     # a pseudo-merge to overwrite the old imports and stitch the old
2779     # history in.
2780     #
2781     # Finally: we do not necessarily reify the public view (as
2782     # described above).  This is so that we do not end up stacking two
2783     # pseudo-merges.  So what we actually do is figure out the inputs
2784     # to any public view pseudo-merge and put them in @mergeinputs.
2785
2786     my @mergeinputs;
2787     # $mergeinputs[]{Commit}
2788     # $mergeinputs[]{Info}
2789     # $mergeinputs[0] is the one whose tree we use
2790     # @mergeinputs is in the order we use in the actual commit)
2791     #
2792     # Also:
2793     # $mergeinputs[]{Message} is a commit message to use
2794     # $mergeinputs[]{ReverseParents} if def specifies that parent
2795     #                                list should be in opposite order
2796     # Such an entry has no Commit or Info.  It applies only when found
2797     # in the last entry.  (This ugliness is to support making
2798     # identical imports to previous dgit versions.)
2799
2800     my $lastpush_hash = git_get_ref(lrfetchref());
2801     printdebug "previous reference hash=$lastpush_hash\n";
2802     $lastpush_mergeinput = $lastpush_hash && {
2803         Commit => $lastpush_hash,
2804         Info => "dgit suite branch on dgit git server",
2805     };
2806
2807     my $lastfetch_hash = git_get_ref(lrref());
2808     printdebug "fetch_from_archive: lastfetch=$lastfetch_hash\n";
2809     my $lastfetch_mergeinput = $lastfetch_hash && {
2810         Commit => $lastfetch_hash,
2811         Info => "dgit client's archive history view",
2812     };
2813
2814     my $dsc_mergeinput = $dsc_hash && {
2815         Commit => $dsc_hash,
2816         Info => "Dgit field in .dsc from archive",
2817     };
2818
2819     my $cwd = getcwd();
2820     my $del_lrfetchrefs = sub {
2821         changedir $cwd;
2822         my $gur;
2823         printdebug "del_lrfetchrefs...\n";
2824         foreach my $fullrefname (sort keys %lrfetchrefs_d) {
2825             my $objid = $lrfetchrefs_d{$fullrefname};
2826             printdebug "del_lrfetchrefs: $objid $fullrefname\n";
2827             if (!$gur) {
2828                 $gur ||= new IO::Handle;
2829                 open $gur, "|-", qw(git update-ref --stdin) or die $!;
2830             }
2831             printf $gur "delete %s %s\n", $fullrefname, $objid;
2832         }
2833         if ($gur) {
2834             close $gur or failedcmd "git update-ref delete lrfetchrefs";
2835         }
2836     };
2837
2838     if (defined $dsc_hash) {
2839         ensure_we_have_orig();
2840         if (!$lastpush_hash || $dsc_hash eq $lastpush_hash) {
2841             @mergeinputs = $dsc_mergeinput
2842         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
2843             print STDERR <<END or die $!;
2844
2845 Git commit in archive is behind the last version allegedly pushed/uploaded.
2846 Commit referred to by archive: $dsc_hash
2847 Last version pushed with dgit: $lastpush_hash
2848 $later_warning_msg
2849 END
2850             @mergeinputs = ($lastpush_mergeinput);
2851         } else {
2852             # Archive has .dsc which is not a descendant of the last dgit
2853             # push.  This can happen if the archive moves .dscs about.
2854             # Just follow its lead.
2855             if (is_fast_fwd($lastpush_hash,$dsc_hash)) {
2856                 progress "archive .dsc names newer git commit";
2857                 @mergeinputs = ($dsc_mergeinput);
2858             } else {
2859                 progress "archive .dsc names other git commit, fixing up";
2860                 @mergeinputs = ($dsc_mergeinput, $lastpush_mergeinput);
2861             }
2862         }
2863     } elsif ($dsc) {
2864         @mergeinputs = generate_commits_from_dsc();
2865         # We have just done an import.  Now, our import algorithm might
2866         # have been improved.  But even so we do not want to generate
2867         # a new different import of the same package.  So if the
2868         # version numbers are the same, just use our existing version.
2869         # If the version numbers are different, the archive has changed
2870         # (perhaps, rewound).
2871         if ($lastfetch_mergeinput &&
2872             !version_compare( (mergeinfo_version $lastfetch_mergeinput),
2873                               (mergeinfo_version $mergeinputs[0]) )) {
2874             @mergeinputs = ($lastfetch_mergeinput);
2875         }
2876     } elsif ($lastpush_hash) {
2877         # only in git, not in the archive yet
2878         @mergeinputs = ($lastpush_mergeinput);
2879         print STDERR <<END or die $!;
2880
2881 Package not found in the archive, but has allegedly been pushed using dgit.
2882 $later_warning_msg
2883 END
2884     } else {
2885         printdebug "nothing found!\n";
2886         if (defined $skew_warning_vsn) {
2887             print STDERR <<END or die $!;
2888
2889 Warning: relevant archive skew detected.
2890 Archive allegedly contains $skew_warning_vsn
2891 But we were not able to obtain any version from the archive or git.
2892
2893 END
2894         }
2895         unshift @end, $del_lrfetchrefs;
2896         return undef;
2897     }
2898
2899     if ($lastfetch_hash &&
2900         !grep {
2901             my $h = $_->{Commit};
2902             $h and is_fast_fwd($lastfetch_hash, $h);
2903             # If true, one of the existing parents of this commit
2904             # is a descendant of the $lastfetch_hash, so we'll
2905             # be ff from that automatically.
2906         } @mergeinputs
2907         ) {
2908         # Otherwise:
2909         push @mergeinputs, $lastfetch_mergeinput;
2910     }
2911
2912     printdebug "fetch mergeinfos:\n";
2913     foreach my $mi (@mergeinputs) {
2914         if ($mi->{Info}) {
2915             printdebug " commit $mi->{Commit} $mi->{Info}\n";
2916         } else {
2917             printdebug sprintf " ReverseParents=%d Message=%s",
2918                 $mi->{ReverseParents}, $mi->{Message};
2919         }
2920     }
2921
2922     my $compat_info= pop @mergeinputs
2923         if $mergeinputs[$#mergeinputs]{Message};
2924
2925     @mergeinputs = grep { defined $_->{Commit} } @mergeinputs;
2926
2927     my $hash;
2928     if (@mergeinputs > 1) {
2929         # here we go, then:
2930         my $tree_commit = $mergeinputs[0]{Commit};
2931
2932         my $tree = cmdoutput @git, qw(cat-file commit), $tree_commit;
2933         $tree =~ m/\n\n/;  $tree = $`;
2934         $tree =~ m/^tree (\w+)$/m or die "$dsc_hash tree ?";
2935         $tree = $1;
2936
2937         # We use the changelog author of the package in question the
2938         # author of this pseudo-merge.  This is (roughly) correct if
2939         # this commit is simply representing aa non-dgit upload.
2940         # (Roughly because it does not record sponsorship - but we
2941         # don't have sponsorship info because that's in the .changes,
2942         # which isn't in the archivw.)
2943         #
2944         # But, it might be that we are representing archive history
2945         # updates (including in-archive copies).  These are not really
2946         # the responsibility of the person who created the .dsc, but
2947         # there is no-one whose name we should better use.  (The
2948         # author of the .dsc-named commit is clearly worse.)
2949
2950         my $useclogp = mergeinfo_getclogp $mergeinputs[0];
2951         my $author = clogp_authline $useclogp;
2952         my $cversion = getfield $useclogp, 'Version';
2953
2954         my $mcf = ".git/dgit/mergecommit";
2955         open MC, ">", $mcf or die "$mcf $!";
2956         print MC <<END or die $!;
2957 tree $tree
2958 END
2959
2960         my @parents = grep { $_->{Commit} } @mergeinputs;
2961         @parents = reverse @parents if $compat_info->{ReverseParents};
2962         print MC <<END or die $! foreach @parents;
2963 parent $_->{Commit}
2964 END
2965
2966         print MC <<END or die $!;
2967 author $author
2968 committer $author
2969
2970 END
2971
2972         if (defined $compat_info->{Message}) {
2973             print MC $compat_info->{Message} or die $!;
2974         } else {
2975             print MC <<END or die $!;
2976 Record $package ($cversion) in archive suite $csuite
2977
2978 Record that
2979 END
2980             my $message_add_info = sub {
2981                 my ($mi) = (@_);
2982                 my $mversion = mergeinfo_version $mi;
2983                 printf MC "  %-20s %s\n", $mversion, $mi->{Info}
2984                     or die $!;
2985             };
2986
2987             $message_add_info->($mergeinputs[0]);
2988             print MC <<END or die $!;
2989 should be treated as descended from
2990 END
2991             $message_add_info->($_) foreach @mergeinputs[1..$#mergeinputs];
2992         }
2993
2994         close MC or die $!;
2995         $hash = make_commit $mcf;
2996     } else {
2997         $hash = $mergeinputs[0]{Commit};
2998     }
2999     printdebug "fetch hash=$hash\n";
3000
3001     my $chkff = sub {
3002         my ($lasth, $what) = @_;
3003         return unless $lasth;
3004         die "$lasth $hash $what ?" unless is_fast_fwd($lasth, $hash);
3005     };
3006
3007     $chkff->($lastpush_hash, 'dgit repo server tip (last push)')
3008         if $lastpush_hash;
3009     $chkff->($lastfetch_hash, 'local tracking tip (last fetch)');
3010
3011     fetch_from_archive_record_1($hash);
3012
3013     if (defined $skew_warning_vsn) {
3014         mkpath '.git/dgit';
3015         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
3016         my $gotclogp = commit_getclogp($hash);
3017         my $got_vsn = getfield $gotclogp, 'Version';
3018         printdebug "SKEW CHECK GOT $got_vsn\n";
3019         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
3020             print STDERR <<END or die $!;
3021
3022 Warning: archive skew detected.  Using the available version:
3023 Archive allegedly contains    $skew_warning_vsn
3024 We were able to obtain only   $got_vsn
3025
3026 END
3027         }
3028     }
3029
3030     if ($lastfetch_hash ne $hash) {
3031         fetch_from_archive_record_2($hash);
3032     }
3033
3034     lrfetchref_used lrfetchref();
3035
3036     unshift @end, $del_lrfetchrefs;
3037     return $hash;
3038 }
3039
3040 sub set_local_git_config ($$) {
3041     my ($k, $v) = @_;
3042     runcmd @git, qw(config), $k, $v;
3043 }
3044
3045 sub setup_mergechangelogs (;$) {
3046     my ($always) = @_;
3047     return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
3048
3049     my $driver = 'dpkg-mergechangelogs';
3050     my $cb = "merge.$driver";
3051     my $attrs = '.git/info/attributes';
3052     ensuredir '.git/info';
3053
3054     open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
3055     if (!open ATTRS, "<", $attrs) {
3056         $!==ENOENT or die "$attrs: $!";
3057     } else {
3058         while (<ATTRS>) {
3059             chomp;
3060             next if m{^debian/changelog\s};
3061             print NATTRS $_, "\n" or die $!;
3062         }
3063         ATTRS->error and die $!;
3064         close ATTRS;
3065     }
3066     print NATTRS "debian/changelog merge=$driver\n" or die $!;
3067     close NATTRS;
3068
3069     set_local_git_config "$cb.name", 'debian/changelog merge driver';
3070     set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
3071
3072     rename "$attrs.new", "$attrs" or die "$attrs: $!";
3073 }
3074
3075 sub setup_useremail (;$) {
3076     my ($always) = @_;
3077     return unless $always || access_cfg_bool(1, 'setup-useremail');
3078
3079     my $setup = sub {
3080         my ($k, $envvar) = @_;
3081         my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
3082         return unless defined $v;
3083         set_local_git_config "user.$k", $v;
3084     };
3085
3086     $setup->('email', 'DEBEMAIL');
3087     $setup->('name', 'DEBFULLNAME');
3088 }
3089
3090 sub ensure_setup_existing_tree () {
3091     my $k = "remote.$remotename.skipdefaultupdate";
3092     my $c = git_get_config $k;
3093     return if defined $c;
3094     set_local_git_config $k, 'true';
3095 }
3096
3097 sub setup_new_tree () {
3098     setup_mergechangelogs();
3099     setup_useremail();
3100 }
3101
3102 sub multisuite_suite_child ($$$) {
3103     my ($tsuite, $merginputs, $fn) = @_;
3104     # in child, sets things up, calls $fn->(), and returns undef
3105     # in parent, returns canonical suite name for $tsuite
3106     my $canonsuitefh = IO::File::new_tmpfile;
3107     my $pid = fork // die $!;
3108     if (!$pid) {
3109         $isuite = $tsuite;
3110         $us .= " [$isuite]";
3111         $debugprefix .= " ";
3112         progress "fetching $tsuite...";
3113         canonicalise_suite();
3114         print $canonsuitefh $csuite, "\n" or die $!;
3115         close $canonsuitefh or die $!;
3116         $fn->();
3117         return undef;
3118     }
3119     waitpid $pid,0 == $pid or die $!;
3120     fail "failed to obtain $tsuite: ".waitstatusmsg() if $? && $?!=256*4;
3121     seek $canonsuitefh,0,0 or die $!;
3122     local $csuite = <$canonsuitefh>;
3123     die $! unless defined $csuite && chomp $csuite;
3124     if ($? == 256*4) {
3125         printdebug "multisuite $tsuite missing\n";
3126         return $csuite;
3127     }
3128     printdebug "multisuite $tsuite ok (canon=$csuite)\n";
3129     push @$merginputs, {
3130         Ref => lrref,
3131         Info => $csuite,
3132     };
3133     return $csuite;
3134 }
3135
3136 sub fork_for_multisuite ($) {
3137     my ($before_fetch_merge) = @_;
3138     # if nothing unusual, just returns ''
3139     #
3140     # if multisuite:
3141     # returns 0 to caller in child, to do first of the specified suites
3142     # in child, $csuite is not yet set
3143     #
3144     # returns 1 to caller in parent, to finish up anything needed after
3145     # in parent, $csuite is set to canonicalised portmanteau
3146
3147     my $org_isuite = $isuite;
3148     my @suites = split /\,/, $isuite;
3149     return '' unless @suites > 1;
3150     printdebug "fork_for_multisuite: @suites\n";
3151
3152     my @mergeinputs;
3153
3154     my $cbasesuite = multisuite_suite_child($suites[0], \@mergeinputs,
3155                                             sub { });
3156     return 0 unless defined $cbasesuite;
3157
3158     fail "package $package missing in (base suite) $cbasesuite"
3159         unless @mergeinputs;
3160
3161     my @csuites = ($cbasesuite);
3162
3163     $before_fetch_merge->();
3164
3165     foreach my $tsuite (@suites[1..$#suites]) {
3166         my $csubsuite = multisuite_suite_child($tsuite, \@mergeinputs,
3167                                                sub {
3168             @end = ();
3169             fetch();
3170             exit 0;
3171         });
3172         # xxx collecte the ref here
3173
3174         $csubsuite =~ s/^\Q$cbasesuite\E-/-/;
3175         push @csuites, $csubsuite;
3176     }
3177
3178     foreach my $mi (@mergeinputs) {
3179         my $ref = git_get_ref $mi->{Ref};
3180         die "$mi->{Ref} ?" unless length $ref;
3181         $mi->{Commit} = $ref;
3182     }
3183
3184     $csuite = join ",", @csuites;
3185
3186     my $previous = git_get_ref lrref;
3187     if ($previous) {
3188         unshift @mergeinputs, {
3189             Commit => $previous,
3190             Info => "local combined tracking branch",
3191             Warning =>
3192  "archive seems to have rewound: local tracking branch is ahead!",
3193         };
3194     }
3195
3196     foreach my $ix (0..$#mergeinputs) {
3197         $mergeinputs[$ix]{Index} = $ix;
3198     }
3199
3200     @mergeinputs = sort {
3201         -version_compare(mergeinfo_version $a,
3202                          mergeinfo_version $b) # highest version first
3203             or
3204         $a->{Index} <=> $b->{Index}; # earliest in spec first
3205     } @mergeinputs;
3206
3207     my @needed;
3208
3209   NEEDED:
3210     foreach my $mi (@mergeinputs) {
3211         printdebug "multisuite merge check $mi->{Info}\n";
3212         foreach my $previous (@needed) {
3213             next unless is_fast_fwd $mi->{Commit}, $previous->{Commit};
3214             printdebug "multisuite merge un-needed $previous->{Info}\n";
3215             next NEEDED;
3216         }
3217         push @needed, $mi;
3218         printdebug "multisuite merge this-needed\n";
3219         $mi->{Character} = '+';
3220     }
3221
3222     $needed[0]{Character} = '*';
3223
3224     my $output = $needed[0]{Commit};
3225
3226     if (@needed > 1) {
3227         printdebug "multisuite merge nontrivial\n";
3228         my $tree = cmdoutput qw(git rev-parse), $needed[0]{Commit}.':';
3229
3230         my $commit = "tree $tree\n";
3231         my $msg = "Combine archive branches $csuite [dgit]\n\n".
3232             "Input branches:\n";
3233
3234         foreach my $mi (sort { $a->{Index} <=> $b->{Index} } @mergeinputs) {
3235             printdebug "multisuite merge include $mi->{Info}\n";
3236             $mi->{Character} //= ' ';
3237             $commit .= "parent $mi->{Commit}\n";
3238             $msg .= sprintf " %s  %-25s %s\n",
3239                 $mi->{Character},
3240                 (mergeinfo_version $mi),
3241                 $mi->{Info};
3242         }
3243         my $authline = clogp_authline mergeinfo_getclogp $needed[0];
3244         $msg .= "\nKey\n".
3245             " * marks the highest version branch, which choose to use\n".
3246             " + marks each branch which was not already an ancestor\n\n".
3247             "[dgit multi-suite $csuite]\n";
3248         $commit .=
3249             "author $authline\n".
3250             "committer $authline\n\n";
3251         $output = make_commit_text $commit.$msg;
3252         printdebug "multisuite merge generated $output\n";
3253     }
3254
3255     fetch_from_archive_record_1($output);
3256     fetch_from_archive_record_2($output);
3257
3258     progress "calculated combined tracking suite $csuite";
3259
3260     return 1;
3261 }
3262
3263 sub clone_set_head () {
3264     open H, "> .git/HEAD" or die $!;
3265     print H "ref: ".lref()."\n" or die $!;
3266     close H or die $!;
3267 }
3268 sub clone_finish ($) {
3269     my ($dstdir) = @_;
3270     runcmd @git, qw(reset --hard), lrref();
3271     runcmd qw(bash -ec), <<'END';
3272         set -o pipefail
3273         git ls-tree -r --name-only -z HEAD | \
3274         xargs -0r touch -h -r . --
3275 END
3276     printdone "ready for work in $dstdir";
3277 }
3278
3279 sub clone ($) {
3280     my ($dstdir) = @_;
3281     badusage "dry run makes no sense with clone" unless act_local();
3282
3283     my $multi_fetched = fork_for_multisuite(sub {
3284         printdebug "multi clone before fetch merge\n";
3285         changedir $dstdir;
3286     });
3287     if ($multi_fetched) {
3288         printdebug "multi clone after fetch merge\n";
3289         clone_set_head();
3290         clone_finish($dstdir);
3291         exit 0;
3292     }
3293     printdebug "clone main body\n";
3294
3295     canonicalise_suite();
3296     my $hasgit = check_for_git();
3297     mkdir $dstdir or fail "create \`$dstdir': $!";
3298     changedir $dstdir;
3299     runcmd @git, qw(init -q);
3300     clone_set_head();
3301     my $giturl = access_giturl(1);
3302     if (defined $giturl) {
3303         runcmd @git, qw(remote add), 'origin', $giturl;
3304     }
3305     if ($hasgit) {
3306         progress "fetching existing git history";
3307         git_fetch_us();
3308         runcmd_ordryrun_local @git, qw(fetch origin);
3309     } else {
3310         progress "starting new git history";
3311     }
3312     fetch_from_archive() or no_such_package;
3313     my $vcsgiturl = $dsc->{'Vcs-Git'};
3314     if (length $vcsgiturl) {
3315         $vcsgiturl =~ s/\s+-b\s+\S+//g;
3316         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
3317     }
3318     setup_new_tree();
3319     clone_finish($dstdir);
3320 }
3321
3322 sub fetch () {
3323     canonicalise_suite();
3324     if (check_for_git()) {
3325         git_fetch_us();
3326     }
3327     fetch_from_archive() or no_such_package();
3328     printdone "fetched into ".lrref();
3329 }
3330
3331 sub pull () {
3332     my $multi_fetched = fork_for_multisuite(sub { });
3333     fetch() unless $multi_fetched; # parent
3334     return if $multi_fetched eq '0'; # child
3335     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
3336         lrref();
3337     printdone "fetched to ".lrref()." and merged into HEAD";
3338 }
3339
3340 sub check_not_dirty () {
3341     foreach my $f (qw(local-options local-patch-header)) {
3342         if (stat_exists "debian/source/$f") {
3343             fail "git tree contains debian/source/$f";
3344         }
3345     }
3346
3347     return if $ignoredirty;
3348
3349     my @cmd = (@git, qw(diff --quiet HEAD));
3350     debugcmd "+",@cmd;
3351     $!=0; $?=-1; system @cmd;
3352     return if !$?;
3353     if ($?==256) {
3354         fail "working tree is dirty (does not match HEAD)";
3355     } else {
3356         failedcmd @cmd;
3357     }
3358 }
3359
3360 sub commit_admin ($) {
3361     my ($m) = @_;
3362     progress "$m";
3363     runcmd_ordryrun_local @git, qw(commit -m), $m;
3364 }
3365
3366 sub commit_quilty_patch () {
3367     my $output = cmdoutput @git, qw(status --porcelain);
3368     my %adds;
3369     foreach my $l (split /\n/, $output) {
3370         next unless $l =~ m/\S/;
3371         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
3372             $adds{$1}++;
3373         }
3374     }
3375     delete $adds{'.pc'}; # if there wasn't one before, don't add it
3376     if (!%adds) {
3377         progress "nothing quilty to commit, ok.";
3378         return;
3379     }
3380     my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
3381     runcmd_ordryrun_local @git, qw(add -f), @adds;
3382     commit_admin <<END
3383 Commit Debian 3.0 (quilt) metadata
3384
3385 [dgit ($our_version) quilt-fixup]
3386 END
3387 }
3388
3389 sub get_source_format () {
3390     my %options;
3391     if (open F, "debian/source/options") {
3392         while (<F>) {
3393             next if m/^\s*\#/;
3394             next unless m/\S/;
3395             s/\s+$//; # ignore missing final newline
3396             if (m/\s*\#\s*/) {
3397                 my ($k, $v) = ($`, $'); #');
3398                 $v =~ s/^"(.*)"$/$1/;
3399                 $options{$k} = $v;
3400             } else {
3401                 $options{$_} = 1;
3402             }
3403         }
3404         F->error and die $!;
3405         close F;
3406     } else {
3407         die $! unless $!==&ENOENT;
3408     }
3409
3410     if (!open F, "debian/source/format") {
3411         die $! unless $!==&ENOENT;
3412         return '';
3413     }
3414     $_ = <F>;
3415     F->error and die $!;
3416     chomp;
3417     return ($_, \%options);
3418 }
3419
3420 sub madformat_wantfixup ($) {
3421     my ($format) = @_;
3422     return 0 unless $format eq '3.0 (quilt)';
3423     our $quilt_mode_warned;
3424     if ($quilt_mode eq 'nocheck') {
3425         progress "Not doing any fixup of \`$format' due to".
3426             " ----no-quilt-fixup or --quilt=nocheck"
3427             unless $quilt_mode_warned++;
3428         return 0;
3429     }
3430     progress "Format \`$format', need to check/update patch stack"
3431         unless $quilt_mode_warned++;
3432     return 1;
3433 }
3434
3435 sub maybe_split_brain_save ($$$) {
3436     my ($headref, $dgitview, $msg) = @_;
3437     # => message fragment "$saved" describing disposition of $dgitview
3438     return "commit id $dgitview" unless defined $split_brain_save;
3439     my @cmd = (shell_cmd "cd ../../../..",
3440                @git, qw(update-ref -m),
3441                "dgit --dgit-view-save $msg HEAD=$headref",
3442                $split_brain_save, $dgitview);
3443     runcmd @cmd;
3444     return "and left in $split_brain_save";
3445 }
3446
3447 # An "infopair" is a tuple [ $thing, $what ]
3448 # (often $thing is a commit hash; $what is a description)
3449
3450 sub infopair_cond_equal ($$) {
3451     my ($x,$y) = @_;
3452     $x->[0] eq $y->[0] or fail <<END;
3453 $x->[1] ($x->[0]) not equal to $y->[1] ($y->[0])
3454 END
3455 };
3456
3457 sub infopair_lrf_tag_lookup ($$) {
3458     my ($tagnames, $what) = @_;
3459     # $tagname may be an array ref
3460     my @tagnames = ref $tagnames ? @$tagnames : ($tagnames);
3461     printdebug "infopair_lrfetchref_tag_lookup $what @tagnames\n";
3462     foreach my $tagname (@tagnames) {
3463         my $lrefname = lrfetchrefs."/tags/$tagname";
3464         my $tagobj = $lrfetchrefs_f{$lrefname};
3465         next unless defined $tagobj;
3466         printdebug "infopair_lrfetchref_tag_lookup $tagobj $tagname $what\n";
3467         return [ git_rev_parse($tagobj), $what ];
3468     }
3469     fail @tagnames==1 ? <<END : <<END;
3470 Wanted tag $what (@tagnames) on dgit server, but not found
3471 END
3472 Wanted tag $what (one of: @tagnames) on dgit server, but not found
3473 END
3474 }
3475
3476 sub infopair_cond_ff ($$) {
3477     my ($anc,$desc) = @_;
3478     is_fast_fwd($anc->[0], $desc->[0]) or fail <<END;
3479 $anc->[1] ($anc->[0]) .. $desc->[1] ($desc->[0]) is not fast forward
3480 END
3481 };
3482
3483 sub pseudomerge_version_check ($$) {
3484     my ($clogp, $archive_hash) = @_;
3485
3486     my $arch_clogp = commit_getclogp $archive_hash;
3487     my $i_arch_v = [ (getfield $arch_clogp, 'Version'),
3488                      'version currently in archive' ];
3489     if (defined $overwrite_version) {
3490         if (length $overwrite_version) {
3491             infopair_cond_equal([ $overwrite_version,
3492                                   '--overwrite= version' ],
3493                                 $i_arch_v);
3494         } else {
3495             my $v = $i_arch_v->[0];
3496             progress "Checking package changelog for archive version $v ...";
3497             eval {
3498                 my @xa = ("-f$v", "-t$v");
3499                 my $vclogp = parsechangelog @xa;
3500                 my $cv = [ (getfield $vclogp, 'Version'),
3501                            "Version field from dpkg-parsechangelog @xa" ];
3502                 infopair_cond_equal($i_arch_v, $cv);
3503             };
3504             if ($@) {
3505                 $@ =~ s/^dgit: //gm;
3506                 fail "$@".
3507                     "Perhaps debian/changelog does not mention $v ?";
3508             }
3509         }
3510     }
3511     
3512     printdebug "pseudomerge_version_check i_arch_v @$i_arch_v\n";
3513     return $i_arch_v;
3514 }
3515
3516 sub pseudomerge_make_commit ($$$$ $$) {
3517     my ($clogp, $dgitview, $archive_hash, $i_arch_v,
3518         $msg_cmd, $msg_msg) = @_;
3519     progress "Declaring that HEAD inciudes all changes in $i_arch_v->[0]...";
3520
3521     my $tree = cmdoutput qw(git rev-parse), "${dgitview}:";
3522     my $authline = clogp_authline $clogp;
3523
3524     chomp $msg_msg;
3525     $msg_cmd .=
3526         !defined $overwrite_version ? ""
3527         : !length  $overwrite_version ? " --overwrite"
3528         : " --overwrite=".$overwrite_version;
3529
3530     mkpath '.git/dgit';
3531     my $pmf = ".git/dgit/pseudomerge";
3532     open MC, ">", $pmf or die "$pmf $!";
3533     print MC <<END or die $!;
3534 tree $tree
3535 parent $dgitview
3536 parent $archive_hash
3537 author $authline
3538 commiter $authline
3539
3540 $msg_msg
3541
3542 [$msg_cmd]
3543 END
3544     close MC or die $!;
3545
3546     return make_commit($pmf);
3547 }
3548
3549 sub splitbrain_pseudomerge ($$$$) {
3550     my ($clogp, $maintview, $dgitview, $archive_hash) = @_;
3551     # => $merged_dgitview
3552     printdebug "splitbrain_pseudomerge...\n";
3553     #
3554     #     We:      debian/PREVIOUS    HEAD($maintview)
3555     # expect:          o ----------------- o
3556     #                    \                   \
3557     #                     o                   o
3558     #                 a/d/PREVIOUS        $dgitview
3559     #                $archive_hash              \
3560     #  If so,                \                   \
3561     #  we do:                 `------------------ o
3562     #   this:                                   $dgitview'
3563     #
3564
3565     return $dgitview unless defined $archive_hash;
3566
3567     printdebug "splitbrain_pseudomerge...\n";
3568
3569     my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3570
3571     if (!defined $overwrite_version) {
3572         progress "Checking that HEAD inciudes all changes in archive...";
3573     }
3574
3575     return $dgitview if is_fast_fwd $archive_hash, $dgitview;
3576
3577     if (defined $overwrite_version) {
3578     } elsif (!eval {
3579         my $t_dep14 = debiantag_maintview $i_arch_v->[0], access_nomdistro;
3580         my $i_dep14 = infopair_lrf_tag_lookup($t_dep14, "maintainer view tag");
3581         my $t_dgit = debiantag_new $i_arch_v->[0], access_nomdistro;
3582         my $i_dgit = infopair_lrf_tag_lookup($t_dgit, "dgit view tag");
3583         my $i_archive = [ $archive_hash, "current archive contents" ];
3584
3585         printdebug "splitbrain_pseudomerge i_archive @$i_archive\n";
3586
3587         infopair_cond_equal($i_dgit, $i_archive);
3588         infopair_cond_ff($i_dep14, $i_dgit);
3589         infopair_cond_ff($i_dep14, [ $maintview, 'HEAD' ]);
3590         1;
3591     }) {
3592         print STDERR <<END;
3593 $us: check failed (maybe --overwrite is needed, consult documentation)
3594 END
3595         die "$@";
3596     }
3597
3598     my $r = pseudomerge_make_commit
3599         $clogp, $dgitview, $archive_hash, $i_arch_v,
3600         "dgit --quilt=$quilt_mode",
3601         (defined $overwrite_version ? <<END_OVERWR : <<END_MAKEFF);
3602 Declare fast forward from $i_arch_v->[0]
3603 END_OVERWR
3604 Make fast forward from $i_arch_v->[0]
3605 END_MAKEFF
3606
3607     maybe_split_brain_save $maintview, $r, "pseudomerge";
3608
3609     progress "Made pseudo-merge of $i_arch_v->[0] into dgit view.";
3610     return $r;
3611 }       
3612
3613 sub plain_overwrite_pseudomerge ($$$) {
3614     my ($clogp, $head, $archive_hash) = @_;
3615
3616     printdebug "plain_overwrite_pseudomerge...";
3617
3618     my $i_arch_v = pseudomerge_version_check($clogp, $archive_hash);
3619
3620     return $head if is_fast_fwd $archive_hash, $head;
3621
3622     my $m = "Declare fast forward from $i_arch_v->[0]";
3623
3624     my $r = pseudomerge_make_commit
3625         $clogp, $head, $archive_hash, $i_arch_v,
3626         "dgit", $m;
3627
3628     runcmd @git, qw(update-ref -m), $m, 'HEAD', $r, $head;
3629
3630     progress "Make pseudo-merge of $i_arch_v->[0] into your HEAD.";
3631     return $r;
3632 }
3633
3634 sub push_parse_changelog ($) {
3635     my ($clogpfn) = @_;
3636
3637     my $clogp = Dpkg::Control::Hash->new();
3638     $clogp->load($clogpfn) or die;
3639
3640     my $clogpackage = getfield $clogp, 'Source';
3641     $package //= $clogpackage;
3642     fail "-p specified $package but changelog specified $clogpackage"
3643         unless $package eq $clogpackage;
3644     my $cversion = getfield $clogp, 'Version';
3645     my $tag = debiantag($cversion, access_nomdistro);
3646     runcmd @git, qw(check-ref-format), $tag;
3647
3648     my $dscfn = dscfn($cversion);
3649
3650     return ($clogp, $cversion, $dscfn);
3651 }
3652
3653 sub push_parse_dsc ($$$) {
3654     my ($dscfn,$dscfnwhat, $cversion) = @_;
3655     $dsc = parsecontrol($dscfn,$dscfnwhat);
3656     my $dversion = getfield $dsc, 'Version';
3657     my $dscpackage = getfield $dsc, 'Source';
3658     ($dscpackage eq $package && $dversion eq $cversion) or
3659         fail "$dscfn is for $dscpackage $dversion".
3660             " but debian/changelog is for $package $cversion";
3661 }
3662
3663 sub push_tagwants ($$$$) {
3664     my ($cversion, $dgithead, $maintviewhead, $tfbase) = @_;
3665     my @tagwants;
3666     push @tagwants, {
3667         TagFn => \&debiantag,
3668         Objid => $dgithead,
3669         TfSuffix => '',
3670         View => 'dgit',
3671     };
3672     if (defined $maintviewhead) {
3673         push @tagwants, {
3674             TagFn => \&debiantag_maintview,
3675             Objid => $maintviewhead,
3676             TfSuffix => '-maintview',
3677             View => 'maint',
3678         };
3679     } elsif ($dodep14tag eq 'no' ? 0
3680              : $dodep14tag eq 'want' ? access_cfg_tagformats_can_splitbrain
3681              : $dodep14tag eq 'always'
3682              ? (access_cfg_tagformats_can_splitbrain or fail <<END)
3683 --dep14tag-always (or equivalent in config) means server must support
3684  both "new" and "maint" tag formats, but config says it doesn't.
3685 END
3686             : die "$dodep14tag ?") {
3687         push @tagwants, {
3688             TagFn => \&debiantag_maintview,
3689             Objid => $dgithead,
3690             TfSuffix => '-dgit',
3691             View => 'dgit',
3692         };
3693     };
3694     foreach my $tw (@tagwants) {
3695         $tw->{Tag} = $tw->{TagFn}($cversion, access_nomdistro);
3696         $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
3697     }
3698     printdebug 'push_tagwants: ', Dumper(\@_, \@tagwants);
3699     return @tagwants;
3700 }
3701
3702 sub push_mktags ($$ $$ $) {
3703     my ($clogp,$dscfn,
3704         $changesfile,$changesfilewhat,
3705         $tagwants) = @_;
3706
3707     die unless $tagwants->[0]{View} eq 'dgit';
3708
3709     $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
3710     $dsc->save("$dscfn.tmp") or die $!;
3711
3712     my $changes = parsecontrol($changesfile,$changesfilewhat);
3713     foreach my $field (qw(Source Distribution Version)) {
3714         $changes->{$field} eq $clogp->{$field} or
3715             fail "changes field $field \`$changes->{$field}'".
3716                 " does not match changelog \`$clogp->{$field}'";
3717     }
3718
3719     my $cversion = getfield $clogp, 'Version';
3720     my $clogsuite = getfield $clogp, 'Distribution';
3721
3722     # We make the git tag by hand because (a) that makes it easier
3723     # to control the "tagger" (b) we can do remote signing
3724     my $authline = clogp_authline $clogp;
3725     my $delibs = join(" ", "",@deliberatelies);
3726     my $declaredistro = access_nomdistro();
3727
3728     my $mktag = sub {
3729         my ($tw) = @_;
3730         my $tfn = $tw->{Tfn};
3731         my $head = $tw->{Objid};
3732         my $tag = $tw->{Tag};
3733
3734         open TO, '>', $tfn->('.tmp') or die $!;
3735         print TO <<END or die $!;
3736 object $head
3737 type commit
3738 tag $tag
3739 tagger $authline
3740
3741 END
3742         if ($tw->{View} eq 'dgit') {
3743             print TO <<END or die $!;
3744 $package release $cversion for $clogsuite ($csuite) [dgit]
3745 [dgit distro=$declaredistro$delibs]
3746 END
3747             foreach my $ref (sort keys %previously) {
3748                 print TO <<END or die $!;
3749 [dgit previously:$ref=$previously{$ref}]
3750 END
3751             }
3752         } elsif ($tw->{View} eq 'maint') {
3753             print TO <<END or die $!;
3754 $package release $cversion for $clogsuite ($csuite)
3755 (maintainer view tag generated by dgit --quilt=$quilt_mode)
3756 END
3757         } else {
3758             die Dumper($tw)."?";
3759         }
3760
3761         close TO or die $!;
3762
3763         my $tagobjfn = $tfn->('.tmp');
3764         if ($sign) {
3765             if (!defined $keyid) {
3766                 $keyid = access_cfg('keyid','RETURN-UNDEF');
3767             }
3768             if (!defined $keyid) {
3769                 $keyid = getfield $clogp, 'Maintainer';
3770             }
3771             unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
3772             my @sign_cmd = (@gpg, qw(--detach-sign --armor));
3773             push @sign_cmd, qw(-u),$keyid if defined $keyid;
3774             push @sign_cmd, $tfn->('.tmp');
3775             runcmd_ordryrun @sign_cmd;
3776             if (act_scary()) {
3777                 $tagobjfn = $tfn->('.signed.tmp');
3778                 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
3779                     $tfn->('.tmp'), $tfn->('.tmp.asc');
3780             }
3781         }
3782         return $tagobjfn;
3783     };
3784
3785     my @r = map { $mktag->($_); } @$tagwants;
3786     return @r;
3787 }
3788
3789 sub sign_changes ($) {
3790     my ($changesfile) = @_;
3791     if ($sign) {
3792         my @debsign_cmd = @debsign;
3793         push @debsign_cmd, "-k$keyid" if defined $keyid;
3794         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
3795         push @debsign_cmd, $changesfile;
3796         runcmd_ordryrun @debsign_cmd;
3797     }
3798 }
3799
3800 sub dopush () {
3801     printdebug "actually entering push\n";
3802
3803     supplementary_message(<<'END');
3804 Push failed, while checking state of the archive.
3805 You can retry the push, after fixing the problem, if you like.
3806 END
3807     if (check_for_git()) {
3808         git_fetch_us();
3809     }
3810     my $archive_hash = fetch_from_archive();
3811     if (!$archive_hash) {
3812         $new_package or
3813             fail "package appears to be new in this suite;".
3814                 " if this is intentional, use --new";
3815     }
3816
3817     supplementary_message(<<'END');
3818 Push failed, while preparing your push.
3819 You can retry the push, after fixing the problem, if you like.
3820 END
3821
3822     need_tagformat 'new', "quilt mode $quilt_mode"
3823         if quiltmode_splitbrain;
3824
3825     prep_ud();
3826
3827     access_giturl(); # check that success is vaguely likely
3828     select_tagformat();
3829
3830     my $clogpfn = ".git/dgit/changelog.822.tmp";
3831     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
3832
3833     responder_send_file('parsed-changelog', $clogpfn);
3834
3835     my ($clogp, $cversion, $dscfn) =
3836         push_parse_changelog("$clogpfn");
3837
3838     my $dscpath = "$buildproductsdir/$dscfn";
3839     stat_exists $dscpath or
3840         fail "looked for .dsc $dscpath, but $!;".
3841             " maybe you forgot to build";
3842
3843     responder_send_file('dsc', $dscpath);
3844
3845     push_parse_dsc($dscpath, $dscfn, $cversion);
3846
3847     my $format = getfield $dsc, 'Format';
3848     printdebug "format $format\n";
3849
3850     my $actualhead = git_rev_parse('HEAD');
3851     my $dgithead = $actualhead;
3852     my $maintviewhead = undef;
3853
3854     my $upstreamversion = upstreamversion $clogp->{Version};
3855
3856     if (madformat_wantfixup($format)) {
3857         # user might have not used dgit build, so maybe do this now:
3858         if (quiltmode_splitbrain()) {
3859             changedir $ud;
3860             quilt_make_fake_dsc($upstreamversion);
3861             my $cachekey;
3862             ($dgithead, $cachekey) =
3863                 quilt_check_splitbrain_cache($actualhead, $upstreamversion);
3864             $dgithead or fail
3865  "--quilt=$quilt_mode but no cached dgit view:
3866  perhaps tree changed since dgit build[-source] ?";
3867             $split_brain = 1;
3868             $dgithead = splitbrain_pseudomerge($clogp,
3869                                                $actualhead, $dgithead,
3870                                                $archive_hash);
3871             $maintviewhead = $actualhead;
3872             changedir '../../../..';
3873             prep_ud(); # so _only_subdir() works, below
3874         } else {
3875             commit_quilty_patch();
3876         }
3877     }
3878
3879     if (defined $overwrite_version && !defined $maintviewhead) {
3880         $dgithead = plain_overwrite_pseudomerge($clogp,
3881                                                 $dgithead,
3882                                                 $archive_hash);
3883     }
3884
3885     check_not_dirty();
3886
3887     my $forceflag = '';
3888     if ($archive_hash) {
3889         if (is_fast_fwd($archive_hash, $dgithead)) {
3890             # ok
3891         } elsif (deliberately_not_fast_forward) {
3892             $forceflag = '+';
3893         } else {
3894             fail "dgit push: HEAD is not a descendant".
3895                 " of the archive's version.\n".
3896                 "To overwrite the archive's contents,".
3897                 " pass --overwrite[=VERSION].\n".
3898                 "To rewind history, if permitted by the archive,".
3899                 " use --deliberately-not-fast-forward.";
3900         }
3901     }
3902
3903     changedir $ud;
3904     progress "checking that $dscfn corresponds to HEAD";
3905     runcmd qw(dpkg-source -x --),
3906         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
3907     my ($tree,$dir) = mktree_in_ud_from_only_subdir("source package");
3908     check_for_vendor_patches() if madformat($dsc->{format});
3909     changedir '../../../..';
3910     my @diffcmd = (@git, qw(diff --quiet), $tree, $dgithead);
3911     debugcmd "+",@diffcmd;
3912     $!=0; $?=-1;
3913     my $r = system @diffcmd;
3914     if ($r) {
3915         if ($r==256) {
3916             my $diffs = cmdoutput @git, qw(diff --stat), $tree, $dgithead;
3917             fail <<END
3918 HEAD specifies a different tree to $dscfn:
3919 $diffs
3920 Perhaps you forgot to build.  Or perhaps there is a problem with your
3921  source tree (see dgit(7) for some hints).  To see a full diff, run
3922    git diff $tree HEAD
3923 END
3924         } else {
3925             failedcmd @diffcmd;
3926         }
3927     }
3928     if (!$changesfile) {
3929         my $pat = changespat $cversion;
3930         my @cs = glob "$buildproductsdir/$pat";
3931         fail "failed to find unique changes file".
3932             " (looked for $pat in $buildproductsdir);".
3933             " perhaps you need to use dgit -C"
3934             unless @cs==1;
3935         ($changesfile) = @cs;
3936     } else {
3937         $changesfile = "$buildproductsdir/$changesfile";
3938     }
3939
3940     # Check that changes and .dsc agree enough
3941     $changesfile =~ m{[^/]*$};
3942     my $changes = parsecontrol($changesfile,$&);
3943     files_compare_inputs($dsc, $changes)
3944         unless forceing [qw(dsc-changes-mismatch)];
3945
3946     # Perhaps adjust .dsc to contain right set of origs
3947     changes_update_origs_from_dsc($dsc, $changes, $upstreamversion,
3948                                   $changesfile)
3949         unless forceing [qw(changes-origs-exactly)];
3950
3951     # Checks complete, we're going to try and go ahead:
3952
3953     responder_send_file('changes',$changesfile);
3954     responder_send_command("param head $dgithead");
3955     responder_send_command("param csuite $csuite");
3956     responder_send_command("param tagformat $tagformat");
3957     if (defined $maintviewhead) {
3958         die unless ($protovsn//4) >= 4;
3959         responder_send_command("param maint-view $maintviewhead");
3960     }
3961
3962     if (deliberately_not_fast_forward) {
3963         git_for_each_ref(lrfetchrefs, sub {
3964             my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
3965             my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
3966             responder_send_command("previously $rrefname=$objid");
3967             $previously{$rrefname} = $objid;
3968         });
3969     }
3970
3971     my @tagwants = push_tagwants($cversion, $dgithead, $maintviewhead,
3972                                  ".git/dgit/tag");
3973     my @tagobjfns;
3974
3975     supplementary_message(<<'END');
3976 Push failed, while signing the tag.
3977 You can retry the push, after fixing the problem, if you like.
3978 END
3979     # If we manage to sign but fail to record it anywhere, it's fine.
3980     if ($we_are_responder) {
3981         @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
3982         responder_receive_files('signed-tag', @tagobjfns);
3983     } else {
3984         @tagobjfns = push_mktags($clogp,$dscpath,
3985                               $changesfile,$changesfile,
3986                               \@tagwants);
3987     }
3988     supplementary_message(<<'END');
3989 Push failed, *after* signing the tag.
3990 If you want to try again, you should use a new version number.
3991 END
3992
3993     pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
3994
3995     foreach my $tw (@tagwants) {
3996         my $tag = $tw->{Tag};
3997         my $tagobjfn = $tw->{TagObjFn};
3998         my $tag_obj_hash =
3999             cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
4000         runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
4001         runcmd_ordryrun_local
4002             @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
4003     }
4004
4005     supplementary_message(<<'END');
4006 Push failed, while updating the remote git repository - see messages above.
4007 If you want to try again, you should use a new version number.
4008 END
4009     if (!check_for_git()) {
4010         create_remote_git_repo();
4011     }
4012
4013     my @pushrefs = $forceflag.$dgithead.":".rrref();
4014     foreach my $tw (@tagwants) {
4015         push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
4016     }
4017
4018     runcmd_ordryrun @git,
4019         qw(-c push.followTags=false push), access_giturl(), @pushrefs;
4020     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), $dgithead;
4021
4022     supplementary_message(<<'END');
4023 Push failed, while obtaining signatures on the .changes and .dsc.
4024 If it was just that the signature failed, you may try again by using
4025 debsign by hand to sign the changes
4026    $changesfile
4027 and then dput to complete the upload.
4028 If you need to change the package, you must use a new version number.
4029 END
4030     if ($we_are_responder) {
4031         my $dryrunsuffix = act_local() ? "" : ".tmp";
4032         responder_receive_files('signed-dsc-changes',
4033                                 "$dscpath$dryrunsuffix",
4034                                 "$changesfile$dryrunsuffix");
4035     } else {
4036         if (act_local()) {
4037             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
4038         } else {
4039             progress "[new .dsc left in $dscpath.tmp]";
4040         }
4041         sign_changes $changesfile;
4042     }
4043
4044     supplementary_message(<<END);
4045 Push failed, while uploading package(s) to the archive server.
4046 You can retry the upload of exactly these same files with dput of:
4047   $changesfile
4048 If that .changes file is broken, you will need to use a new version
4049 number for your next attempt at the upload.
4050 END
4051     my $host = access_cfg('upload-host','RETURN-UNDEF');
4052     my @hostarg = defined($host) ? ($host,) : ();
4053     runcmd_ordryrun @dput, @hostarg, $changesfile;
4054     printdone "pushed and uploaded $cversion";
4055
4056     supplementary_message('');
4057     responder_send_command("complete");
4058 }
4059
4060 sub cmd_clone {
4061     parseopts();
4062     notpushing();
4063     my $dstdir;
4064     badusage "-p is not allowed with clone; specify as argument instead"
4065         if defined $package;
4066     if (@ARGV==1) {
4067         ($package) = @ARGV;
4068     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
4069         ($package,$isuite) = @ARGV;
4070     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
4071         ($package,$dstdir) = @ARGV;
4072     } elsif (@ARGV==3) {
4073         ($package,$isuite,$dstdir) = @ARGV;
4074     } else {
4075         badusage "incorrect arguments to dgit clone";
4076     }
4077     $dstdir ||= "$package";
4078
4079     if (stat_exists $dstdir) {
4080         fail "$dstdir already exists";
4081     }
4082
4083     my $cwd_remove;
4084     if ($rmonerror && !$dryrun_level) {
4085         $cwd_remove= getcwd();
4086         unshift @end, sub { 
4087             return unless defined $cwd_remove;
4088             if (!chdir "$cwd_remove") {
4089                 return if $!==&ENOENT;
4090                 die "chdir $cwd_remove: $!";
4091             }
4092             printdebug "clone rmonerror removing $dstdir\n";
4093             if (stat $dstdir) {
4094                 rmtree($dstdir) or die "remove $dstdir: $!\n";
4095             } elsif (grep { $! == $_ }
4096                      (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
4097             } else {
4098                 print STDERR "check whether to remove $dstdir: $!\n";
4099             }
4100         };
4101     }
4102
4103     clone($dstdir);
4104     $cwd_remove = undef;
4105 }
4106
4107 sub branchsuite () {
4108     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
4109     if ($branch =~ m#$lbranch_re#o) {
4110         return $1;
4111     } else {
4112         return undef;
4113     }
4114 }
4115
4116 sub fetchpullargs () {
4117     notpushing();
4118     if (!defined $package) {
4119         my $sourcep = parsecontrol('debian/control','debian/control');
4120         $package = getfield $sourcep, 'Source';
4121     }
4122     if (@ARGV==0) {
4123         $isuite = branchsuite();
4124         if (!$isuite) {
4125             my $clogp = parsechangelog();
4126             $isuite = getfield $clogp, 'Distribution';
4127         }
4128     } elsif (@ARGV==1) {
4129         ($isuite) = @ARGV;
4130     } else {
4131         badusage "incorrect arguments to dgit fetch or dgit pull";
4132     }
4133 }
4134
4135 sub cmd_fetch {
4136     parseopts();
4137     fetchpullargs();
4138     my $multi_fetched = fork_for_multisuite(sub { });
4139     exit 0 if $multi_fetched;
4140     fetch();
4141 }
4142
4143 sub cmd_pull {
4144     parseopts();
4145     fetchpullargs();
4146     if (quiltmode_splitbrain()) {
4147         my ($format, $fopts) = get_source_format();
4148         madformat($format) and fail <<END
4149 dgit pull not yet supported in split view mode (--quilt=$quilt_mode)
4150 END
4151     }
4152     pull();
4153 }
4154
4155 sub cmd_push {
4156     parseopts();
4157     pushing();
4158     badusage "-p is not allowed with dgit push" if defined $package;
4159     check_not_dirty();
4160     my $clogp = parsechangelog();
4161     $package = getfield $clogp, 'Source';
4162     my $specsuite;
4163     if (@ARGV==0) {
4164     } elsif (@ARGV==1) {
4165         ($specsuite) = (@ARGV);
4166     } else {
4167         badusage "incorrect arguments to dgit push";
4168     }
4169     $isuite = getfield $clogp, 'Distribution';
4170     if ($new_package) {
4171         local ($package) = $existing_package; # this is a hack
4172         canonicalise_suite();
4173     } else {
4174         canonicalise_suite();
4175     }
4176     if (defined $specsuite &&
4177         $specsuite ne $isuite &&
4178         $specsuite ne $csuite) {
4179             fail "dgit push: changelog specifies $isuite ($csuite)".
4180                 " but command line specifies $specsuite";
4181     }
4182     dopush();
4183 }
4184
4185 #---------- remote commands' implementation ----------
4186
4187 sub cmd_remote_push_build_host {
4188     my ($nrargs) = shift @ARGV;
4189     my (@rargs) = @ARGV[0..$nrargs-1];
4190     @ARGV = @ARGV[$nrargs..$#ARGV];
4191     die unless @rargs;
4192     my ($dir,$vsnwant) = @rargs;
4193     # vsnwant is a comma-separated list; we report which we have
4194     # chosen in our ready response (so other end can tell if they
4195     # offered several)
4196     $debugprefix = ' ';
4197     $we_are_responder = 1;
4198     $us .= " (build host)";
4199
4200     pushing();
4201
4202     open PI, "<&STDIN" or die $!;
4203     open STDIN, "/dev/null" or die $!;
4204     open PO, ">&STDOUT" or die $!;
4205     autoflush PO 1;
4206     open STDOUT, ">&STDERR" or die $!;
4207     autoflush STDOUT 1;
4208
4209     $vsnwant //= 1;
4210     ($protovsn) = grep {
4211         $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
4212     } @rpushprotovsn_support;
4213
4214     fail "build host has dgit rpush protocol versions ".
4215         (join ",", @rpushprotovsn_support).
4216         " but invocation host has $vsnwant"
4217         unless defined $protovsn;
4218
4219     responder_send_command("dgit-remote-push-ready $protovsn");
4220     rpush_handle_protovsn_bothends();
4221     changedir $dir;
4222     &cmd_push;
4223 }
4224
4225 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
4226 # ... for compatibility with proto vsn.1 dgit (just so that user gets
4227 #     a good error message)
4228
4229 sub rpush_handle_protovsn_bothends () {
4230     if ($protovsn < 4) {
4231         need_tagformat 'old', "rpush negotiated protocol $protovsn";
4232     }
4233     select_tagformat();
4234 }
4235
4236 our $i_tmp;
4237
4238 sub i_cleanup {
4239     local ($@, $?);
4240     my $report = i_child_report();
4241     if (defined $report) {
4242         printdebug "($report)\n";
4243     } elsif ($i_child_pid) {
4244         printdebug "(killing build host child $i_child_pid)\n";
4245         kill 15, $i_child_pid;
4246     }
4247     if (defined $i_tmp && !defined $initiator_tempdir) {
4248         changedir "/";
4249         eval { rmtree $i_tmp; };
4250     }
4251 }
4252
4253 END { i_cleanup(); }
4254
4255 sub i_method {
4256     my ($base,$selector,@args) = @_;
4257     $selector =~ s/\-/_/g;
4258     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
4259 }
4260
4261 sub cmd_rpush {
4262     pushing();
4263     my $host = nextarg;
4264     my $dir;
4265     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
4266         $host = $1;
4267         $dir = $'; #';
4268     } else {
4269         $dir = nextarg;
4270     }
4271     $dir =~ s{^-}{./-};
4272     my @rargs = ($dir);
4273     push @rargs, join ",", @rpushprotovsn_support;
4274     my @rdgit;
4275     push @rdgit, @dgit;
4276     push @rdgit, @ropts;
4277     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
4278     push @rdgit, @ARGV;
4279     my @cmd = (@ssh, $host, shellquote @rdgit);
4280     debugcmd "+",@cmd;
4281
4282     if (defined $initiator_tempdir) {
4283         rmtree $initiator_tempdir;
4284         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
4285         $i_tmp = $initiator_tempdir;
4286     } else {
4287         $i_tmp = tempdir();
4288     }
4289     $i_child_pid = open2(\*RO, \*RI, @cmd);
4290     changedir $i_tmp;
4291     ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
4292     die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
4293     $supplementary_message = '' unless $protovsn >= 3;
4294
4295     fail "rpush negotiated protocol version $protovsn".
4296         " which does not support quilt mode $quilt_mode"
4297         if quiltmode_splitbrain;
4298
4299     rpush_handle_protovsn_bothends();
4300     for (;;) {
4301         my ($icmd,$iargs) = initiator_expect {
4302             m/^(\S+)(?: (.*))?$/;
4303             ($1,$2);
4304         };
4305         i_method "i_resp", $icmd, $iargs;
4306     }
4307 }
4308
4309 sub i_resp_progress ($) {
4310     my ($rhs) = @_;
4311     my $msg = protocol_read_bytes \*RO, $rhs;
4312     progress $msg;
4313 }
4314
4315 sub i_resp_supplementary_message ($) {
4316     my ($rhs) = @_;
4317     $supplementary_message = protocol_read_bytes \*RO, $rhs;
4318 }
4319
4320 sub i_resp_complete {
4321     my $pid = $i_child_pid;
4322     $i_child_pid = undef; # prevents killing some other process with same pid
4323     printdebug "waiting for build host child $pid...\n";
4324     my $got = waitpid $pid, 0;
4325     die $! unless $got == $pid;
4326     die "build host child failed $?" if $?;
4327
4328     i_cleanup();
4329     printdebug "all done\n";
4330     exit 0;
4331 }
4332
4333 sub i_resp_file ($) {
4334     my ($keyword) = @_;
4335     my $localname = i_method "i_localname", $keyword;
4336     my $localpath = "$i_tmp/$localname";
4337     stat_exists $localpath and
4338         badproto \*RO, "file $keyword ($localpath) twice";
4339     protocol_receive_file \*RO, $localpath;
4340     i_method "i_file", $keyword;
4341 }
4342
4343 our %i_param;
4344
4345 sub i_resp_param ($) {
4346     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
4347     $i_param{$1} = $2;
4348 }
4349
4350 sub i_resp_previously ($) {
4351     $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
4352         or badproto \*RO, "bad previously spec";
4353     my $r = system qw(git check-ref-format), $1;
4354     die "bad previously ref spec ($r)" if $r;
4355     $previously{$1} = $2;
4356 }
4357
4358 our %i_wanted;
4359
4360 sub i_resp_want ($) {
4361     my ($keyword) = @_;
4362     die "$keyword ?" if $i_wanted{$keyword}++;
4363     my @localpaths = i_method "i_want", $keyword;
4364     printdebug "[[  $keyword @localpaths\n";
4365     foreach my $localpath (@localpaths) {
4366         protocol_send_file \*RI, $localpath;
4367     }
4368     print RI "files-end\n" or die $!;
4369 }
4370
4371 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
4372
4373 sub i_localname_parsed_changelog {
4374     return "remote-changelog.822";
4375 }
4376 sub i_file_parsed_changelog {
4377     ($i_clogp, $i_version, $i_dscfn) =
4378         push_parse_changelog "$i_tmp/remote-changelog.822";
4379     die if $i_dscfn =~ m#/|^\W#;
4380 }
4381
4382 sub i_localname_dsc {
4383     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4384     return $i_dscfn;
4385 }
4386 sub i_file_dsc { }
4387
4388 sub i_localname_changes {
4389     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
4390     $i_changesfn = $i_dscfn;
4391     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
4392     return $i_changesfn;
4393 }
4394 sub i_file_changes { }
4395
4396 sub i_want_signed_tag {
4397     printdebug Dumper(\%i_param, $i_dscfn);
4398     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
4399         && defined $i_param{'csuite'}
4400         or badproto \*RO, "premature desire for signed-tag";
4401     my $head = $i_param{'head'};
4402     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
4403
4404     my $maintview = $i_param{'maint-view'};
4405     die if defined $maintview && $maintview =~ m/[^0-9a-f]/;
4406
4407     select_tagformat();
4408     if ($protovsn >= 4) {
4409         my $p = $i_param{'tagformat'} // '<undef>';
4410         $p eq $tagformat
4411             or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
4412     }
4413
4414     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
4415     $csuite = $&;
4416     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
4417
4418     my @tagwants = push_tagwants $i_version, $head, $maintview, "tag";
4419
4420     return
4421         push_mktags $i_clogp, $i_dscfn,
4422             $i_changesfn, 'remote changes',
4423             \@tagwants;
4424 }
4425
4426 sub i_want_signed_dsc_changes {
4427     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
4428     sign_changes $i_changesfn;
4429     return ($i_dscfn, $i_changesfn);
4430 }
4431
4432 #---------- building etc. ----------
4433
4434 our $version;
4435 our $sourcechanges;
4436 our $dscfn;
4437
4438 #----- `3.0 (quilt)' handling -----
4439
4440 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
4441
4442 sub quiltify_dpkg_commit ($$$;$) {
4443     my ($patchname,$author,$msg, $xinfo) = @_;
4444     $xinfo //= '';
4445
4446     mkpath '.git/dgit';
4447     my $descfn = ".git/dgit/quilt-description.tmp";
4448     open O, '>', $descfn or die "$descfn: $!";
4449     $msg =~ s/\n+/\n\n/;
4450     print O <<END or die $!;
4451 From: $author
4452 ${xinfo}Subject: $msg
4453 ---
4454
4455 END
4456     close O or die $!;
4457
4458     {
4459         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
4460         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
4461         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
4462         runcmd @dpkgsource, qw(--commit .), $patchname;
4463     }
4464 }
4465
4466 sub quiltify_trees_differ ($$;$$$) {
4467     my ($x,$y,$finegrained,$ignorenamesr,$unrepres) = @_;
4468     # returns true iff the two tree objects differ other than in debian/
4469     # with $finegrained,
4470     # returns bitmask 01 - differ in upstream files except .gitignore
4471     #                 02 - differ in .gitignore
4472     # if $ignorenamesr is defined, $ingorenamesr->{$fn}
4473     #  is set for each modified .gitignore filename $fn
4474     # if $unrepres is defined, array ref to which is appeneded
4475     #  a list of unrepresentable changes (removals of upstream files
4476     #  (as messages)
4477     local $/=undef;
4478     my @cmd = (@git, qw(diff-tree -z));
4479     push @cmd, qw(--name-only) unless $unrepres;
4480     push @cmd, qw(-r) if $finegrained || $unrepres;
4481     push @cmd, $x, $y;
4482     my $diffs= cmdoutput @cmd;
4483     my $r = 0;
4484     my @lmodes;
4485     foreach my $f (split /\0/, $diffs) {
4486         if ($unrepres && !@lmodes) {
4487             @lmodes = $f =~ m/^\:(\w+) (\w+) \w+ \w+ / or die "$_ ?";
4488             next;
4489         }
4490         my ($oldmode,$newmode) = @lmodes;
4491         @lmodes = ();
4492
4493         next if $f =~ m#^debian(?:/.*)?$#s;
4494
4495         if ($unrepres) {
4496             eval {
4497                 die "deleted\n" unless $newmode =~ m/[^0]/;
4498                 die "not a plain file\n" unless $newmode =~ m/^10\d{4}$/;
4499                 if ($oldmode =~ m/[^0]/) {
4500                     die "mode changed\n" if $oldmode ne $newmode;
4501                 } else {
4502                     die "non-default mode\n" unless $newmode =~ m/^100644$/;
4503                 }
4504             };
4505             if ($@) {
4506                 local $/="\n"; chomp $@;
4507                 push @$unrepres, [ $f, $@ ];
4508             }
4509         }
4510
4511         my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
4512         $r |= $isignore ? 02 : 01;
4513         $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
4514     }
4515     printdebug "quiltify_trees_differ $x $y => $r\n";
4516     return $r;
4517 }
4518
4519 sub quiltify_tree_sentinelfiles ($) {
4520     # lists the `sentinel' files present in the tree
4521     my ($x) = @_;
4522     my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
4523         qw(-- debian/rules debian/control);
4524     $r =~ s/\n/,/g;
4525     return $r;
4526 }
4527
4528 sub quiltify_splitbrain_needed () {
4529     if (!$split_brain) {
4530         progress "dgit view: changes are required...";
4531         runcmd @git, qw(checkout -q -b dgit-view);
4532         $split_brain = 1;
4533     }
4534 }
4535
4536 sub quiltify_splitbrain ($$$$$$) {
4537     my ($clogp, $unapplied, $headref, $diffbits,
4538         $editedignores, $cachekey) = @_;
4539     if ($quilt_mode !~ m/gbp|dpm/) {
4540         # treat .gitignore just like any other upstream file
4541         $diffbits = { %$diffbits };
4542         $_ = !!$_ foreach values %$diffbits;
4543     }
4544     # We would like any commits we generate to be reproducible
4545     my @authline = clogp_authline($clogp);
4546     local $ENV{GIT_COMMITTER_NAME} =  $authline[0];
4547     local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
4548     local $ENV{GIT_COMMITTER_DATE} =  $authline[2];
4549     local $ENV{GIT_AUTHOR_NAME} =  $authline[0];
4550     local $ENV{GIT_AUTHOR_EMAIL} = $authline[1];
4551     local $ENV{GIT_AUTHOR_DATE} =  $authline[2];
4552
4553     if ($quilt_mode =~ m/gbp|unapplied/ &&
4554         ($diffbits->{O2H} & 01)) {
4555         my $msg =
4556  "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
4557  " but git tree differs from orig in upstream files.";
4558         if (!stat_exists "debian/patches") {
4559             $msg .=
4560  "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
4561         }  
4562         fail $msg;
4563     }
4564     if ($quilt_mode =~ m/dpm/ &&
4565         ($diffbits->{H2A} & 01)) {
4566         fail <<END;
4567 --quilt=$quilt_mode specified, implying patches-applied git tree
4568  but git tree differs from result of applying debian/patches to upstream
4569 END
4570     }
4571     if ($quilt_mode =~ m/gbp|unapplied/ &&
4572         ($diffbits->{O2A} & 01)) { # some patches
4573         quiltify_splitbrain_needed();
4574         progress "dgit view: creating patches-applied version using gbp pq";
4575         runcmd shell_cmd 'exec >/dev/null', gbp_pq, qw(import);
4576         # gbp pq import creates a fresh branch; push back to dgit-view
4577         runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
4578         runcmd @git, qw(checkout -q dgit-view);
4579     }
4580     if ($quilt_mode =~ m/gbp|dpm/ &&
4581         ($diffbits->{O2A} & 02)) {
4582         fail <<END
4583 --quilt=$quilt_mode specified, implying that HEAD is for use with a
4584  tool which does not create patches for changes to upstream
4585  .gitignores: but, such patches exist in debian/patches.
4586 END
4587     }
4588     if (($diffbits->{O2H} & 02) && # user has modified .gitignore
4589         !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
4590         quiltify_splitbrain_needed();
4591         progress "dgit view: creating patch to represent .gitignore changes";
4592         ensuredir "debian/patches";
4593         my $gipatch = "debian/patches/auto-gitignore";
4594         open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
4595         stat GIPATCH or die "$gipatch: $!";
4596         fail "$gipatch already exists; but want to create it".
4597             " to record .gitignore changes" if (stat _)[7];
4598         print GIPATCH <<END or die "$gipatch: $!";
4599 Subject: Update .gitignore from Debian packaging branch
4600
4601 The Debian packaging git branch contains these updates to the upstream
4602 .gitignore file(s).  This patch is autogenerated, to provide these
4603 updates to users of the official Debian archive view of the package.
4604
4605 [dgit ($our_version) update-gitignore]
4606 ---
4607 END
4608         close GIPATCH or die "$gipatch: $!";
4609         runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
4610             $unapplied, $headref, "--", sort keys %$editedignores;
4611         open SERIES, "+>>", "debian/patches/series" or die $!;
4612         defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
4613         my $newline;
4614         defined read SERIES, $newline, 1 or die $!;
4615         print SERIES "\n" or die $! unless $newline eq "\n";
4616         print SERIES "auto-gitignore\n" or die $!;
4617         close SERIES or die  $!;
4618         runcmd @git, qw(add -- debian/patches/series), $gipatch;
4619         commit_admin <<END
4620 Commit patch to update .gitignore
4621
4622 [dgit ($our_version) update-gitignore-quilt-fixup]
4623 END
4624     }
4625
4626     my $dgitview = git_rev_parse 'HEAD';
4627
4628     changedir '../../../..';
4629     # When we no longer need to support squeeze, use --create-reflog
4630     # instead of this:
4631     ensuredir ".git/logs/refs/dgit-intern";
4632     my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
4633       or die $!;
4634
4635     my $oldcache = git_get_ref "refs/$splitbraincache";
4636     if ($oldcache eq $dgitview) {
4637         my $tree = cmdoutput qw(git rev-parse), "$dgitview:";
4638         # git update-ref doesn't always update, in this case.  *sigh*
4639         my $dummy = make_commit_text <<END;
4640 tree $tree
4641 parent $dgitview
4642 author Dgit <dgit\@example.com> 1000000000 +0000
4643 committer Dgit <dgit\@example.com> 1000000000 +0000
4644
4645 Dummy commit - do not use
4646 END
4647         runcmd @git, qw(update-ref -m), "dgit $our_version - dummy",
4648             "refs/$splitbraincache", $dummy;
4649     }
4650     runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
4651         $dgitview;
4652
4653     changedir '.git/dgit/unpack/work';
4654
4655     my $saved = maybe_split_brain_save $headref, $dgitview, "converted";
4656     progress "dgit view: created ($saved)";
4657 }
4658
4659 sub quiltify ($$$$) {
4660     my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
4661
4662     # Quilt patchification algorithm
4663     #
4664     # We search backwards through the history of the main tree's HEAD
4665     # (T) looking for a start commit S whose tree object is identical
4666     # to to the patch tip tree (ie the tree corresponding to the
4667     # current dpkg-committed patch series).  For these purposes
4668     # `identical' disregards anything in debian/ - this wrinkle is
4669     # necessary because dpkg-source treates debian/ specially.
4670     #
4671     # We can only traverse edges where at most one of the ancestors'
4672     # trees differs (in changes outside in debian/).  And we cannot
4673     # handle edges which change .pc/ or debian/patches.  To avoid
4674     # going down a rathole we avoid traversing edges which introduce
4675     # debian/rules or debian/control.  And we set a limit on the
4676     # number of edges we are willing to look at.
4677     #
4678     # If we succeed, we walk forwards again.  For each traversed edge
4679     # PC (with P parent, C child) (starting with P=S and ending with
4680     # C=T) to we do this:
4681     #  - git checkout C
4682     #  - dpkg-source --commit with a patch name and message derived from C
4683     # After traversing PT, we git commit the changes which
4684     # should be contained within debian/patches.
4685
4686     # The search for the path S..T is breadth-first.  We maintain a
4687     # todo list containing search nodes.  A search node identifies a
4688     # commit, and looks something like this:
4689     #  $p = {
4690     #      Commit => $git_commit_id,
4691     #      Child => $c,                          # or undef if P=T
4692     #      Whynot => $reason_edge_PC_unsuitable, # in @nots only
4693     #      Nontrivial => true iff $p..$c has relevant changes
4694     #  };
4695
4696     my @todo;
4697     my @nots;
4698     my $sref_S;
4699     my $max_work=100;
4700     my %considered; # saves being exponential on some weird graphs
4701
4702     my $t_sentinels = quiltify_tree_sentinelfiles $target;
4703
4704     my $not = sub {
4705         my ($search,$whynot) = @_;
4706         printdebug " search NOT $search->{Commit} $whynot\n";
4707         $search->{Whynot} = $whynot;
4708         push @nots, $search;
4709         no warnings qw(exiting);
4710         next;
4711     };
4712
4713     push @todo, {
4714         Commit => $target,
4715     };
4716
4717     while (@todo) {
4718         my $c = shift @todo;
4719         next if $considered{$c->{Commit}}++;
4720
4721         $not->($c, "maximum search space exceeded") if --$max_work <= 0;
4722
4723         printdebug "quiltify investigate $c->{Commit}\n";
4724
4725         # are we done?
4726         if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
4727             printdebug " search finished hooray!\n";
4728             $sref_S = $c;
4729             last;
4730         }
4731
4732         if ($quilt_mode eq 'nofix') {
4733             fail "quilt fixup required but quilt mode is \`nofix'\n".
4734                 "HEAD commit $c->{Commit} differs from tree implied by ".
4735                 " debian/patches (tree object $oldtiptree)";
4736         }
4737         if ($quilt_mode eq 'smash') {
4738             printdebug " search quitting smash\n";
4739             last;
4740         }
4741
4742         my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
4743         $not->($c, "has $c_sentinels not $t_sentinels")
4744             if $c_sentinels ne $t_sentinels;
4745
4746         my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
4747         $commitdata =~ m/\n\n/;
4748         $commitdata =~ $`;
4749         my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
4750         @parents = map { { Commit => $_, Child => $c } } @parents;
4751
4752         $not->($c, "root commit") if !@parents;
4753
4754         foreach my $p (@parents) {
4755             $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
4756         }
4757         my $ndiffers = grep { $_->{Nontrivial} } @parents;
4758         $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
4759
4760         foreach my $p (@parents) {
4761             printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
4762
4763             my @cmd= (@git, qw(diff-tree -r --name-only),
4764                       $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
4765             my $patchstackchange = cmdoutput @cmd;
4766             if (length $patchstackchange) {
4767                 $patchstackchange =~ s/\n/,/g;
4768                 $not->($p, "changed $patchstackchange");
4769             }
4770
4771             printdebug " search queue P=$p->{Commit} ",
4772                 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
4773             push @todo, $p;
4774         }
4775     }
4776
4777     if (!$sref_S) {
4778         printdebug "quiltify want to smash\n";
4779
4780         my $abbrev = sub {
4781             my $x = $_[0]{Commit};
4782             $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
4783             return $x;
4784         };
4785         my $reportnot = sub {
4786             my ($notp) = @_;
4787             my $s = $abbrev->($notp);
4788             my $c = $notp->{Child};
4789             $s .= "..".$abbrev->($c) if $c;
4790             $s .= ": ".$notp->{Whynot};
4791             return $s;
4792         };
4793         if ($quilt_mode eq 'linear') {
4794             print STDERR "$us: quilt fixup cannot be linear.  Stopped at:\n";
4795             foreach my $notp (@nots) {
4796                 print STDERR "$us:  ", $reportnot->($notp), "\n";
4797             }
4798             print STDERR "$us: $_\n" foreach @$failsuggestion;
4799             fail "quilt fixup naive history linearisation failed.\n".
4800  "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
4801         } elsif ($quilt_mode eq 'smash') {
4802         } elsif ($quilt_mode eq 'auto') {
4803             progress "quilt fixup cannot be linear, smashing...";
4804         } else {
4805             die "$quilt_mode ?";
4806         }
4807
4808         my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
4809         $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
4810         my $ncommits = 3;
4811         my $msg = cmdoutput @git, qw(log), "-n$ncommits";
4812
4813         quiltify_dpkg_commit "auto-$version-$target-$time",
4814             (getfield $clogp, 'Maintainer'),
4815             "Automatically generated patch ($clogp->{Version})\n".
4816             "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
4817         return;
4818     }
4819
4820     progress "quiltify linearisation planning successful, executing...";
4821
4822     for (my $p = $sref_S;
4823          my $c = $p->{Child};
4824          $p = $p->{Child}) {
4825         printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
4826         next unless $p->{Nontrivial};
4827
4828         my $cc = $c->{Commit};
4829
4830         my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
4831         $commitdata =~ m/\n\n/ or die "$c ?";
4832         $commitdata = $`;
4833         my $msg = $'; #';
4834         $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
4835         my $author = $1;
4836
4837         my $commitdate = cmdoutput
4838             @git, qw(log -n1 --pretty=format:%aD), $cc;
4839
4840         $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
4841
4842         my $strip_nls = sub { $msg =~ s/\n+$//; $msg .= "\n"; };
4843         $strip_nls->();
4844
4845         my $title = $1;
4846         my $patchname;
4847         my $patchdir;
4848
4849         my $gbp_check_suitable = sub {
4850             $_ = shift;
4851             my ($what) = @_;
4852
4853             eval {
4854                 die "contains unexpected slashes\n" if m{//} || m{/$};
4855                 die "contains leading punctuation\n" if m{^\W} || m{/\W};
4856                 die "contains bad character(s)\n" if m{[^-a-z0-9_.+=~/]}i;
4857                 die "too long" if length > 200;
4858             };
4859             return $_ unless $@;
4860             print STDERR "quiltifying commit $cc:".
4861                 " ignoring/dropping Gbp-Pq $what: $@";
4862             return undef;
4863         };
4864
4865         if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* name \s+ |
4866                            gbp-pq-name: \s* )
4867                        (\S+) \s* \n //ixm) {
4868             $patchname = $gbp_check_suitable->($1, 'Name');
4869         }
4870         if ($msg =~ s/^ (?: gbp(?:-pq)? : \s* topic \s+ |
4871                            gbp-pq-topic: \s* )
4872                        (\S+) \s* \n //ixm) {
4873             $patchdir = $gbp_check_suitable->($1, 'Topic');
4874         }
4875
4876         $strip_nls->();
4877
4878         if (!defined $patchname) {
4879             $patchname = $title;
4880             $patchname =~ s/[.:]$//;
4881             use Text::Iconv;
4882             eval {
4883                 my $converter = new Text::Iconv qw(UTF-8 ASCII//TRANSLIT);
4884                 my $translitname = $converter->convert($patchname);
4885                 die unless defined $translitname;
4886                 $patchname = $translitname;
4887             };
4888             print STDERR
4889                 "dgit: patch title transliteration error: $@"
4890                 if $@;
4891             $patchname =~ y/ A-Z/-a-z/;
4892             $patchname =~ y/-a-z0-9_.+=~//cd;
4893             $patchname =~ s/^\W/x-$&/;
4894             $patchname = substr($patchname,0,40);
4895         }
4896         if (!defined $patchdir) {
4897             $patchdir = '';
4898         }
4899         if (length $patchdir) {
4900             $patchname = "$patchdir/$patchname";
4901         }
4902         if ($patchname =~ m{^(.*)/}) {
4903             mkpath "debian/patches/$1";
4904         }
4905
4906         my $index;
4907         for ($index='';
4908              stat "debian/patches/$patchname$index";
4909              $index++) { }
4910         $!==ENOENT or die "$patchname$index $!";
4911
4912         runcmd @git, qw(checkout -q), $cc;
4913
4914         # We use the tip's changelog so that dpkg-source doesn't
4915         # produce complaining messages from dpkg-parsechangelog.  None
4916         # of the information dpkg-source gets from the changelog is
4917         # actually relevant - it gets put into the original message
4918         # which dpkg-source provides our stunt editor, and then
4919         # overwritten.
4920         runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
4921
4922         quiltify_dpkg_commit "$patchname$index", $author, $msg,
4923             "Date: $commitdate\n".
4924             "X-Dgit-Generated: $clogp->{Version} $cc\n";
4925
4926         runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
4927     }
4928
4929     runcmd @git, qw(checkout -q master);
4930 }
4931
4932 sub build_maybe_quilt_fixup () {
4933     my ($format,$fopts) = get_source_format;
4934     return unless madformat_wantfixup $format;
4935     # sigh
4936
4937     check_for_vendor_patches();
4938
4939     if (quiltmode_splitbrain) {
4940         fail <<END unless access_cfg_tagformats_can_splitbrain;
4941 quilt mode $quilt_mode requires split view so server needs to support
4942  both "new" and "maint" tag formats, but config says it doesn't.
4943 END
4944     }
4945
4946     my $clogp = parsechangelog();
4947     my $headref = git_rev_parse('HEAD');
4948
4949     prep_ud();
4950     changedir $ud;
4951
4952     my $upstreamversion = upstreamversion $version;
4953
4954     if ($fopts->{'single-debian-patch'}) {
4955         quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
4956     } else {
4957         quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
4958     }
4959
4960     die 'bug' if $split_brain && !$need_split_build_invocation;
4961
4962     changedir '../../../..';
4963     runcmd_ordryrun_local
4964         @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
4965 }
4966
4967 sub quilt_fixup_mkwork ($) {
4968     my ($headref) = @_;
4969
4970     mkdir "work" or die $!;
4971     changedir "work";
4972     mktree_in_ud_here();
4973     runcmd @git, qw(reset -q --hard), $headref;
4974 }
4975
4976 sub quilt_fixup_linkorigs ($$) {
4977     my ($upstreamversion, $fn) = @_;
4978     # calls $fn->($leafname);
4979
4980     foreach my $f (<../../../../*>) { #/){
4981         my $b=$f; $b =~ s{.*/}{};
4982         {
4983             local ($debuglevel) = $debuglevel-1;
4984             printdebug "QF linkorigs $b, $f ?\n";
4985         }
4986         next unless is_orig_file_of_vsn $b, $upstreamversion;
4987         printdebug "QF linkorigs $b, $f Y\n";
4988         link_ltarget $f, $b or die "$b $!";
4989         $fn->($b);
4990     }
4991 }
4992
4993 sub quilt_fixup_delete_pc () {
4994     runcmd @git, qw(rm -rqf .pc);
4995     commit_admin <<END
4996 Commit removal of .pc (quilt series tracking data)
4997
4998 [dgit ($our_version) upgrade quilt-remove-pc]
4999 END
5000 }
5001
5002 sub quilt_fixup_singlepatch ($$$) {
5003     my ($clogp, $headref, $upstreamversion) = @_;
5004
5005     progress "starting quiltify (single-debian-patch)";
5006
5007     # dpkg-source --commit generates new patches even if
5008     # single-debian-patch is in debian/source/options.  In order to
5009     # get it to generate debian/patches/debian-changes, it is
5010     # necessary to build the source package.
5011
5012     quilt_fixup_linkorigs($upstreamversion, sub { });
5013     quilt_fixup_mkwork($headref);
5014
5015     rmtree("debian/patches");
5016
5017     runcmd @dpkgsource, qw(-b .);
5018     changedir "..";
5019     runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
5020     rename srcfn("$upstreamversion", "/debian/patches"), 
5021            "work/debian/patches";
5022
5023     changedir "work";
5024     commit_quilty_patch();
5025 }
5026
5027 sub quilt_make_fake_dsc ($) {
5028     my ($upstreamversion) = @_;
5029
5030     my $fakeversion="$upstreamversion-~~DGITFAKE";
5031
5032     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
5033     print $fakedsc <<END or die $!;
5034 Format: 3.0 (quilt)
5035 Source: $package
5036 Version: $fakeversion
5037 Files:
5038 END
5039
5040     my $dscaddfile=sub {
5041         my ($b) = @_;
5042         
5043         my $md = new Digest::MD5;
5044
5045         my $fh = new IO::File $b, '<' or die "$b $!";
5046         stat $fh or die $!;
5047         my $size = -s _;
5048
5049         $md->addfile($fh);
5050         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
5051     };
5052
5053     quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
5054
5055     my @files=qw(debian/source/format debian/rules
5056                  debian/control debian/changelog);
5057     foreach my $maybe (qw(debian/patches debian/source/options
5058                           debian/tests/control)) {
5059         next unless stat_exists "../../../$maybe";
5060         push @files, $maybe;
5061     }
5062
5063     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
5064     runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
5065
5066     $dscaddfile->($debtar);
5067     close $fakedsc or die $!;
5068 }
5069
5070 sub quilt_check_splitbrain_cache ($$) {
5071     my ($headref, $upstreamversion) = @_;
5072     # Called only if we are in (potentially) split brain mode.
5073     # Called in $ud.
5074     # Computes the cache key and looks in the cache.
5075     # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
5076
5077     my $splitbrain_cachekey;
5078     
5079     progress
5080  "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
5081     # we look in the reflog of dgit-intern/quilt-cache
5082     # we look for an entry whose message is the key for the cache lookup
5083     my @cachekey = (qw(dgit), $our_version);
5084     push @cachekey, $upstreamversion;
5085     push @cachekey, $quilt_mode;
5086     push @cachekey, $headref;
5087
5088     push @cachekey, hashfile('fake.dsc');
5089
5090     my $srcshash = Digest::SHA->new(256);
5091     my %sfs = ( %INC, '$0(dgit)' => $0 );
5092     foreach my $sfk (sort keys %sfs) {
5093         next unless $sfk =~ m/^\$0\b/ || $sfk =~ m{^Debian/Dgit\b};
5094         $srcshash->add($sfk,"  ");
5095         $srcshash->add(hashfile($sfs{$sfk}));
5096         $srcshash->add("\n");
5097     }
5098     push @cachekey, $srcshash->hexdigest();
5099     $splitbrain_cachekey = "@cachekey";
5100
5101     my @cmd = (@git, qw(log -g), '--pretty=format:%H %gs',
5102                $splitbraincache);
5103     printdebug "splitbrain cachekey $splitbrain_cachekey\n";
5104     debugcmd "|(probably)",@cmd;
5105     my $child = open GC, "-|";  defined $child or die $!;
5106     if (!$child) {
5107         chdir '../../..' or die $!;
5108         if (!stat ".git/logs/refs/$splitbraincache") {
5109             $! == ENOENT or die $!;
5110             printdebug ">(no reflog)\n";
5111             exit 0;
5112         }
5113         exec @cmd; die $!;
5114     }
5115     while (<GC>) {
5116         chomp;
5117         printdebug ">| ", $_, "\n" if $debuglevel > 1;
5118         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
5119             
5120         my $cachehit = $1;
5121         quilt_fixup_mkwork($headref);
5122         my $saved = maybe_split_brain_save $headref, $cachehit, "cache-hit";
5123         if ($cachehit ne $headref) {
5124             progress "dgit view: found cached ($saved)";
5125             runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
5126             $split_brain = 1;
5127             return ($cachehit, $splitbrain_cachekey);
5128         }
5129         progress "dgit view: found cached, no changes required";
5130         return ($headref, $splitbrain_cachekey);
5131     }
5132     die $! if GC->error;
5133     failedcmd unless close GC;
5134
5135     printdebug "splitbrain cache miss\n";
5136     return (undef, $splitbrain_cachekey);
5137 }
5138
5139 sub quilt_fixup_multipatch ($$$) {
5140     my ($clogp, $headref, $upstreamversion) = @_;
5141
5142     progress "examining quilt state (multiple patches, $quilt_mode mode)";
5143
5144     # Our objective is:
5145     #  - honour any existing .pc in case it has any strangeness
5146     #  - determine the git commit corresponding to the tip of
5147     #    the patch stack (if there is one)
5148     #  - if there is such a git commit, convert each subsequent
5149     #    git commit into a quilt patch with dpkg-source --commit
5150     #  - otherwise convert all the differences in the tree into
5151     #    a single git commit
5152     #
5153     # To do this we:
5154
5155     # Our git tree doesn't necessarily contain .pc.  (Some versions of
5156     # dgit would include the .pc in the git tree.)  If there isn't
5157     # one, we need to generate one by unpacking the patches that we
5158     # have.
5159     #
5160     # We first look for a .pc in the git tree.  If there is one, we
5161     # will use it.  (This is not the normal case.)
5162     #
5163     # Otherwise need to regenerate .pc so that dpkg-source --commit
5164     # can work.  We do this as follows:
5165     #     1. Collect all relevant .orig from parent directory
5166     #     2. Generate a debian.tar.gz out of
5167     #         debian/{patches,rules,source/format,source/options}
5168     #     3. Generate a fake .dsc containing just these fields:
5169     #          Format Source Version Files
5170     #     4. Extract the fake .dsc
5171     #        Now the fake .dsc has a .pc directory.
5172     # (In fact we do this in every case, because in future we will
5173     # want to search for a good base commit for generating patches.)
5174     #
5175     # Then we can actually do the dpkg-source --commit
5176     #     1. Make a new working tree with the same object
5177     #        store as our main tree and check out the main
5178     #        tree's HEAD.
5179     #     2. Copy .pc from the fake's extraction, if necessary
5180     #     3. Run dpkg-source --commit
5181     #     4. If the result has changes to debian/, then
5182     #          - git add them them
5183     #          - git add .pc if we had a .pc in-tree
5184     #          - git commit
5185     #     5. If we had a .pc in-tree, delete it, and git commit
5186     #     6. Back in the main tree, fast forward to the new HEAD
5187
5188     # Another situation we may have to cope with is gbp-style
5189     # patches-unapplied trees.
5190     #
5191     # We would want to detect these, so we know to escape into
5192     # quilt_fixup_gbp.  However, this is in general not possible.
5193     # Consider a package with a one patch which the dgit user reverts
5194     # (with git revert or the moral equivalent).
5195     #
5196     # That is indistinguishable in contents from a patches-unapplied
5197     # tree.  And looking at the history to distinguish them is not
5198     # useful because the user might have made a confusing-looking git
5199     # history structure (which ought to produce an error if dgit can't
5200     # cope, not a silent reintroduction of an unwanted patch).
5201     #
5202     # So gbp users will have to pass an option.  But we can usually
5203     # detect their failure to do so: if the tree is not a clean
5204     # patches-applied tree, quilt linearisation fails, but the tree
5205     # _is_ a clean patches-unapplied tree, we can suggest that maybe
5206     # they want --quilt=unapplied.
5207     #
5208     # To help detect this, when we are extracting the fake dsc, we
5209     # first extract it with --skip-patches, and then apply the patches
5210     # afterwards with dpkg-source --before-build.  That lets us save a
5211     # tree object corresponding to .origs.
5212
5213     my $splitbrain_cachekey;
5214
5215     quilt_make_fake_dsc($upstreamversion);
5216
5217     if (quiltmode_splitbrain()) {
5218         my $cachehit;
5219         ($cachehit, $splitbrain_cachekey) =
5220             quilt_check_splitbrain_cache($headref, $upstreamversion);
5221         return if $cachehit;
5222     }
5223
5224     runcmd qw(sh -ec),
5225         'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
5226
5227     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
5228     rename $fakexdir, "fake" or die "$fakexdir $!";
5229
5230     changedir 'fake';
5231
5232     remove_stray_gits("source package");
5233     mktree_in_ud_here();
5234
5235     rmtree '.pc';
5236
5237     my $unapplied=git_add_write_tree();
5238     printdebug "fake orig tree object $unapplied\n";
5239
5240     ensuredir '.pc';
5241
5242     my @bbcmd = (qw(sh -ec), 'exec dpkg-source --before-build . >/dev/null');
5243     $!=0; $?=-1;
5244     if (system @bbcmd) {
5245         failedcmd @bbcmd if $? < 0;
5246         fail <<END;
5247 failed to apply your git tree's patch stack (from debian/patches/) to
5248  the corresponding upstream tarball(s).  Your source tree and .orig
5249  are probably too inconsistent.  dgit can only fix up certain kinds of
5250  anomaly (depending on the quilt mode).  See --quilt= in dgit(1).
5251 END
5252     }
5253
5254     changedir '..';
5255
5256     quilt_fixup_mkwork($headref);
5257
5258     my $mustdeletepc=0;
5259     if (stat_exists ".pc") {
5260         -d _ or die;
5261         progress "Tree already contains .pc - will use it then delete it.";
5262         $mustdeletepc=1;
5263     } else {
5264         rename '../fake/.pc','.pc' or die $!;
5265     }
5266
5267     changedir '../fake';
5268     rmtree '.pc';
5269     my $oldtiptree=git_add_write_tree();
5270     printdebug "fake o+d/p tree object $unapplied\n";
5271     changedir '../work';
5272
5273
5274     # We calculate some guesswork now about what kind of tree this might
5275     # be.  This is mostly for error reporting.
5276
5277     my %editedignores;
5278     my @unrepres;
5279     my $diffbits = {
5280         # H = user's HEAD
5281         # O = orig, without patches applied
5282         # A = "applied", ie orig with H's debian/patches applied
5283         O2H => quiltify_trees_differ($unapplied,$headref,   1,
5284                                      \%editedignores, \@unrepres),
5285         H2A => quiltify_trees_differ($headref,  $oldtiptree,1),
5286         O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
5287     };
5288
5289     my @dl;
5290     foreach my $b (qw(01 02)) {
5291         foreach my $v (qw(O2H O2A H2A)) {
5292             push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
5293         }
5294     }
5295     printdebug "differences \@dl @dl.\n";
5296
5297     progress sprintf
5298 "$us: base trees orig=%.20s o+d/p=%.20s",
5299               $unapplied, $oldtiptree;
5300     progress sprintf
5301 "$us: quilt differences: src:  %s orig %s     gitignores:  %s orig %s\n".
5302 "$us: quilt differences:      HEAD %s o+d/p               HEAD %s o+d/p",
5303                              $dl[0], $dl[1],              $dl[3], $dl[4],
5304                                  $dl[2],                     $dl[5];
5305
5306     if (@unrepres) {
5307         print STDERR "dgit:  cannot represent change: $_->[1]: $_->[0]\n"
5308             foreach @unrepres;
5309         forceable_fail [qw(unrepresentable)], <<END;
5310 HEAD has changes to .orig[s] which are not representable by `3.0 (quilt)'
5311 END
5312     }
5313
5314     my @failsuggestion;
5315     if (!($diffbits->{O2H} & $diffbits->{O2A})) {
5316         push @failsuggestion, "This might be a patches-unapplied branch.";
5317     }  elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
5318         push @failsuggestion, "This might be a patches-applied branch.";
5319     }
5320     push @failsuggestion, "Maybe you need to specify one of".
5321         " --[quilt=]gbp --[quilt=]dpm --quilt=unapplied ?";
5322
5323     if (quiltmode_splitbrain()) {
5324         quiltify_splitbrain($clogp, $unapplied, $headref,
5325                             $diffbits, \%editedignores,
5326                             $splitbrain_cachekey);
5327         return;
5328     }
5329
5330     progress "starting quiltify (multiple patches, $quilt_mode mode)";
5331     quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
5332
5333     if (!open P, '>>', ".pc/applied-patches") {
5334         $!==&ENOENT or die $!;
5335     } else {
5336         close P;
5337     }
5338
5339     commit_quilty_patch();
5340
5341     if ($mustdeletepc) {
5342         quilt_fixup_delete_pc();
5343     }
5344 }
5345
5346 sub quilt_fixup_editor () {
5347     my $descfn = $ENV{$fakeeditorenv};
5348     my $editing = $ARGV[$#ARGV];
5349     open I1, '<', $descfn or die "$descfn: $!";
5350     open I2, '<', $editing or die "$editing: $!";
5351     unlink $editing or die "$editing: $!";
5352     open O, '>', $editing or die "$editing: $!";
5353     while (<I1>) { print O or die $!; } I1->error and die $!;
5354     my $copying = 0;
5355     while (<I2>) {
5356         $copying ||= m/^\-\-\- /;
5357         next unless $copying;
5358         print O or die $!;
5359     }
5360     I2->error and die $!;
5361     close O or die $1;
5362     exit 0;
5363 }
5364
5365 sub maybe_apply_patches_dirtily () {
5366     return unless $quilt_mode =~ m/gbp|unapplied/;
5367     print STDERR <<END or die $!;
5368
5369 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
5370 dgit: Have to apply the patches - making the tree dirty.
5371 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
5372
5373 END
5374     $patches_applied_dirtily = 01;
5375     $patches_applied_dirtily |= 02 unless stat_exists '.pc';
5376     runcmd qw(dpkg-source --before-build .);
5377 }
5378
5379 sub maybe_unapply_patches_again () {
5380     progress "dgit: Unapplying patches again to tidy up the tree."
5381         if $patches_applied_dirtily;
5382     runcmd qw(dpkg-source --after-build .)
5383         if $patches_applied_dirtily & 01;
5384     rmtree '.pc'
5385         if $patches_applied_dirtily & 02;
5386     $patches_applied_dirtily = 0;
5387 }
5388
5389 #----- other building -----
5390
5391 our $clean_using_builder;
5392 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
5393 #   clean the tree before building (perhaps invoked indirectly by
5394 #   whatever we are using to run the build), rather than separately
5395 #   and explicitly by us.
5396
5397 sub clean_tree () {
5398     return if $clean_using_builder;
5399     if ($cleanmode eq 'dpkg-source') {
5400         maybe_apply_patches_dirtily();
5401         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
5402     } elsif ($cleanmode eq 'dpkg-source-d') {
5403         maybe_apply_patches_dirtily();
5404         runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
5405     } elsif ($cleanmode eq 'git') {
5406         runcmd_ordryrun_local @git, qw(clean -xdf);
5407     } elsif ($cleanmode eq 'git-ff') {
5408         runcmd_ordryrun_local @git, qw(clean -xdff);
5409     } elsif ($cleanmode eq 'check') {
5410         my $leftovers = cmdoutput @git, qw(clean -xdn);
5411         if (length $leftovers) {
5412             print STDERR $leftovers, "\n" or die $!;
5413             fail "tree contains uncommitted files and --clean=check specified";
5414         }
5415     } elsif ($cleanmode eq 'none') {
5416     } else {
5417         die "$cleanmode ?";
5418     }
5419 }
5420
5421 sub cmd_clean () {
5422     badusage "clean takes no additional arguments" if @ARGV;
5423     notpushing();
5424     clean_tree();
5425     maybe_unapply_patches_again();
5426 }
5427
5428 sub build_prep_early () {
5429     our $build_prep_early_done //= 0;
5430     return if $build_prep_early_done++;
5431     notpushing();
5432     badusage "-p is not allowed when building" if defined $package;
5433     my $clogp = parsechangelog();
5434     $isuite = getfield $clogp, 'Distribution';
5435     $package = getfield $clogp, 'Source';
5436     $version = getfield $clogp, 'Version';
5437     check_not_dirty();
5438 }
5439
5440 sub build_prep () {
5441     build_prep_early();
5442     clean_tree();
5443     build_maybe_quilt_fixup();
5444     if ($rmchanges) {
5445         my $pat = changespat $version;
5446         foreach my $f (glob "$buildproductsdir/$pat") {
5447             if (act_local()) {
5448                 unlink $f or fail "remove old changes file $f: $!";
5449             } else {
5450                 progress "would remove $f";
5451             }
5452         }
5453     }
5454 }
5455
5456 sub changesopts_initial () {
5457     my @opts =@changesopts[1..$#changesopts];
5458 }
5459
5460 sub changesopts_version () {
5461     if (!defined $changes_since_version) {
5462         my @vsns = archive_query('archive_query');
5463         my @quirk = access_quirk();
5464         if ($quirk[0] eq 'backports') {
5465             local $isuite = $quirk[2];
5466             local $csuite;
5467             canonicalise_suite();
5468             push @vsns, archive_query('archive_query');
5469         }
5470         if (@vsns) {
5471             @vsns = map { $_->[0] } @vsns;
5472             @vsns = sort { -version_compare($a, $b) } @vsns;
5473             $changes_since_version = $vsns[0];
5474             progress "changelog will contain changes since $vsns[0]";
5475         } else {
5476             $changes_since_version = '_';
5477             progress "package seems new, not specifying -v<version>";
5478         }
5479     }
5480     if ($changes_since_version ne '_') {
5481         return ("-v$changes_since_version");
5482     } else {
5483         return ();
5484     }
5485 }
5486
5487 sub changesopts () {
5488     return (changesopts_initial(), changesopts_version());
5489 }
5490
5491 sub massage_dbp_args ($;$) {
5492     my ($cmd,$xargs) = @_;
5493     # We need to:
5494     #
5495     #  - if we're going to split the source build out so we can
5496     #    do strange things to it, massage the arguments to dpkg-buildpackage
5497     #    so that the main build doessn't build source (or add an argument
5498     #    to stop it building source by default).
5499     #
5500     #  - add -nc to stop dpkg-source cleaning the source tree,
5501     #    unless we're not doing a split build and want dpkg-source
5502     #    as cleanmode, in which case we can do nothing
5503     #
5504     # return values:
5505     #    0 - source will NOT need to be built separately by caller
5506     #   +1 - source will need to be built separately by caller
5507     #   +2 - source will need to be built separately by caller AND
5508     #        dpkg-buildpackage should not in fact be run at all!
5509     debugcmd '#massaging#', @$cmd if $debuglevel>1;
5510 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
5511     if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
5512         $clean_using_builder = 1;
5513         return 0;
5514     }
5515     # -nc has the side effect of specifying -b if nothing else specified
5516     # and some combinations of -S, -b, et al, are errors, rather than
5517     # later simply overriding earlie.  So we need to:
5518     #  - search the command line for these options
5519     #  - pick the last one
5520     #  - perhaps add our own as a default
5521     #  - perhaps adjust it to the corresponding non-source-building version
5522     my $dmode = '-F';
5523     foreach my $l ($cmd, $xargs) {
5524         next unless $l;
5525         @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
5526     }
5527     push @$cmd, '-nc';
5528 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
5529     my $r = 0;
5530     if ($need_split_build_invocation) {
5531         printdebug "massage split $dmode.\n";
5532         $r = $dmode =~ m/[S]/     ? +2 :
5533              $dmode =~ y/gGF/ABb/ ? +1 :
5534              $dmode =~ m/[ABb]/   ?  0 :
5535              die "$dmode ?";
5536     }
5537     printdebug "massage done $r $dmode.\n";
5538     push @$cmd, $dmode;
5539 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
5540     return $r;
5541 }
5542
5543 sub in_parent (&) {
5544     my ($fn) = @_;
5545     my $wasdir = must_getcwd();
5546     changedir "..";
5547     $fn->();
5548     changedir $wasdir;
5549 }    
5550
5551 sub postbuild_mergechanges ($) { # must run with CWD=.. (eg in in_parent)
5552     my ($msg_if_onlyone) = @_;
5553     # If there is only one .changes file, fail with $msg_if_onlyone,
5554     # or if that is undef, be a no-op.
5555     # Returns the changes file to report to the user.
5556     my $pat = changespat $version;
5557     my @changesfiles = glob $pat;
5558     @changesfiles = sort {
5559         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
5560             or $a cmp $b
5561     } @changesfiles;
5562     my $result;
5563     if (@changesfiles==1) {
5564         fail <<END.$msg_if_onlyone if defined $msg_if_onlyone;
5565 only one changes file from build (@changesfiles)
5566 END
5567         $result = $changesfiles[0];
5568     } elsif (@changesfiles==2) {
5569         my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
5570         foreach my $l (split /\n/, getfield $binchanges, 'Files') {
5571             fail "$l found in binaries changes file $binchanges"
5572                 if $l =~ m/\.dsc$/;
5573         }
5574         runcmd_ordryrun_local @mergechanges, @changesfiles;
5575         my $multichanges = changespat $version,'multi';
5576         if (act_local()) {
5577             stat_exists $multichanges or fail "$multichanges: $!";
5578             foreach my $cf (glob $pat) {
5579                 next if $cf eq $multichanges;
5580                 rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
5581             }
5582         }
5583         $result = $multichanges;
5584     } else {
5585         fail "wrong number of different changes files (@changesfiles)";
5586     }
5587     printdone "build successful, results in $result\n" or die $!;
5588 }
5589
5590 sub midbuild_checkchanges () {
5591     my $pat = changespat $version;
5592     return if $rmchanges;
5593     my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
5594     @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
5595     fail <<END
5596 changes files other than source matching $pat already present; building would result in ambiguity about the intended results.
5597 Suggest you delete @unwanted.
5598 END
5599         if @unwanted;
5600 }
5601
5602 sub midbuild_checkchanges_vanilla ($) {
5603     my ($wantsrc) = @_;
5604     midbuild_checkchanges() if $wantsrc == 1;
5605 }
5606
5607 sub postbuild_mergechanges_vanilla ($) {
5608     my ($wantsrc) = @_;
5609     if ($wantsrc == 1) {
5610         in_parent {
5611             postbuild_mergechanges(undef);
5612         };
5613     } else {
5614         printdone "build successful\n";
5615     }
5616 }
5617
5618 sub cmd_build {
5619     my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
5620     my $wantsrc = massage_dbp_args \@dbp;
5621     if ($wantsrc > 0) {
5622         build_source();
5623         midbuild_checkchanges_vanilla $wantsrc;
5624     } else {
5625         build_prep();
5626     }
5627     if ($wantsrc < 2) {
5628         push @dbp, changesopts_version();
5629         maybe_apply_patches_dirtily();
5630         runcmd_ordryrun_local @dbp;
5631     }
5632     maybe_unapply_patches_again();
5633     postbuild_mergechanges_vanilla $wantsrc;
5634 }
5635
5636 sub pre_gbp_build {
5637     $quilt_mode //= 'gbp';
5638 }
5639
5640 sub cmd_gbp_build {
5641     build_prep_early();
5642
5643     # gbp can make .origs out of thin air.  In my tests it does this
5644     # even for a 1.0 format package, with no origs present.  So I
5645     # guess it keys off just the version number.  We don't know
5646     # exactly what .origs ought to exist, but let's assume that we
5647     # should run gbp if: the version has an upstream part and the main
5648     # orig is absent.
5649     my $upstreamversion = upstreamversion $version;
5650     my $origfnpat = srcfn $upstreamversion, '.orig.tar.*';
5651     my $gbp_make_orig = $version =~ m/-/ && !(() = glob "../$origfnpat");
5652
5653     if ($gbp_make_orig) {
5654         clean_tree();
5655         $cleanmode = 'none'; # don't do it again
5656         $need_split_build_invocation = 1;
5657     }
5658
5659     my @dbp = @dpkgbuildpackage;
5660
5661     my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
5662
5663     if (!length $gbp_build[0]) {
5664         if (length executable_on_path('git-buildpackage')) {
5665             $gbp_build[0] = qw(git-buildpackage);
5666         } else {
5667             $gbp_build[0] = 'gbp buildpackage';
5668         }
5669     }
5670     my @cmd = opts_opt_multi_cmd @gbp_build;
5671
5672     push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
5673
5674     if ($gbp_make_orig) {
5675         ensuredir '.git/dgit';
5676         my $ok = '.git/dgit/origs-gen-ok';
5677         unlink $ok or $!==&ENOENT or die $!;
5678         my @origs_cmd = @cmd;
5679         push @origs_cmd, qw(--git-cleaner=true);
5680         push @origs_cmd, "--git-prebuild=touch $ok .git/dgit/no-such-dir/ok";
5681         push @origs_cmd, @ARGV;
5682         if (act_local()) {
5683             debugcmd @origs_cmd;
5684             system @origs_cmd;
5685             do { local $!; stat_exists $ok; }
5686                 or failedcmd @origs_cmd;
5687         } else {
5688             dryrun_report @origs_cmd;
5689         }
5690     }
5691
5692     if ($wantsrc > 0) {
5693         build_source();
5694         midbuild_checkchanges_vanilla $wantsrc;
5695     } else {
5696         if (!$clean_using_builder) {
5697             push @cmd, '--git-cleaner=true';
5698         }
5699         build_prep();
5700     }
5701     maybe_unapply_patches_again();
5702     if ($wantsrc < 2) {
5703         push @cmd, changesopts();
5704         runcmd_ordryrun_local @cmd, @ARGV;
5705     }
5706     postbuild_mergechanges_vanilla $wantsrc;
5707 }
5708 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
5709
5710 sub build_source {
5711     my $our_cleanmode = $cleanmode;
5712     if ($need_split_build_invocation) {
5713         # Pretend that clean is being done some other way.  This
5714         # forces us not to try to use dpkg-buildpackage to clean and
5715         # build source all in one go; and instead we run dpkg-source
5716         # (and build_prep() will do the clean since $clean_using_builder
5717         # is false).
5718         $our_cleanmode = 'ELSEWHERE';
5719     }
5720     if ($our_cleanmode =~ m/^dpkg-source/) {
5721         # dpkg-source invocation (below) will clean, so build_prep shouldn't
5722         $clean_using_builder = 1;
5723     }
5724     build_prep();
5725     $sourcechanges = changespat $version,'source';
5726     if (act_local()) {
5727         unlink "../$sourcechanges" or $!==ENOENT
5728             or fail "remove $sourcechanges: $!";
5729     }
5730     $dscfn = dscfn($version);
5731     if ($our_cleanmode eq 'dpkg-source') {
5732         maybe_apply_patches_dirtily();
5733         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
5734             changesopts();
5735     } elsif ($our_cleanmode eq 'dpkg-source-d') {
5736         maybe_apply_patches_dirtily();
5737         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
5738             changesopts();
5739     } else {
5740         my @cmd = (@dpkgsource, qw(-b --));
5741         if ($split_brain) {
5742             changedir $ud;
5743             runcmd_ordryrun_local @cmd, "work";
5744             my @udfiles = <${package}_*>;
5745             changedir "../../..";
5746             foreach my $f (@udfiles) {
5747                 printdebug "source copy, found $f\n";
5748                 next unless
5749                     $f eq $dscfn or
5750                     ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
5751                      $f eq srcfn($version, $&));
5752                 printdebug "source copy, found $f - renaming\n";
5753                 rename "$ud/$f", "../$f" or $!==ENOENT
5754                     or fail "put in place new source file ($f): $!";
5755             }
5756         } else {
5757             my $pwd = must_getcwd();
5758             my $leafdir = basename $pwd;
5759             changedir "..";
5760             runcmd_ordryrun_local @cmd, $leafdir;
5761             changedir $pwd;
5762         }
5763         runcmd_ordryrun_local qw(sh -ec),
5764             'exec >$1; shift; exec "$@"','x',
5765             "../$sourcechanges",
5766             @dpkggenchanges, qw(-S), changesopts();
5767     }
5768 }
5769
5770 sub cmd_build_source {
5771     badusage "build-source takes no additional arguments" if @ARGV;
5772     build_source();
5773     maybe_unapply_patches_again();
5774     printdone "source built, results in $dscfn and $sourcechanges";
5775 }
5776
5777 sub cmd_sbuild {
5778     build_source();
5779     midbuild_checkchanges();
5780     in_parent {
5781         if (act_local()) {
5782             stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
5783             stat_exists $sourcechanges
5784                 or fail "$sourcechanges (in parent directory): $!";
5785         }
5786         runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
5787     };
5788     maybe_unapply_patches_again();
5789     in_parent {
5790         postbuild_mergechanges(<<END);
5791 perhaps you need to pass -A ?  (sbuild's default is to build only
5792 arch-specific binaries; dgit 1.4 used to override that.)
5793 END
5794     };
5795 }    
5796
5797 sub cmd_quilt_fixup {
5798     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
5799     my $clogp = parsechangelog();
5800     $version = getfield $clogp, 'Version';
5801     $package = getfield $clogp, 'Source';
5802     check_not_dirty();
5803     clean_tree();
5804     build_maybe_quilt_fixup();
5805 }
5806
5807 sub cmd_import_dsc {
5808     my $needsig = 0;
5809
5810     while (@ARGV) {
5811         last unless $ARGV[0] =~ m/^-/;
5812         $_ = shift @ARGV;
5813         last if m/^--?$/;
5814         if (m/^--require-valid-signature$/) {
5815             $needsig = 1;
5816         } else {
5817             badusage "unknown dgit import-dsc sub-option \`$_'";
5818         }
5819     }
5820
5821     badusage "usage: dgit import-dsc .../PATH/TO/.DSC BRANCH" unless @ARGV==2;
5822     my ($dscfn, $dstbranch) = @ARGV;
5823
5824     badusage "dry run makes no sense with import-dsc" unless act_local();
5825
5826     my $force = $dstbranch =~ s/^\+//   ? +1 :
5827                 $dstbranch =~ s/^\.\.// ? -1 :
5828                                            0;
5829     my $info = $force ? " $&" : '';
5830     $info = "$dscfn$info";
5831
5832     my $specbranch = $dstbranch;
5833     $dstbranch = "refs/heads/$dstbranch" unless $dstbranch =~ m#^refs/#;
5834     $dstbranch = cmdoutput @git, qw(check-ref-format --normalize), $dstbranch;
5835
5836     my @symcmd = (@git, qw(symbolic-ref -q HEAD));
5837     my $chead = cmdoutput_errok @symcmd;
5838     defined $chead or $?==256 or failedcmd @symcmd;
5839
5840     fail "$dstbranch is checked out - will not update it"
5841         if defined $chead and $chead eq $dstbranch;
5842
5843     my $oldhash = git_get_ref $dstbranch;
5844
5845     open D, "<", $dscfn or fail "open import .dsc ($dscfn): $!";
5846     $dscdata = do { local $/ = undef; <D>; };
5847     D->error and fail "read $dscfn: $!";
5848     close C;
5849
5850     # we don't normally need this so import it here
5851     use Dpkg::Source::Package;
5852     my $dp = new Dpkg::Source::Package filename => $dscfn,
5853         require_valid_signature => $needsig;
5854     {
5855         local $SIG{__WARN__} = sub {
5856             print STDERR $_[0];
5857             return unless $needsig;
5858             fail "import-dsc signature check failed";
5859         };
5860         if (!$dp->is_signed()) {
5861             warn "$us: warning: importing unsigned .dsc\n";
5862         } else {
5863             my $r = $dp->check_signature();
5864             die "->check_signature => $r" if $needsig && $r;
5865         }
5866     }
5867
5868     parse_dscdata();
5869
5870     my $dgit_commit = $dsc->{$ourdscfield[0]};
5871     if (defined $dgit_commit && 
5872         !forceing [qw(import-dsc-with-dgit-field)]) {
5873         $dgit_commit =~ m/\w+/ or fail "invalid hash in .dsc";
5874         progress "dgit: import-dsc of .dsc with Dgit field, using git hash";
5875         my @cmd = (qw(sh -ec),
5876                    "echo $dgit_commit | git cat-file --batch-check");
5877         my $objgot = cmdoutput @cmd;
5878         if ($objgot =~ m#^\w+ missing\b#) {
5879             fail <<END
5880 .dsc contains Dgit field referring to object $dgit_commit
5881 Your git tree does not have that object.  Try `git fetch' from a
5882 plausible server (browse.dgit.d.o? alioth?), and try the import-dsc again.
5883 END
5884         }
5885         if ($oldhash && !is_fast_fwd $oldhash, $dgit_commit) {
5886             if ($force > 0) {
5887                 progress "Not fast forward, forced update.";
5888             } else {
5889                 fail "Not fast forward to $dgit_commit";
5890             }
5891         }
5892         @cmd = (@git, qw(update-ref -m), "dgit import-dsc (Dgit): $info",
5893                 $dstbranch, $dgit_commit);
5894         runcmd @cmd;
5895         progress "dgit: import-dsc updated git ref $dstbranch";
5896         return 0;
5897     }
5898
5899     fail <<END
5900 Branch $dstbranch already exists
5901 Specify ..$specbranch for a pseudo-merge, binding in existing history
5902 Specify  +$specbranch to overwrite, discarding existing history
5903 END
5904         if $oldhash && !$force;
5905
5906     $package = getfield $dsc, 'Source';
5907     my @dfi = dsc_files_info();
5908     foreach my $fi (@dfi) {
5909         my $f = $fi->{Filename};
5910         my $here = "../$f";
5911         next if lstat $here;
5912         fail "stat $here: $!" unless $! == ENOENT;
5913         my $there = $dscfn;
5914         if ($dscfn =~ m#^(?:\./+)?\.\./+#) {
5915             $there = $';
5916         } elsif ($dscfn =~ m#^/#) {
5917             $there = $dscfn;
5918         } else {
5919             fail "cannot import $dscfn which seems to be inside working tree!";
5920         }
5921         $there =~ s#/+[^/]+$## or
5922             fail "cannot import $dscfn which seems to not have a basename";
5923         $there .= "/$f";
5924         symlink $there, $here or fail "symlink $there to $here: $!";
5925         progress "made symlink $here -> $there";
5926 #       print STDERR Dumper($fi);
5927     }
5928     my @mergeinputs = generate_commits_from_dsc();
5929     die unless @mergeinputs == 1;
5930
5931     my $newhash = $mergeinputs[0]{Commit};
5932
5933     if ($oldhash) {
5934         if ($force > 0) {
5935             progress "Import, forced update - synthetic orphan git history.";
5936         } elsif ($force < 0) {
5937             progress "Import, merging.";
5938             my $tree = cmdoutput @git, qw(rev-parse), "$newhash:";
5939             my $version = getfield $dsc, 'Version';
5940             $newhash = make_commit_text <<END;
5941 tree $tree
5942 parent $newhash
5943 parent $oldhash
5944
5945 Merge $package ($version) import into $dstbranch
5946 END
5947         } else {
5948             die; # caught earlier
5949         }
5950     }
5951
5952     my @cmd = (@git, qw(update-ref -m), "dgit import-dsc: $info",
5953                $dstbranch, $newhash);
5954     runcmd @cmd;
5955     progress "dgit: import-dsc results are in in git ref $dstbranch";
5956 }
5957
5958 sub cmd_archive_api_query {
5959     badusage "need only 1 subpath argument" unless @ARGV==1;
5960     my ($subpath) = @ARGV;
5961     my @cmd = archive_api_query_cmd($subpath);
5962     push @cmd, qw(-f);
5963     debugcmd ">",@cmd;
5964     exec @cmd or fail "exec curl: $!\n";
5965 }
5966
5967 sub cmd_clone_dgit_repos_server {
5968     badusage "need destination argument" unless @ARGV==1;
5969     my ($destdir) = @ARGV;
5970     $package = '_dgit-repos-server';
5971     my @cmd = (@git, qw(clone), access_giturl(), $destdir);
5972     debugcmd ">",@cmd;
5973     exec @cmd or fail "exec git clone: $!\n";
5974 }
5975
5976 sub cmd_setup_mergechangelogs {
5977     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5978     setup_mergechangelogs(1);
5979 }
5980
5981 sub cmd_setup_useremail {
5982     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
5983     setup_useremail(1);
5984 }
5985
5986 sub cmd_setup_new_tree {
5987     badusage "no arguments allowed to dgit setup-tree" if @ARGV;
5988     setup_new_tree();
5989 }
5990
5991 #---------- argument parsing and main program ----------
5992
5993 sub cmd_version {
5994     print "dgit version $our_version\n" or die $!;
5995     exit 0;
5996 }
5997
5998 our (%valopts_long, %valopts_short);
5999 our @rvalopts;
6000
6001 sub defvalopt ($$$$) {
6002     my ($long,$short,$val_re,$how) = @_;
6003     my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
6004     $valopts_long{$long} = $oi;
6005     $valopts_short{$short} = $oi;
6006     # $how subref should:
6007     #   do whatever assignemnt or thing it likes with $_[0]
6008     #   if the option should not be passed on to remote, @rvalopts=()
6009     # or $how can be a scalar ref, meaning simply assign the value
6010 }
6011
6012 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
6013 defvalopt '--distro',        '-d', '.+',      \$idistro;
6014 defvalopt '',                '-k', '.+',      \$keyid;
6015 defvalopt '--existing-package','', '.*',      \$existing_package;
6016 defvalopt '--build-products-dir','','.*',     \$buildproductsdir;
6017 defvalopt '--clean',       '', $cleanmode_re, \$cleanmode;
6018 defvalopt '--package',   '-p',   $package_re, \$package;
6019 defvalopt '--quilt',     '', $quilt_modes_re, \$quilt_mode;
6020
6021 defvalopt '', '-C', '.+', sub {
6022     ($changesfile) = (@_);
6023     if ($changesfile =~ s#^(.*)/##) {
6024         $buildproductsdir = $1;
6025     }
6026 };
6027
6028 defvalopt '--initiator-tempdir','','.*', sub {
6029     ($initiator_tempdir) = (@_);
6030     $initiator_tempdir =~ m#^/# or
6031         badusage "--initiator-tempdir must be used specify an".
6032         " absolute, not relative, directory."
6033 };
6034
6035 sub parseopts () {
6036     my $om;
6037
6038     if (defined $ENV{'DGIT_SSH'}) {
6039         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
6040     } elsif (defined $ENV{'GIT_SSH'}) {
6041         @ssh = ($ENV{'GIT_SSH'});
6042     }
6043
6044     my $oi;
6045     my $val;
6046     my $valopt = sub {
6047         my ($what) = @_;
6048         @rvalopts = ($_);
6049         if (!defined $val) {
6050             badusage "$what needs a value" unless @ARGV;
6051             $val = shift @ARGV;
6052             push @rvalopts, $val;
6053         }
6054         badusage "bad value \`$val' for $what" unless
6055             $val =~ m/^$oi->{Re}$(?!\n)/s;
6056         my $how = $oi->{How};
6057         if (ref($how) eq 'SCALAR') {
6058             $$how = $val;
6059         } else {
6060             $how->($val);
6061         }
6062         push @ropts, @rvalopts;
6063     };
6064
6065     while (@ARGV) {
6066         last unless $ARGV[0] =~ m/^-/;
6067         $_ = shift @ARGV;
6068         last if m/^--?$/;
6069         if (m/^--/) {
6070             if (m/^--dry-run$/) {
6071                 push @ropts, $_;
6072                 $dryrun_level=2;
6073             } elsif (m/^--damp-run$/) {
6074                 push @ropts, $_;
6075                 $dryrun_level=1;
6076             } elsif (m/^--no-sign$/) {
6077                 push @ropts, $_;
6078                 $sign=0;
6079             } elsif (m/^--help$/) {
6080                 cmd_help();
6081             } elsif (m/^--version$/) {
6082                 cmd_version();
6083             } elsif (m/^--new$/) {
6084                 push @ropts, $_;
6085                 $new_package=1;
6086             } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
6087                      ($om = $opts_opt_map{$1}) &&
6088                      length $om->[0]) {
6089                 push @ropts, $_;
6090                 $om->[0] = $2;
6091             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
6092                      !$opts_opt_cmdonly{$1} &&
6093                      ($om = $opts_opt_map{$1})) {
6094                 push @ropts, $_;
6095                 push @$om, $2;
6096             } elsif (m/^--(gbp|dpm)$/s) {
6097                 push @ropts, "--quilt=$1";
6098                 $quilt_mode = $1;
6099             } elsif (m/^--ignore-dirty$/s) {
6100                 push @ropts, $_;
6101                 $ignoredirty = 1;
6102             } elsif (m/^--no-quilt-fixup$/s) {
6103                 push @ropts, $_;
6104                 $quilt_mode = 'nocheck';
6105             } elsif (m/^--no-rm-on-error$/s) {
6106                 push @ropts, $_;
6107                 $rmonerror = 0;
6108             } elsif (m/^--overwrite$/s) {
6109                 push @ropts, $_;
6110                 $overwrite_version = '';
6111             } elsif (m/^--overwrite=(.+)$/s) {
6112                 push @ropts, $_;
6113                 $overwrite_version = $1;
6114             } elsif (m/^--dep14tag$/s) {
6115                 push @ropts, $_;
6116                 $dodep14tag= 'want';
6117             } elsif (m/^--no-dep14tag$/s) {
6118                 push @ropts, $_;
6119                 $dodep14tag= 'no';
6120             } elsif (m/^--always-dep14tag$/s) {
6121                 push @ropts, $_;
6122                 $dodep14tag= 'always';
6123             } elsif (m/^--delayed=(\d+)$/s) {
6124                 push @ropts, $_;
6125                 push @dput, $_;
6126             } elsif (m/^--dgit-view-save=(.+)$/s) {
6127                 push @ropts, $_;
6128                 $split_brain_save = $1;
6129                 $split_brain_save =~ s#^(?!refs/)#refs/heads/#;
6130             } elsif (m/^--(no-)?rm-old-changes$/s) {
6131                 push @ropts, $_;
6132                 $rmchanges = !$1;
6133             } elsif (m/^--deliberately-($deliberately_re)$/s) {
6134                 push @ropts, $_;
6135                 push @deliberatelies, $&;
6136             } elsif (m/^--force-(.*)/ && defined $forceopts{$1}) {
6137                 push @ropts, $&;
6138                 $forceopts{$1} = 1;
6139                 $_='';
6140             } elsif (m/^--force-/) {
6141                 print STDERR
6142                     "$us: warning: ignoring unknown force option $_\n";
6143                 $_='';
6144             } elsif (m/^--dgit-tag-format=(old|new)$/s) {
6145                 # undocumented, for testing
6146                 push @ropts, $_;
6147                 $tagformat_want = [ $1, 'command line', 1 ];
6148                 # 1 menas overrides distro configuration
6149             } elsif (m/^--always-split-source-build$/s) {
6150                 # undocumented, for testing
6151                 push @ropts, $_;
6152                 $need_split_build_invocation = 1;
6153             } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
6154                 $val = $2 ? $' : undef; #';
6155                 $valopt->($oi->{Long});
6156             } else {
6157                 badusage "unknown long option \`$_'";
6158             }
6159         } else {
6160             while (m/^-./s) {
6161                 if (s/^-n/-/) {
6162                     push @ropts, $&;
6163                     $dryrun_level=2;
6164                 } elsif (s/^-L/-/) {
6165                     push @ropts, $&;
6166                     $dryrun_level=1;
6167                 } elsif (s/^-h/-/) {
6168                     cmd_help();
6169                 } elsif (s/^-D/-/) {
6170                     push @ropts, $&;
6171                     $debuglevel++;
6172                     enabledebug();
6173                 } elsif (s/^-N/-/) {
6174                     push @ropts, $&;
6175                     $new_package=1;
6176                 } elsif (m/^-m/) {
6177                     push @ropts, $&;
6178                     push @changesopts, $_;
6179                     $_ = '';
6180                 } elsif (s/^-wn$//s) {
6181                     push @ropts, $&;
6182                     $cleanmode = 'none';
6183                 } elsif (s/^-wg$//s) {
6184                     push @ropts, $&;
6185                     $cleanmode = 'git';
6186                 } elsif (s/^-wgf$//s) {
6187                     push @ropts, $&;
6188                     $cleanmode = 'git-ff';
6189                 } elsif (s/^-wd$//s) {
6190                     push @ropts, $&;
6191                     $cleanmode = 'dpkg-source';
6192                 } elsif (s/^-wdd$//s) {
6193                     push @ropts, $&;
6194                     $cleanmode = 'dpkg-source-d';
6195                 } elsif (s/^-wc$//s) {
6196                     push @ropts, $&;
6197                     $cleanmode = 'check';
6198                 } elsif (s/^-c([^=]*)\=(.*)$//s) {
6199                     push @git, '-c', $&;
6200                     $gitcfgs{cmdline}{$1} = [ $2 ];
6201                 } elsif (s/^-c([^=]+)$//s) {
6202                     push @git, '-c', $&;
6203                     $gitcfgs{cmdline}{$1} = [ 'true' ];
6204                 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
6205                     $val = $'; #';
6206                     $val = undef unless length $val;
6207                     $valopt->($oi->{Short});
6208                     $_ = '';
6209                 } else {
6210                     badusage "unknown short option \`$_'";
6211                 }
6212             }
6213         }
6214     }
6215 }
6216
6217 sub check_env_sanity () {
6218     my $blocked = new POSIX::SigSet;
6219     sigprocmask SIG_UNBLOCK, $blocked, $blocked or die $!;
6220
6221     eval {
6222         foreach my $name (qw(PIPE CHLD)) {
6223             my $signame = "SIG$name";
6224             my $signum = eval "POSIX::$signame" // die;
6225             ($SIG{$name} // 'DEFAULT') eq 'DEFAULT' or
6226                 die "$signame is set to something other than SIG_DFL\n";
6227             $blocked->ismember($signum) and
6228                 die "$signame is blocked\n";
6229         }
6230     };
6231     return unless $@;
6232     chomp $@;
6233     fail <<END;
6234 On entry to dgit, $@
6235 This is a bug produced by something in in your execution environment.
6236 Giving up.
6237 END
6238 }
6239
6240
6241 sub finalise_opts_opts () {
6242     foreach my $k (keys %opts_opt_map) {
6243         my $om = $opts_opt_map{$k};
6244
6245         my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
6246         if (defined $v) {
6247             badcfg "cannot set command for $k"
6248                 unless length $om->[0];
6249             $om->[0] = $v;
6250         }
6251
6252         foreach my $c (access_cfg_cfgs("opts-$k")) {
6253             my @vl =
6254                 map { $_ ? @$_ : () }
6255                 map { $gitcfgs{$_}{$c} }
6256                 reverse @gitcfgsources;
6257             printdebug "CL $c ", (join " ", map { shellquote } @vl),
6258                 "\n" if $debuglevel >= 4;
6259             next unless @vl;
6260             badcfg "cannot configure options for $k"
6261                 if $opts_opt_cmdonly{$k};
6262             my $insertpos = $opts_cfg_insertpos{$k};
6263             @$om = ( @$om[0..$insertpos-1],
6264                      @vl,
6265                      @$om[$insertpos..$#$om] );
6266         }
6267     }
6268 }
6269
6270 if ($ENV{$fakeeditorenv}) {
6271     git_slurp_config();
6272     quilt_fixup_editor();
6273 }
6274
6275 parseopts();
6276 check_env_sanity();
6277 git_slurp_config();
6278
6279 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
6280 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
6281     if $dryrun_level == 1;
6282 if (!@ARGV) {
6283     print STDERR $helpmsg or die $!;
6284     exit 8;
6285 }
6286 my $cmd = shift @ARGV;
6287 $cmd =~ y/-/_/;
6288
6289 my $pre_fn = ${*::}{"pre_$cmd"};
6290 $pre_fn->() if $pre_fn;
6291
6292 if (!defined $rmchanges) {
6293     local $access_forpush;
6294     $rmchanges = access_cfg_bool(0, 'rm-old-changes');
6295 }
6296
6297 if (!defined $quilt_mode) {
6298     local $access_forpush;
6299     $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
6300         // access_cfg('quilt-mode', 'RETURN-UNDEF')
6301         // 'linear';
6302     $quilt_mode =~ m/^($quilt_modes_re)$/ 
6303         or badcfg "unknown quilt-mode \`$quilt_mode'";
6304     $quilt_mode = $1;
6305 }
6306
6307 if (!defined $dodep14tag) {
6308     local $access_forpush;
6309     $dodep14tag = access_cfg('dep14tag', 'RETURN-UNDEF') // 'want';
6310     $dodep14tag =~ m/^($dodep14tag_re)$/ 
6311         or badcfg "unknown dep14tag setting \`$dodep14tag'";
6312     $dodep14tag = $1;
6313 }
6314
6315 $need_split_build_invocation ||= quiltmode_splitbrain();
6316
6317 if (!defined $cleanmode) {
6318     local $access_forpush;
6319     $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
6320     $cleanmode //= 'dpkg-source';
6321
6322     badcfg "unknown clean-mode \`$cleanmode'" unless
6323         $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
6324 }
6325
6326 my $fn = ${*::}{"cmd_$cmd"};
6327 $fn or badusage "unknown operation $cmd";
6328 $fn->();