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