chiark / gitweb /
352e5b16c21b7b0db4b13fefd3d383db5f214e43
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013-2015 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
38 use Debian::Dgit;
39
40 our $our_version = 'UNRELEASED'; ###substituted###
41
42 our @rpushprotovsn_support = qw(3 2); # 4 is new tag format
43 our $protovsn;
44
45 our $isuite = 'unstable';
46 our $idistro;
47 our $package;
48 our @ropts;
49
50 our $sign = 1;
51 our $dryrun_level = 0;
52 our $changesfile;
53 our $buildproductsdir = '..';
54 our $new_package = 0;
55 our $ignoredirty = 0;
56 our $rmonerror = 1;
57 our @deliberatelies;
58 our %previously;
59 our $existing_package = 'dpkg';
60 our $cleanmode;
61 our $changes_since_version;
62 our $rmchanges;
63 our $quilt_mode;
64 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|unapplied';
65 our $we_are_responder;
66 our $initiator_tempdir;
67 our $patches_applied_dirtily = 00;
68 our $tagformat;
69 our $tagformatfn;
70
71 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
72
73 our $suite_re = '[-+.0-9a-z]+';
74 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
75
76 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
77 our $splitbraincache = 'dgit-intern/quilt-cache';
78
79 our (@git) = qw(git);
80 our (@dget) = qw(dget);
81 our (@curl) = qw(curl -f);
82 our (@dput) = qw(dput);
83 our (@debsign) = qw(debsign);
84 our (@gpg) = qw(gpg);
85 our (@sbuild) = qw(sbuild);
86 our (@ssh) = 'ssh';
87 our (@dgit) = qw(dgit);
88 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
89 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
90 our (@dpkggenchanges) = qw(dpkg-genchanges);
91 our (@mergechanges) = qw(mergechanges -f);
92 our (@gbp) = qw(gbp);
93 our (@changesopts) = ('');
94
95 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
96                      'curl' => \@curl,
97                      'dput' => \@dput,
98                      'debsign' => \@debsign,
99                      'gpg' => \@gpg,
100                      'sbuild' => \@sbuild,
101                      'ssh' => \@ssh,
102                      'dgit' => \@dgit,
103                      'git' => \@git,
104                      'dpkg-source' => \@dpkgsource,
105                      'dpkg-buildpackage' => \@dpkgbuildpackage,
106                      'dpkg-genchanges' => \@dpkggenchanges,
107                      'gbp' => \@gbp,
108                      'ch' => \@changesopts,
109                      'mergechanges' => \@mergechanges);
110
111 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
112 our %opts_cfg_insertpos = map {
113     $_,
114     scalar @{ $opts_opt_map{$_} }
115 } keys %opts_opt_map;
116
117 sub finalise_opts_opts();
118
119 our $keyid;
120
121 autoflush STDOUT 1;
122
123 our $supplementary_message = '';
124 our $need_split_build_invocation = 0;
125 our $split_brain = 0;
126
127 END {
128     local ($@, $?);
129     print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
130 }
131
132 our $remotename = 'dgit';
133 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
134 our $csuite;
135 our $instead_distro;
136
137 sub debiantag ($$) {
138     my ($v,$distro) = @_;
139     return $tagformatfn->($v, $distro);
140 }
141
142 sub lbranch () { return "$branchprefix/$csuite"; }
143 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
144 sub lref () { return "refs/heads/".lbranch(); }
145 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
146 sub rrref () { return server_ref($csuite); }
147
148 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
149
150 sub stripepoch ($) {
151     my ($vsn) = @_;
152     $vsn =~ s/^\d+\://;
153     return $vsn;
154 }
155
156 sub srcfn ($$) {
157     my ($vsn,$sfx) = @_;
158     return "${package}_".(stripepoch $vsn).$sfx
159 }
160
161 sub dscfn ($) {
162     my ($vsn) = @_;
163     return srcfn($vsn,".dsc");
164 }
165
166 sub changespat ($;$) {
167     my ($vsn, $arch) = @_;
168     return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
169 }
170
171 our $us = 'dgit';
172 initdebug('');
173
174 our @end;
175 END { 
176     local ($?);
177     foreach my $f (@end) {
178         eval { $f->(); };
179         print STDERR "$us: cleanup: $@" if length $@;
180     }
181 };
182
183 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
184
185 sub no_such_package () {
186     print STDERR "$us: package $package does not exist in suite $isuite\n";
187     exit 4;
188 }
189
190 sub fetchspec () {
191     local $csuite = '*';
192     return  "+".rrref().":".lrref();
193 }
194
195 sub changedir ($) {
196     my ($newdir) = @_;
197     printdebug "CD $newdir\n";
198     chdir $newdir or die "chdir: $newdir: $!";
199 }
200
201 sub deliberately ($) {
202     my ($enquiry) = @_;
203     return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
204 }
205
206 sub deliberately_not_fast_forward () {
207     foreach (qw(not-fast-forward fresh-repo)) {
208         return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
209     }
210 }
211
212 sub quiltmode_splitbrain () {
213     $quilt_mode =~ m/gbp|dpm|unapplied/;
214 }
215
216 #---------- remote protocol support, common ----------
217
218 # remote push initiator/responder protocol:
219 #  $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
220 #  where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
221 #  < dgit-remote-push-ready <actual-proto-vsn>
222 #
223 # occasionally:
224 #
225 #  > progress NBYTES
226 #  [NBYTES message]
227 #
228 #  > supplementary-message NBYTES          # $protovsn >= 3
229 #  [NBYTES message]
230 #
231 # main sequence:
232 #
233 #  > file parsed-changelog
234 #  [indicates that output of dpkg-parsechangelog follows]
235 #  > data-block NBYTES
236 #  > [NBYTES bytes of data (no newline)]
237 #  [maybe some more blocks]
238 #  > data-end
239 #
240 #  > file dsc
241 #  [etc]
242 #
243 #  > file changes
244 #  [etc]
245 #
246 #  > param head HEAD
247 #  > param csuite SUITE
248 #
249 #  > previously REFNAME=OBJNAME       # if --deliberately-not-fast-forward
250 #                                     # goes into tag, for replay prevention
251 #
252 #  > want signed-tag
253 #  [indicates that signed tag is wanted]
254 #  < data-block NBYTES
255 #  < [NBYTES bytes of data (no newline)]
256 #  [maybe some more blocks]
257 #  < data-end
258 #  < files-end
259 #
260 #  > want signed-dsc-changes
261 #  < data-block NBYTES    [transfer of signed dsc]
262 #  [etc]
263 #  < data-block NBYTES    [transfer of signed changes]
264 #  [etc]
265 #  < files-end
266 #
267 #  > complete
268
269 our $i_child_pid;
270
271 sub i_child_report () {
272     # Sees if our child has died, and reap it if so.  Returns a string
273     # describing how it died if it failed, or undef otherwise.
274     return undef unless $i_child_pid;
275     my $got = waitpid $i_child_pid, WNOHANG;
276     return undef if $got <= 0;
277     die unless $got == $i_child_pid;
278     $i_child_pid = undef;
279     return undef unless $?;
280     return "build host child ".waitstatusmsg();
281 }
282
283 sub badproto ($$) {
284     my ($fh, $m) = @_;
285     fail "connection lost: $!" if $fh->error;
286     fail "protocol violation; $m not expected";
287 }
288
289 sub badproto_badread ($$) {
290     my ($fh, $wh) = @_;
291     fail "connection lost: $!" if $!;
292     my $report = i_child_report();
293     fail $report if defined $report;
294     badproto $fh, "eof (reading $wh)";
295 }
296
297 sub protocol_expect (&$) {
298     my ($match, $fh) = @_;
299     local $_;
300     $_ = <$fh>;
301     defined && chomp or badproto_badread $fh, "protocol message";
302     if (wantarray) {
303         my @r = &$match;
304         return @r if @r;
305     } else {
306         my $r = &$match;
307         return $r if $r;
308     }
309     badproto $fh, "\`$_'";
310 }
311
312 sub protocol_send_file ($$) {
313     my ($fh, $ourfn) = @_;
314     open PF, "<", $ourfn or die "$ourfn: $!";
315     for (;;) {
316         my $d;
317         my $got = read PF, $d, 65536;
318         die "$ourfn: $!" unless defined $got;
319         last if !$got;
320         print $fh "data-block ".length($d)."\n" or die $!;
321         print $fh $d or die $!;
322     }
323     PF->error and die "$ourfn $!";
324     print $fh "data-end\n" or die $!;
325     close PF;
326 }
327
328 sub protocol_read_bytes ($$) {
329     my ($fh, $nbytes) = @_;
330     $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
331     my $d;
332     my $got = read $fh, $d, $nbytes;
333     $got==$nbytes or badproto_badread $fh, "data block";
334     return $d;
335 }
336
337 sub protocol_receive_file ($$) {
338     my ($fh, $ourfn) = @_;
339     printdebug "() $ourfn\n";
340     open PF, ">", $ourfn or die "$ourfn: $!";
341     for (;;) {
342         my ($y,$l) = protocol_expect {
343             m/^data-block (.*)$/ ? (1,$1) :
344             m/^data-end$/ ? (0,) :
345             ();
346         } $fh;
347         last unless $y;
348         my $d = protocol_read_bytes $fh, $l;
349         print PF $d or die $!;
350     }
351     close PF or die $!;
352 }
353
354 #---------- remote protocol support, responder ----------
355
356 sub responder_send_command ($) {
357     my ($command) = @_;
358     return unless $we_are_responder;
359     # called even without $we_are_responder
360     printdebug ">> $command\n";
361     print PO $command, "\n" or die $!;
362 }    
363
364 sub responder_send_file ($$) {
365     my ($keyword, $ourfn) = @_;
366     return unless $we_are_responder;
367     printdebug "]] $keyword $ourfn\n";
368     responder_send_command "file $keyword";
369     protocol_send_file \*PO, $ourfn;
370 }
371
372 sub responder_receive_files ($@) {
373     my ($keyword, @ourfns) = @_;
374     die unless $we_are_responder;
375     printdebug "[[ $keyword @ourfns\n";
376     responder_send_command "want $keyword";
377     foreach my $fn (@ourfns) {
378         protocol_receive_file \*PI, $fn;
379     }
380     printdebug "[[\$\n";
381     protocol_expect { m/^files-end$/ } \*PI;
382 }
383
384 #---------- remote protocol support, initiator ----------
385
386 sub initiator_expect (&) {
387     my ($match) = @_;
388     protocol_expect { &$match } \*RO;
389 }
390
391 #---------- end remote code ----------
392
393 sub progress {
394     if ($we_are_responder) {
395         my $m = join '', @_;
396         responder_send_command "progress ".length($m) or die $!;
397         print PO $m or die $!;
398     } else {
399         print @_, "\n";
400     }
401 }
402
403 our $ua;
404
405 sub url_get {
406     if (!$ua) {
407         $ua = LWP::UserAgent->new();
408         $ua->env_proxy;
409     }
410     my $what = $_[$#_];
411     progress "downloading $what...";
412     my $r = $ua->get(@_) or die $!;
413     return undef if $r->code == 404;
414     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
415     return $r->decoded_content(charset => 'none');
416 }
417
418 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
419
420 sub runcmd {
421     debugcmd "+",@_;
422     $!=0; $?=-1;
423     failedcmd @_ if system @_;
424 }
425
426 sub act_local () { return $dryrun_level <= 1; }
427 sub act_scary () { return !$dryrun_level; }
428
429 sub printdone {
430     if (!$dryrun_level) {
431         progress "dgit ok: @_";
432     } else {
433         progress "would be ok: @_ (but dry run only)";
434     }
435 }
436
437 sub dryrun_report {
438     printcmd(\*STDERR,$debugprefix."#",@_);
439 }
440
441 sub runcmd_ordryrun {
442     if (act_scary()) {
443         runcmd @_;
444     } else {
445         dryrun_report @_;
446     }
447 }
448
449 sub runcmd_ordryrun_local {
450     if (act_local()) {
451         runcmd @_;
452     } else {
453         dryrun_report @_;
454     }
455 }
456
457 sub shell_cmd {
458     my ($first_shell, @cmd) = @_;
459     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
460 }
461
462 our $helpmsg = <<END;
463 main usages:
464   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
465   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
466   dgit [dgit-opts] build [dpkg-buildpackage-opts]
467   dgit [dgit-opts] sbuild [sbuild-opts]
468   dgit [dgit-opts] push [dgit-opts] [suite]
469   dgit [dgit-opts] rpush build-host:build-dir ...
470 important dgit options:
471   -k<keyid>           sign tag and package with <keyid> instead of default
472   --dry-run -n        do not change anything, but go through the motions
473   --damp-run -L       like --dry-run but make local changes, without signing
474   --new -N            allow introducing a new package
475   --debug -D          increase debug level
476   -c<name>=<value>    set git config option (used directly by dgit too)
477 END
478
479 our $later_warning_msg = <<END;
480 Perhaps the upload is stuck in incoming.  Using the version from git.
481 END
482
483 sub badusage {
484     print STDERR "$us: @_\n", $helpmsg or die $!;
485     exit 8;
486 }
487
488 sub nextarg {
489     @ARGV or badusage "too few arguments";
490     return scalar shift @ARGV;
491 }
492
493 sub cmd_help () {
494     print $helpmsg or die $!;
495     exit 0;
496 }
497
498 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
499
500 our %defcfg = ('dgit.default.distro' => 'debian',
501                'dgit.default.username' => '',
502                'dgit.default.archive-query-default-component' => 'main',
503                'dgit.default.ssh' => 'ssh',
504                'dgit.default.archive-query' => 'madison:',
505                'dgit.default.sshpsql-dbname' => 'service=projectb',
506                'dgit.default.dgit-tag-format' => 'old,new',
507                'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
508                'dgit-distro.debian.git-check' => 'url',
509                'dgit-distro.debian.git-check-suffix' => '/info/refs',
510                'dgit-distro.debian.new-private-pushers' => 't',
511                'dgit-distro.debian.dgit-tag-format' => 'old',
512                'dgit-distro.debian/push.git-url' => '',
513                'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
514                'dgit-distro.debian/push.git-user-force' => 'dgit',
515                'dgit-distro.debian/push.git-proto' => 'git+ssh://',
516                'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
517                'dgit-distro.debian/push.git-create' => 'true',
518                'dgit-distro.debian/push.git-check' => 'ssh-cmd',
519  'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
520 # 'dgit-distro.debian.archive-query-tls-key',
521 #    '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
522 # ^ this does not work because curl is broken nowadays
523 # Fixing #790093 properly will involve providing providing the key
524 # in some pacagke and maybe updating these paths.
525 #
526 # 'dgit-distro.debian.archive-query-tls-curl-args',
527 #   '--ca-path=/etc/ssl/ca-debian',
528 # ^ this is a workaround but works (only) on DSA-administered machines
529                'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
530                'dgit-distro.debian.git-url-suffix' => '',
531                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
532                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
533  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
534  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
535                'dgit-distro.ubuntu.git-check' => 'false',
536  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
537                'dgit-distro.test-dummy.ssh' => "$td/ssh",
538                'dgit-distro.test-dummy.username' => "alice",
539                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
540                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
541                'dgit-distro.test-dummy.git-url' => "$td/git",
542                'dgit-distro.test-dummy.git-host' => "git",
543                'dgit-distro.test-dummy.git-path' => "$td/git",
544                'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
545                'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
546                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
547                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
548                );
549
550 our %gitcfg;
551
552 sub git_slurp_config () {
553     local ($debuglevel) = $debuglevel-2;
554     local $/="\0";
555
556     my @cmd = (@git, qw(config -z --get-regexp .*));
557     debugcmd "|",@cmd;
558
559     open GITS, "-|", @cmd or die $!;
560     while (<GITS>) {
561         chomp or die;
562         printdebug "=> ", (messagequote $_), "\n";
563         m/\n/ or die "$_ ?";
564         push @{ $gitcfg{$`} }, $'; #';
565     }
566     $!=0; $?=0;
567     close GITS
568         or ($!==0 && $?==256)
569         or failedcmd @cmd;
570 }
571
572 sub git_get_config ($) {
573     my ($c) = @_;
574     my $l = $gitcfg{$c};
575     printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
576         if $debuglevel >= 4;
577     $l or return undef;
578     @$l==1 or badcfg "multiple values for $c" if @$l > 1;
579     return $l->[0];
580 }
581
582 sub cfg {
583     foreach my $c (@_) {
584         return undef if $c =~ /RETURN-UNDEF/;
585         my $v = git_get_config($c);
586         return $v if defined $v;
587         my $dv = $defcfg{$c};
588         return $dv if defined $dv;
589     }
590     badcfg "need value for one of: @_\n".
591         "$us: distro or suite appears not to be (properly) supported";
592 }
593
594 sub access_basedistro () {
595     if (defined $idistro) {
596         return $idistro;
597     } else {    
598         return cfg("dgit-suite.$isuite.distro",
599                    "dgit.default.distro");
600     }
601 }
602
603 sub access_quirk () {
604     # returns (quirk name, distro to use instead or undef, quirk-specific info)
605     my $basedistro = access_basedistro();
606     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
607                               'RETURN-UNDEF');
608     if (defined $backports_quirk) {
609         my $re = $backports_quirk;
610         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
611         $re =~ s/\*/.*/g;
612         $re =~ s/\%/([-0-9a-z_]+)/
613             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
614         if ($isuite =~ m/^$re$/) {
615             return ('backports',"$basedistro-backports",$1);
616         }
617     }
618     return ('none',undef);
619 }
620
621 our $access_forpush;
622
623 sub parse_cfg_bool ($$$) {
624     my ($what,$def,$v) = @_;
625     $v //= $def;
626     return
627         $v =~ m/^[ty1]/ ? 1 :
628         $v =~ m/^[fn0]/ ? 0 :
629         badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
630 }       
631
632 sub access_forpush_config () {
633     my $d = access_basedistro();
634
635     return 1 if
636         $new_package &&
637         parse_cfg_bool('new-private-pushers', 0,
638                        cfg("dgit-distro.$d.new-private-pushers",
639                            'RETURN-UNDEF'));
640
641     my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
642     $v //= 'a';
643     return
644         $v =~ m/^[ty1]/ ? 0 : # force readonly,    forpush = 0
645         $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
646         $v =~ m/^[a]/  ? '' : # auto,              forpush = ''
647         badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
648 }
649
650 sub access_forpush () {
651     $access_forpush //= access_forpush_config();
652     return $access_forpush;
653 }
654
655 sub pushing () {
656     die "$access_forpush ?" if ($access_forpush // 1) ne 1;
657     badcfg "pushing but distro is configured readonly"
658         if access_forpush_config() eq '0';
659     $access_forpush = 1;
660     $supplementary_message = <<'END' unless $we_are_responder;
661 Push failed, before we got started.
662 You can retry the push, after fixing the problem, if you like.
663 END
664     finalise_opts_opts();
665 }
666
667 sub notpushing () {
668     finalise_opts_opts();
669 }
670
671 sub supplementary_message ($) {
672     my ($msg) = @_;
673     if (!$we_are_responder) {
674         $supplementary_message = $msg;
675         return;
676     } elsif ($protovsn >= 3) {
677         responder_send_command "supplementary-message ".length($msg)
678             or die $!;
679         print PO $msg or die $!;
680     }
681 }
682
683 sub access_distros () {
684     # Returns list of distros to try, in order
685     #
686     # We want to try:
687     #    0. `instead of' distro name(s) we have been pointed to
688     #    1. the access_quirk distro, if any
689     #    2a. the user's specified distro, or failing that  } basedistro
690     #    2b. the distro calculated from the suite          }
691     my @l = access_basedistro();
692
693     my (undef,$quirkdistro) = access_quirk();
694     unshift @l, $quirkdistro;
695     unshift @l, $instead_distro;
696     @l = grep { defined } @l;
697
698     if (access_forpush()) {
699         @l = map { ("$_/push", $_) } @l;
700     }
701     @l;
702 }
703
704 sub access_cfg_cfgs (@) {
705     my (@keys) = @_;
706     my @cfgs;
707     # The nesting of these loops determines the search order.  We put
708     # the key loop on the outside so that we search all the distros
709     # for each key, before going on to the next key.  That means that
710     # if access_cfg is called with a more specific, and then a less
711     # specific, key, an earlier distro can override the less specific
712     # without necessarily overriding any more specific keys.  (If the
713     # distro wants to override the more specific keys it can simply do
714     # so; whereas if we did the loop the other way around, it would be
715     # impossible to for an earlier distro to override a less specific
716     # key but not the more specific ones without restating the unknown
717     # values of the more specific keys.
718     my @realkeys;
719     my @rundef;
720     # We have to deal with RETURN-UNDEF specially, so that we don't
721     # terminate the search prematurely.
722     foreach (@keys) {
723         if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
724         push @realkeys, $_
725     }
726     foreach my $d (access_distros()) {
727         push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
728     }
729     push @cfgs, map { "dgit.default.$_" } @realkeys;
730     push @cfgs, @rundef;
731     return @cfgs;
732 }
733
734 sub access_cfg (@) {
735     my (@keys) = @_;
736     my (@cfgs) = access_cfg_cfgs(@keys);
737     my $value = cfg(@cfgs);
738     return $value;
739 }
740
741 sub access_cfg_bool ($$) {
742     my ($def, @keys) = @_;
743     parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
744 }
745
746 sub string_to_ssh ($) {
747     my ($spec) = @_;
748     if ($spec =~ m/\s/) {
749         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
750     } else {
751         return ($spec);
752     }
753 }
754
755 sub access_cfg_ssh () {
756     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
757     if (!defined $gitssh) {
758         return @ssh;
759     } else {
760         return string_to_ssh $gitssh;
761     }
762 }
763
764 sub access_runeinfo ($) {
765     my ($info) = @_;
766     return ": dgit ".access_basedistro()." $info ;";
767 }
768
769 sub access_someuserhost ($) {
770     my ($some) = @_;
771     my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
772     defined($user) && length($user) or
773         $user = access_cfg("$some-user",'username');
774     my $host = access_cfg("$some-host");
775     return length($user) ? "$user\@$host" : $host;
776 }
777
778 sub access_gituserhost () {
779     return access_someuserhost('git');
780 }
781
782 sub access_giturl (;$) {
783     my ($optional) = @_;
784     my $url = access_cfg('git-url','RETURN-UNDEF');
785     my $suffix;
786     if (!length $url) {
787         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
788         return undef unless defined $proto;
789         $url =
790             $proto.
791             access_gituserhost().
792             access_cfg('git-path');
793     } else {
794         $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
795     }
796     $suffix //= '.git';
797     return "$url/$package$suffix";
798 }              
799
800 sub parsecontrolfh ($$;$) {
801     my ($fh, $desc, $allowsigned) = @_;
802     our $dpkgcontrolhash_noissigned;
803     my $c;
804     for (;;) {
805         my %opts = ('name' => $desc);
806         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
807         $c = Dpkg::Control::Hash->new(%opts);
808         $c->parse($fh,$desc) or die "parsing of $desc failed";
809         last if $allowsigned;
810         last if $dpkgcontrolhash_noissigned;
811         my $issigned= $c->get_option('is_pgp_signed');
812         if (!defined $issigned) {
813             $dpkgcontrolhash_noissigned= 1;
814             seek $fh, 0,0 or die "seek $desc: $!";
815         } elsif ($issigned) {
816             fail "control file $desc is (already) PGP-signed. ".
817                 " Note that dgit push needs to modify the .dsc and then".
818                 " do the signature itself";
819         } else {
820             last;
821         }
822     }
823     return $c;
824 }
825
826 sub parsecontrol {
827     my ($file, $desc) = @_;
828     my $fh = new IO::Handle;
829     open $fh, '<', $file or die "$file: $!";
830     my $c = parsecontrolfh($fh,$desc);
831     $fh->error and die $!;
832     close $fh;
833     return $c;
834 }
835
836 sub getfield ($$) {
837     my ($dctrl,$field) = @_;
838     my $v = $dctrl->{$field};
839     return $v if defined $v;
840     fail "missing field $field in ".$v->get_option('name');
841 }
842
843 sub parsechangelog {
844     my $c = Dpkg::Control::Hash->new();
845     my $p = new IO::Handle;
846     my @cmd = (qw(dpkg-parsechangelog), @_);
847     open $p, '-|', @cmd or die $!;
848     $c->parse($p);
849     $?=0; $!=0; close $p or failedcmd @cmd;
850     return $c;
851 }
852
853 sub must_getcwd () {
854     my $d = getcwd();
855     defined $d or fail "getcwd failed: $!";
856     return $d;
857 }
858
859 our %rmad;
860
861 sub archive_query ($) {
862     my ($method) = @_;
863     my $query = access_cfg('archive-query','RETURN-UNDEF');
864     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
865     my $proto = $1;
866     my $data = $'; #';
867     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
868 }
869
870 sub pool_dsc_subpath ($$) {
871     my ($vsn,$component) = @_; # $package is implict arg
872     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
873     return "/pool/$component/$prefix/$package/".dscfn($vsn);
874 }
875
876 #---------- `ftpmasterapi' archive query method (nascent) ----------
877
878 sub archive_api_query_cmd ($) {
879     my ($subpath) = @_;
880     my @cmd = qw(curl -sS);
881     my $url = access_cfg('archive-query-url');
882     if ($url =~ m#^https://([-.0-9a-z]+)/#) {
883         my $host = $1;
884         my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
885         foreach my $key (split /\:/, $keys) {
886             $key =~ s/\%HOST\%/$host/g;
887             if (!stat $key) {
888                 fail "for $url: stat $key: $!" unless $!==ENOENT;
889                 next;
890             }
891             fail "config requested specific TLS key but do not know".
892                 " how to get curl to use exactly that EE key ($key)";
893 #           push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
894 #           # Sadly the above line does not work because of changes
895 #           # to gnutls.   The real fix for #790093 may involve
896 #           # new curl options.
897             last;
898         }
899         # Fixing #790093 properly will involve providing a value
900         # for this on clients.
901         my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
902         push @cmd, split / /, $kargs if defined $kargs;
903     }
904     push @cmd, $url.$subpath;
905     return @cmd;
906 }
907
908 sub api_query ($$) {
909     use JSON;
910     my ($data, $subpath) = @_;
911     badcfg "ftpmasterapi archive query method takes no data part"
912         if length $data;
913     my @cmd = archive_api_query_cmd($subpath);
914     my $json = cmdoutput @cmd;
915     return decode_json($json);
916 }
917
918 sub canonicalise_suite_ftpmasterapi () {
919     my ($proto,$data) = @_;
920     my $suites = api_query($data, 'suites');
921     my @matched;
922     foreach my $entry (@$suites) {
923         next unless grep { 
924             my $v = $entry->{$_};
925             defined $v && $v eq $isuite;
926         } qw(codename name);
927         push @matched, $entry;
928     }
929     fail "unknown suite $isuite" unless @matched;
930     my $cn;
931     eval {
932         @matched==1 or die "multiple matches for suite $isuite\n";
933         $cn = "$matched[0]{codename}";
934         defined $cn or die "suite $isuite info has no codename\n";
935         $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
936     };
937     die "bad ftpmaster api response: $@\n".Dumper(\@matched)
938         if length $@;
939     return $cn;
940 }
941
942 sub archive_query_ftpmasterapi () {
943     my ($proto,$data) = @_;
944     my $info = api_query($data, "dsc_in_suite/$isuite/$package");
945     my @rows;
946     my $digester = Digest::SHA->new(256);
947     foreach my $entry (@$info) {
948         eval {
949             my $vsn = "$entry->{version}";
950             my ($ok,$msg) = version_check $vsn;
951             die "bad version: $msg\n" unless $ok;
952             my $component = "$entry->{component}";
953             $component =~ m/^$component_re$/ or die "bad component";
954             my $filename = "$entry->{filename}";
955             $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
956                 or die "bad filename";
957             my $sha256sum = "$entry->{sha256sum}";
958             $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
959             push @rows, [ $vsn, "/pool/$component/$filename",
960                           $digester, $sha256sum ];
961         };
962         die "bad ftpmaster api response: $@\n".Dumper($entry)
963             if length $@;
964     }
965     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
966     return @rows;
967 }
968
969 #---------- `madison' archive query method ----------
970
971 sub archive_query_madison {
972     return map { [ @$_[0..1] ] } madison_get_parse(@_);
973 }
974
975 sub madison_get_parse {
976     my ($proto,$data) = @_;
977     die unless $proto eq 'madison';
978     if (!length $data) {
979         $data= access_cfg('madison-distro','RETURN-UNDEF');
980         $data //= access_basedistro();
981     }
982     $rmad{$proto,$data,$package} ||= cmdoutput
983         qw(rmadison -asource),"-s$isuite","-u$data",$package;
984     my $rmad = $rmad{$proto,$data,$package};
985
986     my @out;
987     foreach my $l (split /\n/, $rmad) {
988         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
989                   \s*( [^ \t|]+ )\s* \|
990                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
991                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
992         $1 eq $package or die "$rmad $package ?";
993         my $vsn = $2;
994         my $newsuite = $3;
995         my $component;
996         if (defined $4) {
997             $component = $4;
998         } else {
999             $component = access_cfg('archive-query-default-component');
1000         }
1001         $5 eq 'source' or die "$rmad ?";
1002         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1003     }
1004     return sort { -version_compare($a->[0],$b->[0]); } @out;
1005 }
1006
1007 sub canonicalise_suite_madison {
1008     # madison canonicalises for us
1009     my @r = madison_get_parse(@_);
1010     @r or fail
1011         "unable to canonicalise suite using package $package".
1012         " which does not appear to exist in suite $isuite;".
1013         " --existing-package may help";
1014     return $r[0][2];
1015 }
1016
1017 #---------- `sshpsql' archive query method ----------
1018
1019 sub sshpsql ($$$) {
1020     my ($data,$runeinfo,$sql) = @_;
1021     if (!length $data) {
1022         $data= access_someuserhost('sshpsql').':'.
1023             access_cfg('sshpsql-dbname');
1024     }
1025     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1026     my ($userhost,$dbname) = ($`,$'); #';
1027     my @rows;
1028     my @cmd = (access_cfg_ssh, $userhost,
1029                access_runeinfo("ssh-psql $runeinfo").
1030                " export LC_MESSAGES=C; export LC_CTYPE=C;".
1031                " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1032     debugcmd "|",@cmd;
1033     open P, "-|", @cmd or die $!;
1034     while (<P>) {
1035         chomp or die;
1036         printdebug(">|$_|\n");
1037         push @rows, $_;
1038     }
1039     $!=0; $?=0; close P or failedcmd @cmd;
1040     @rows or die;
1041     my $nrows = pop @rows;
1042     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1043     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1044     @rows = map { [ split /\|/, $_ ] } @rows;
1045     my $ncols = scalar @{ shift @rows };
1046     die if grep { scalar @$_ != $ncols } @rows;
1047     return @rows;
1048 }
1049
1050 sub sql_injection_check {
1051     foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1052 }
1053
1054 sub archive_query_sshpsql ($$) {
1055     my ($proto,$data) = @_;
1056     sql_injection_check $isuite, $package;
1057     my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1058         SELECT source.version, component.name, files.filename, files.sha256sum
1059           FROM source
1060           JOIN src_associations ON source.id = src_associations.source
1061           JOIN suite ON suite.id = src_associations.suite
1062           JOIN dsc_files ON dsc_files.source = source.id
1063           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1064           JOIN component ON component.id = files_archive_map.component_id
1065           JOIN files ON files.id = dsc_files.file
1066          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1067            AND source.source='$package'
1068            AND files.filename LIKE '%.dsc';
1069 END
1070     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1071     my $digester = Digest::SHA->new(256);
1072     @rows = map {
1073         my ($vsn,$component,$filename,$sha256sum) = @$_;
1074         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1075     } @rows;
1076     return @rows;
1077 }
1078
1079 sub canonicalise_suite_sshpsql ($$) {
1080     my ($proto,$data) = @_;
1081     sql_injection_check $isuite;
1082     my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1083         SELECT suite.codename
1084           FROM suite where suite_name='$isuite' or codename='$isuite';
1085 END
1086     @rows = map { $_->[0] } @rows;
1087     fail "unknown suite $isuite" unless @rows;
1088     die "ambiguous $isuite: @rows ?" if @rows>1;
1089     return $rows[0];
1090 }
1091
1092 #---------- `dummycat' archive query method ----------
1093
1094 sub canonicalise_suite_dummycat ($$) {
1095     my ($proto,$data) = @_;
1096     my $dpath = "$data/suite.$isuite";
1097     if (!open C, "<", $dpath) {
1098         $!==ENOENT or die "$dpath: $!";
1099         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1100         return $isuite;
1101     }
1102     $!=0; $_ = <C>;
1103     chomp or die "$dpath: $!";
1104     close C;
1105     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1106     return $_;
1107 }
1108
1109 sub archive_query_dummycat ($$) {
1110     my ($proto,$data) = @_;
1111     canonicalise_suite();
1112     my $dpath = "$data/package.$csuite.$package";
1113     if (!open C, "<", $dpath) {
1114         $!==ENOENT or die "$dpath: $!";
1115         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1116         return ();
1117     }
1118     my @rows;
1119     while (<C>) {
1120         next if m/^\#/;
1121         next unless m/\S/;
1122         die unless chomp;
1123         printdebug "dummycat query $csuite $package $dpath | $_\n";
1124         my @row = split /\s+/, $_;
1125         @row==2 or die "$dpath: $_ ?";
1126         push @rows, \@row;
1127     }
1128     C->error and die "$dpath: $!";
1129     close C;
1130     return sort { -version_compare($a->[0],$b->[0]); } @rows;
1131 }
1132
1133 #---------- archive query entrypoints and rest of program ----------
1134
1135 sub canonicalise_suite () {
1136     return if defined $csuite;
1137     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1138     $csuite = archive_query('canonicalise_suite');
1139     if ($isuite ne $csuite) {
1140         progress "canonical suite name for $isuite is $csuite";
1141     }
1142 }
1143
1144 sub get_archive_dsc () {
1145     canonicalise_suite();
1146     my @vsns = archive_query('archive_query');
1147     foreach my $vinfo (@vsns) {
1148         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1149         $dscurl = access_cfg('mirror').$subpath;
1150         $dscdata = url_get($dscurl);
1151         if (!$dscdata) {
1152             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1153             next;
1154         }
1155         if ($digester) {
1156             $digester->reset();
1157             $digester->add($dscdata);
1158             my $got = $digester->hexdigest();
1159             $got eq $digest or
1160                 fail "$dscurl has hash $got but".
1161                     " archive told us to expect $digest";
1162         }
1163         my $dscfh = new IO::File \$dscdata, '<' or die $!;
1164         printdebug Dumper($dscdata) if $debuglevel>1;
1165         $dsc = parsecontrolfh($dscfh,$dscurl,1);
1166         printdebug Dumper($dsc) if $debuglevel>1;
1167         my $fmt = getfield $dsc, 'Format';
1168         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1169         $dsc_checked = !!$digester;
1170         return;
1171     }
1172     $dsc = undef;
1173 }
1174
1175 sub check_for_git ();
1176 sub check_for_git () {
1177     # returns 0 or 1
1178     my $how = access_cfg('git-check');
1179     if ($how eq 'ssh-cmd') {
1180         my @cmd =
1181             (access_cfg_ssh, access_gituserhost(),
1182              access_runeinfo("git-check $package").
1183              " set -e; cd ".access_cfg('git-path').";".
1184              " if test -d $package.git; then echo 1; else echo 0; fi");
1185         my $r= cmdoutput @cmd;
1186         if (defined $r and $r =~ m/^divert (\w+)$/) {
1187             my $divert=$1;
1188             my ($usedistro,) = access_distros();
1189             # NB that if we are pushing, $usedistro will be $distro/push
1190             $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1191             $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1192             progress "diverting to $divert (using config for $instead_distro)";
1193             return check_for_git();
1194         }
1195         failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1196         return $r+0;
1197     } elsif ($how eq 'url') {
1198         my $prefix = access_cfg('git-check-url','git-url');
1199         my $suffix = access_cfg('git-check-suffix','git-suffix',
1200                                 'RETURN-UNDEF') // '.git';
1201         my $url = "$prefix/$package$suffix";
1202         my @cmd = (qw(curl -sS -I), $url);
1203         my $result = cmdoutput @cmd;
1204         $result =~ s/^\S+ 200 .*\n\r?\n//;
1205         # curl -sS -I with https_proxy prints
1206         # HTTP/1.0 200 Connection established
1207         $result =~ m/^\S+ (404|200) /s or
1208             fail "unexpected results from git check query - ".
1209                 Dumper($prefix, $result);
1210         my $code = $1;
1211         if ($code eq '404') {
1212             return 0;
1213         } elsif ($code eq '200') {
1214             return 1;
1215         } else {
1216             die;
1217         }
1218     } elsif ($how eq 'true') {
1219         return 1;
1220     } elsif ($how eq 'false') {
1221         return 0;
1222     } else {
1223         badcfg "unknown git-check \`$how'";
1224     }
1225 }
1226
1227 sub create_remote_git_repo () {
1228     my $how = access_cfg('git-create');
1229     if ($how eq 'ssh-cmd') {
1230         runcmd_ordryrun
1231             (access_cfg_ssh, access_gituserhost(),
1232              access_runeinfo("git-create $package").
1233              "set -e; cd ".access_cfg('git-path').";".
1234              " cp -a _template $package.git");
1235     } elsif ($how eq 'true') {
1236         # nothing to do
1237     } else {
1238         badcfg "unknown git-create \`$how'";
1239     }
1240 }
1241
1242 sub select_tagformat () {
1243     # sets $tagformatfn
1244     return if $tagformatfn && !$tagformat;
1245     die 'bug' if $tagformatfn && $tagformat;
1246     # ... $tagformat assigned after previous select_tagformat
1247
1248     my (@supported) = split /\,/, access_cfg('dgit-tag-format');
1249     printdebug "select_tagformat supported @supported\n";
1250
1251     $tagformat //= [ $supported[0], "distro access configuration", 0 ];
1252     printdebug "select_tagformat specified @$tagformat\n";
1253
1254     my ($fmt,$why,$override) = @$tagformat;
1255
1256     fail "target distro supports tag formats @supported".
1257         " but have to use $fmt ($why)"
1258         unless $override
1259             or grep { $_ eq $fmt } @supported;
1260
1261     $tagformat = undef;
1262     $tagformatfn = ${*::}{"debiantag_$fmt"};
1263
1264     fail "trying to use unknown tag format \`$fmt' ($why) !"
1265         unless $tagformatfn;
1266 }
1267
1268 our ($dsc_hash,$lastpush_hash);
1269
1270 our $ud = '.git/dgit/unpack';
1271
1272 sub prep_ud (;$) {
1273     my ($d) = @_;
1274     $d //= $ud;
1275     rmtree($d);
1276     mkpath '.git/dgit';
1277     mkdir $d or die $!;
1278 }
1279
1280 sub mktree_in_ud_here () {
1281     runcmd qw(git init -q);
1282     rmtree('.git/objects');
1283     symlink '../../../../objects','.git/objects' or die $!;
1284 }
1285
1286 sub git_write_tree () {
1287     my $tree = cmdoutput @git, qw(write-tree);
1288     $tree =~ m/^\w+$/ or die "$tree ?";
1289     return $tree;
1290 }
1291
1292 sub remove_stray_gits () {
1293     my @gitscmd = qw(find -name .git -prune -print0);
1294     debugcmd "|",@gitscmd;
1295     open GITS, "-|", @gitscmd or die $!;
1296     {
1297         local $/="\0";
1298         while (<GITS>) {
1299             chomp or die;
1300             print STDERR "$us: warning: removing from source package: ",
1301                 (messagequote $_), "\n";
1302             rmtree $_;
1303         }
1304     }
1305     $!=0; $?=0; close GITS or failedcmd @gitscmd;
1306 }
1307
1308 sub mktree_in_ud_from_only_subdir () {
1309     # changes into the subdir
1310     my (@dirs) = <*/.>;
1311     die "@dirs ?" unless @dirs==1;
1312     $dirs[0] =~ m#^([^/]+)/\.$# or die;
1313     my $dir = $1;
1314     changedir $dir;
1315
1316     remove_stray_gits();
1317     mktree_in_ud_here();
1318     my ($format, $fopts) = get_source_format();
1319     if (madformat($format)) {
1320         rmtree '.pc';
1321     }
1322     runcmd @git, qw(add -Af);
1323     my $tree=git_write_tree();
1324     return ($tree,$dir);
1325 }
1326
1327 sub dsc_files_info () {
1328     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1329                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
1330                        ['Files',           'Digest::MD5', 'new()']) {
1331         my ($fname, $module, $method) = @$csumi;
1332         my $field = $dsc->{$fname};
1333         next unless defined $field;
1334         eval "use $module; 1;" or die $@;
1335         my @out;
1336         foreach (split /\n/, $field) {
1337             next unless m/\S/;
1338             m/^(\w+) (\d+) (\S+)$/ or
1339                 fail "could not parse .dsc $fname line \`$_'";
1340             my $digester = eval "$module"."->$method;" or die $@;
1341             push @out, {
1342                 Hash => $1,
1343                 Bytes => $2,
1344                 Filename => $3,
1345                 Digester => $digester,
1346             };
1347         }
1348         return @out;
1349     }
1350     fail "missing any supported Checksums-* or Files field in ".
1351         $dsc->get_option('name');
1352 }
1353
1354 sub dsc_files () {
1355     map { $_->{Filename} } dsc_files_info();
1356 }
1357
1358 sub is_orig_file ($;$) {
1359     local ($_) = $_[0];
1360     my $base = $_[1];
1361     m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1362     defined $base or return 1;
1363     return $` eq $base;
1364 }
1365
1366 sub make_commit ($) {
1367     my ($file) = @_;
1368     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1369 }
1370
1371 sub clogp_authline ($) {
1372     my ($clogp) = @_;
1373     my $author = getfield $clogp, 'Maintainer';
1374     $author =~ s#,.*##ms;
1375     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1376     my $authline = "$author $date";
1377     $authline =~ m/$git_authline_re/o or
1378         fail "unexpected commit author line format \`$authline'".
1379         " (was generated from changelog Maintainer field)";
1380     return ($1,$2,$3) if wantarray;
1381     return $authline;
1382 }
1383
1384 sub vendor_patches_distro ($$) {
1385     my ($checkdistro, $what) = @_;
1386     return unless defined $checkdistro;
1387
1388     my $series = "debian/patches/\L$checkdistro\E.series";
1389     printdebug "checking for vendor-specific $series ($what)\n";
1390
1391     if (!open SERIES, "<", $series) {
1392         die "$series $!" unless $!==ENOENT;
1393         return;
1394     }
1395     while (<SERIES>) {
1396         next unless m/\S/;
1397         next if m/^\s+\#/;
1398
1399         print STDERR <<END;
1400
1401 Unfortunately, this source package uses a feature of dpkg-source where
1402 the same source package unpacks to different source code on different
1403 distros.  dgit cannot safely operate on such packages on affected
1404 distros, because the meaning of source packages is not stable.
1405
1406 Please ask the distro/maintainer to remove the distro-specific series
1407 files and use a different technique (if necessary, uploading actually
1408 different packages, if different distros are supposed to have
1409 different code).
1410
1411 END
1412         fail "Found active distro-specific series file for".
1413             " $checkdistro ($what): $series, cannot continue";
1414     }
1415     die "$series $!" if SERIES->error;
1416     close SERIES;
1417 }
1418
1419 sub check_for_vendor_patches () {
1420     # This dpkg-source feature doesn't seem to be documented anywhere!
1421     # But it can be found in the changelog (reformatted):
1422
1423     #   commit  4fa01b70df1dc4458daee306cfa1f987b69da58c
1424     #   Author: Raphael Hertzog <hertzog@debian.org>
1425     #   Date: Sun  Oct  3  09:36:48  2010 +0200
1426
1427     #   dpkg-source: correctly create .pc/.quilt_series with alternate
1428     #   series files
1429     #   
1430     #   If you have debian/patches/ubuntu.series and you were
1431     #   unpacking the source package on ubuntu, quilt was still
1432     #   directed to debian/patches/series instead of
1433     #   debian/patches/ubuntu.series.
1434     #   
1435     #   debian/changelog                        |    3 +++
1436     #   scripts/Dpkg/Source/Package/V3/quilt.pm |    4 +++-
1437     #   2 files changed, 6 insertions(+), 1 deletion(-)
1438
1439     use Dpkg::Vendor;
1440     vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
1441     vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
1442                          "Dpkg::Vendor \`current vendor'");
1443     vendor_patches_distro(access_basedistro(),
1444                           "distro being accessed");
1445 }
1446
1447 sub generate_commit_from_dsc () {
1448     prep_ud();
1449     changedir $ud;
1450
1451     foreach my $fi (dsc_files_info()) {
1452         my $f = $fi->{Filename};
1453         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1454
1455         link_ltarget "../../../$f", $f
1456             or $!==&ENOENT
1457             or die "$f $!";
1458
1459         complete_file_from_dsc('.', $fi)
1460             or next;
1461
1462         if (is_orig_file($f)) {
1463             link $f, "../../../../$f"
1464                 or $!==&EEXIST
1465                 or die "$f $!";
1466         }
1467     }
1468
1469     my $dscfn = "$package.dsc";
1470
1471     open D, ">", $dscfn or die "$dscfn: $!";
1472     print D $dscdata or die "$dscfn: $!";
1473     close D or die "$dscfn: $!";
1474     my @cmd = qw(dpkg-source);
1475     push @cmd, '--no-check' if $dsc_checked;
1476     push @cmd, qw(-x --), $dscfn;
1477     runcmd @cmd;
1478
1479     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1480     check_for_vendor_patches() if madformat($dsc->{format});
1481     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1482     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1483     my $authline = clogp_authline $clogp;
1484     my $changes = getfield $clogp, 'Changes';
1485     open C, ">../commit.tmp" or die $!;
1486     print C <<END or die $!;
1487 tree $tree
1488 author $authline
1489 committer $authline
1490
1491 $changes
1492
1493 # imported from the archive
1494 END
1495     close C or die $!;
1496     my $outputhash = make_commit qw(../commit.tmp);
1497     my $cversion = getfield $clogp, 'Version';
1498     progress "synthesised git commit from .dsc $cversion";
1499     if ($lastpush_hash) {
1500         runcmd @git, qw(reset -q --hard), $lastpush_hash;
1501         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1502         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1503         my $oversion = getfield $oldclogp, 'Version';
1504         my $vcmp =
1505             version_compare($oversion, $cversion);
1506         if ($vcmp < 0) {
1507             # git upload/ is earlier vsn than archive, use archive
1508             open C, ">../commit2.tmp" or die $!;
1509             print C <<END or die $!;
1510 tree $tree
1511 parent $lastpush_hash
1512 parent $outputhash
1513 author $authline
1514 committer $authline
1515
1516 Record $package ($cversion) in archive suite $csuite
1517 END
1518             $outputhash = make_commit qw(../commit2.tmp);
1519         } elsif ($vcmp > 0) {
1520             print STDERR <<END or die $!;
1521
1522 Version actually in archive:    $cversion (older)
1523 Last allegedly pushed/uploaded: $oversion (newer or same)
1524 $later_warning_msg
1525 END
1526             $outputhash = $lastpush_hash;
1527         } else {
1528             $outputhash = $lastpush_hash;
1529         }
1530     }
1531     changedir '../../../..';
1532     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1533             'DGIT_ARCHIVE', $outputhash;
1534     cmdoutput @git, qw(log -n2), $outputhash;
1535     # ... gives git a chance to complain if our commit is malformed
1536     rmtree($ud);
1537     return $outputhash;
1538 }
1539
1540 sub complete_file_from_dsc ($$) {
1541     our ($dstdir, $fi) = @_;
1542     # Ensures that we have, in $dir, the file $fi, with the correct
1543     # contents.  (Downloading it from alongside $dscurl if necessary.)
1544
1545     my $f = $fi->{Filename};
1546     my $tf = "$dstdir/$f";
1547     my $downloaded = 0;
1548
1549     if (stat_exists $tf) {
1550         progress "using existing $f";
1551     } else {
1552         my $furl = $dscurl;
1553         $furl =~ s{/[^/]+$}{};
1554         $furl .= "/$f";
1555         die "$f ?" unless $f =~ m/^\Q${package}\E_/;
1556         die "$f ?" if $f =~ m#/#;
1557         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1558         return 0 if !act_local();
1559         $downloaded = 1;
1560     }
1561
1562     open F, "<", "$tf" or die "$tf: $!";
1563     $fi->{Digester}->reset();
1564     $fi->{Digester}->addfile(*F);
1565     F->error and die $!;
1566     my $got = $fi->{Digester}->hexdigest();
1567     $got eq $fi->{Hash} or
1568         fail "file $f has hash $got but .dsc".
1569             " demands hash $fi->{Hash} ".
1570             ($downloaded ? "(got wrong file from archive!)"
1571              : "(perhaps you should delete this file?)");
1572
1573     return 1;
1574 }
1575
1576 sub ensure_we_have_orig () {
1577     foreach my $fi (dsc_files_info()) {
1578         my $f = $fi->{Filename};
1579         next unless is_orig_file($f);
1580         complete_file_from_dsc('..', $fi)
1581             or next;
1582     }
1583 }
1584
1585 sub git_fetch_us () {
1586     my @specs = (fetchspec());
1587     push @specs,
1588         map { "+refs/$_/*:".lrfetchrefs."/$_/*" }
1589         qw(tags heads);
1590     runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(), @specs;
1591
1592     my %here;
1593     my @tagpats = debiantags('*',access_basedistro);
1594
1595     git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
1596         my ($objid,$objtype,$fullrefname,$reftail) = @_;
1597         printdebug "currently $fullrefname=$objid\n";
1598         $here{$fullrefname} = $objid;
1599     });
1600     git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
1601         my ($objid,$objtype,$fullrefname,$reftail) = @_;
1602         my $lref = "refs".substr($fullrefname, length lrfetchrefs);
1603         printdebug "offered $lref=$objid\n";
1604         if (!defined $here{$lref}) {
1605             my @upd = (@git, qw(update-ref), $lref, $objid, '');
1606             runcmd_ordryrun_local @upd;
1607         } elsif ($here{$lref} eq $objid) {
1608         } else {
1609             print STDERR \
1610                 "Not updateting $lref from $here{$lref} to $objid.\n";
1611         }
1612     });
1613 }
1614
1615 sub fetch_from_archive () {
1616     # ensures that lrref() is what is actually in the archive,
1617     #  one way or another
1618     get_archive_dsc();
1619
1620     if ($dsc) {
1621         foreach my $field (@ourdscfield) {
1622             $dsc_hash = $dsc->{$field};
1623             last if defined $dsc_hash;
1624         }
1625         if (defined $dsc_hash) {
1626             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1627             $dsc_hash = $&;
1628             progress "last upload to archive specified git hash";
1629         } else {
1630             progress "last upload to archive has NO git hash";
1631         }
1632     } else {
1633         progress "no version available from the archive";
1634     }
1635
1636     $lastpush_hash = git_get_ref(lrref());
1637     printdebug "previous reference hash=$lastpush_hash\n";
1638     my $hash;
1639     if (defined $dsc_hash) {
1640         fail "missing remote git history even though dsc has hash -".
1641             " could not find ref ".lrref().
1642             " (should have been fetched from ".access_giturl()."#".rrref().")"
1643             unless $lastpush_hash;
1644         $hash = $dsc_hash;
1645         ensure_we_have_orig();
1646         if ($dsc_hash eq $lastpush_hash) {
1647         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1648             print STDERR <<END or die $!;
1649
1650 Git commit in archive is behind the last version allegedly pushed/uploaded.
1651 Commit referred to by archive:  $dsc_hash
1652 Last allegedly pushed/uploaded: $lastpush_hash
1653 $later_warning_msg
1654 END
1655             $hash = $lastpush_hash;
1656         } else {
1657             fail "git head (".lrref()."=$lastpush_hash) is not a ".
1658                 "descendant of archive's .dsc hash ($dsc_hash)";
1659         }
1660     } elsif ($dsc) {
1661         $hash = generate_commit_from_dsc();
1662     } elsif ($lastpush_hash) {
1663         # only in git, not in the archive yet
1664         $hash = $lastpush_hash;
1665         print STDERR <<END or die $!;
1666
1667 Package not found in the archive, but has allegedly been pushed using dgit.
1668 $later_warning_msg
1669 END
1670     } else {
1671         printdebug "nothing found!\n";
1672         if (defined $skew_warning_vsn) {
1673             print STDERR <<END or die $!;
1674
1675 Warning: relevant archive skew detected.
1676 Archive allegedly contains $skew_warning_vsn
1677 But we were not able to obtain any version from the archive or git.
1678
1679 END
1680         }
1681         return 0;
1682     }
1683     printdebug "current hash=$hash\n";
1684     if ($lastpush_hash) {
1685         fail "not fast forward on last upload branch!".
1686             " (archive's version left in DGIT_ARCHIVE)"
1687             unless is_fast_fwd($lastpush_hash, $hash);
1688     }
1689     if (defined $skew_warning_vsn) {
1690         mkpath '.git/dgit';
1691         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1692         my $clogf = ".git/dgit/changelog.tmp";
1693         runcmd shell_cmd "exec >$clogf",
1694             @git, qw(cat-file blob), "$hash:debian/changelog";
1695         my $gotclogp = parsechangelog("-l$clogf");
1696         my $got_vsn = getfield $gotclogp, 'Version';
1697         printdebug "SKEW CHECK GOT $got_vsn\n";
1698         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1699             print STDERR <<END or die $!;
1700
1701 Warning: archive skew detected.  Using the available version:
1702 Archive allegedly contains    $skew_warning_vsn
1703 We were able to obtain only   $got_vsn
1704
1705 END
1706         }
1707     }
1708     if ($lastpush_hash ne $hash) {
1709         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1710         if (act_local()) {
1711             cmdoutput @upd_cmd;
1712         } else {
1713             dryrun_report @upd_cmd;
1714         }
1715     }
1716     return 1;
1717 }
1718
1719 sub set_local_git_config ($$) {
1720     my ($k, $v) = @_;
1721     runcmd @git, qw(config), $k, $v;
1722 }
1723
1724 sub setup_mergechangelogs (;$) {
1725     my ($always) = @_;
1726     return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
1727
1728     my $driver = 'dpkg-mergechangelogs';
1729     my $cb = "merge.$driver";
1730     my $attrs = '.git/info/attributes';
1731     ensuredir '.git/info';
1732
1733     open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
1734     if (!open ATTRS, "<", $attrs) {
1735         $!==ENOENT or die "$attrs: $!";
1736     } else {
1737         while (<ATTRS>) {
1738             chomp;
1739             next if m{^debian/changelog\s};
1740             print NATTRS $_, "\n" or die $!;
1741         }
1742         ATTRS->error and die $!;
1743         close ATTRS;
1744     }
1745     print NATTRS "debian/changelog merge=$driver\n" or die $!;
1746     close NATTRS;
1747
1748     set_local_git_config "$cb.name", 'debian/changelog merge driver';
1749     set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
1750
1751     rename "$attrs.new", "$attrs" or die "$attrs: $!";
1752 }
1753
1754 sub setup_useremail (;$) {
1755     my ($always) = @_;
1756     return unless $always || access_cfg_bool(1, 'setup-useremail');
1757
1758     my $setup = sub {
1759         my ($k, $envvar) = @_;
1760         my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
1761         return unless defined $v;
1762         set_local_git_config "user.$k", $v;
1763     };
1764
1765     $setup->('email', 'DEBEMAIL');
1766     $setup->('name', 'DEBFULLNAME');
1767 }
1768
1769 sub setup_new_tree () {
1770     setup_mergechangelogs();
1771     setup_useremail();
1772 }
1773
1774 sub clone ($) {
1775     my ($dstdir) = @_;
1776     canonicalise_suite();
1777     badusage "dry run makes no sense with clone" unless act_local();
1778     my $hasgit = check_for_git();
1779     mkdir $dstdir or fail "create \`$dstdir': $!";
1780     changedir $dstdir;
1781     runcmd @git, qw(init -q);
1782     my $giturl = access_giturl(1);
1783     if (defined $giturl) {
1784         set_local_git_config "remote.$remotename.fetch", fetchspec();
1785         open H, "> .git/HEAD" or die $!;
1786         print H "ref: ".lref()."\n" or die $!;
1787         close H or die $!;
1788         runcmd @git, qw(remote add), 'origin', $giturl;
1789     }
1790     if ($hasgit) {
1791         progress "fetching existing git history";
1792         git_fetch_us();
1793         runcmd_ordryrun_local @git, qw(fetch origin);
1794     } else {
1795         progress "starting new git history";
1796     }
1797     fetch_from_archive() or no_such_package;
1798     my $vcsgiturl = $dsc->{'Vcs-Git'};
1799     if (length $vcsgiturl) {
1800         $vcsgiturl =~ s/\s+-b\s+\S+//g;
1801         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1802     }
1803     setup_new_tree();
1804     runcmd @git, qw(reset --hard), lrref();
1805     printdone "ready for work in $dstdir";
1806 }
1807
1808 sub fetch () {
1809     if (check_for_git()) {
1810         git_fetch_us();
1811     }
1812     fetch_from_archive() or no_such_package();
1813     printdone "fetched into ".lrref();
1814 }
1815
1816 sub pull () {
1817     fetch();
1818     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1819         lrref();
1820     printdone "fetched to ".lrref()." and merged into HEAD";
1821 }
1822
1823 sub check_not_dirty () {
1824     foreach my $f (qw(local-options local-patch-header)) {
1825         if (stat_exists "debian/source/$f") {
1826             fail "git tree contains debian/source/$f";
1827         }
1828     }
1829
1830     return if $ignoredirty;
1831
1832     my @cmd = (@git, qw(diff --quiet HEAD));
1833     debugcmd "+",@cmd;
1834     $!=0; $?=-1; system @cmd;
1835     return if !$?;
1836     if ($?==256) {
1837         fail "working tree is dirty (does not match HEAD)";
1838     } else {
1839         failedcmd @cmd;
1840     }
1841 }
1842
1843 sub commit_admin ($) {
1844     my ($m) = @_;
1845     progress "$m";
1846     runcmd_ordryrun_local @git, qw(commit -m), $m;
1847 }
1848
1849 sub commit_quilty_patch () {
1850     my $output = cmdoutput @git, qw(status --porcelain);
1851     my %adds;
1852     foreach my $l (split /\n/, $output) {
1853         next unless $l =~ m/\S/;
1854         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1855             $adds{$1}++;
1856         }
1857     }
1858     delete $adds{'.pc'}; # if there wasn't one before, don't add it
1859     if (!%adds) {
1860         progress "nothing quilty to commit, ok.";
1861         return;
1862     }
1863     my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
1864     runcmd_ordryrun_local @git, qw(add -f), @adds;
1865     commit_admin "Commit Debian 3.0 (quilt) metadata";
1866 }
1867
1868 sub get_source_format () {
1869     my %options;
1870     if (open F, "debian/source/options") {
1871         while (<F>) {
1872             next if m/^\s*\#/;
1873             next unless m/\S/;
1874             s/\s+$//; # ignore missing final newline
1875             if (m/\s*\#\s*/) {
1876                 my ($k, $v) = ($`, $'); #');
1877                 $v =~ s/^"(.*)"$/$1/;
1878                 $options{$k} = $v;
1879             } else {
1880                 $options{$_} = 1;
1881             }
1882         }
1883         F->error and die $!;
1884         close F;
1885     } else {
1886         die $! unless $!==&ENOENT;
1887     }
1888
1889     if (!open F, "debian/source/format") {
1890         die $! unless $!==&ENOENT;
1891         return '';
1892     }
1893     $_ = <F>;
1894     F->error and die $!;
1895     chomp;
1896     return ($_, \%options);
1897 }
1898
1899 sub madformat ($) {
1900     my ($format) = @_;
1901     return 0 unless $format eq '3.0 (quilt)';
1902     our $quilt_mode_warned;
1903     if ($quilt_mode eq 'nocheck') {
1904         progress "Not doing any fixup of \`$format' due to".
1905             " ----no-quilt-fixup or --quilt=nocheck"
1906             unless $quilt_mode_warned++;
1907         return 0;
1908     }
1909     progress "Format \`$format', need to check/update patch stack"
1910         unless $quilt_mode_warned++;
1911     return 1;
1912 }
1913
1914 sub push_parse_changelog ($) {
1915     my ($clogpfn) = @_;
1916
1917     my $clogp = Dpkg::Control::Hash->new();
1918     $clogp->load($clogpfn) or die;
1919
1920     $package = getfield $clogp, 'Source';
1921     my $cversion = getfield $clogp, 'Version';
1922     my $tag = debiantag($cversion, access_basedistro);
1923     runcmd @git, qw(check-ref-format), $tag;
1924
1925     my $dscfn = dscfn($cversion);
1926
1927     return ($clogp, $cversion, $tag, $dscfn);
1928 }
1929
1930 sub push_parse_dsc ($$$) {
1931     my ($dscfn,$dscfnwhat, $cversion) = @_;
1932     $dsc = parsecontrol($dscfn,$dscfnwhat);
1933     my $dversion = getfield $dsc, 'Version';
1934     my $dscpackage = getfield $dsc, 'Source';
1935     ($dscpackage eq $package && $dversion eq $cversion) or
1936         fail "$dscfn is for $dscpackage $dversion".
1937             " but debian/changelog is for $package $cversion";
1938 }
1939
1940 sub push_mktag ($$$$$$$) {
1941     my ($head,$clogp,$tag,
1942         $dscfn,
1943         $changesfile,$changesfilewhat,
1944         $tfn) = @_;
1945
1946     $dsc->{$ourdscfield[0]} = $head;
1947     $dsc->save("$dscfn.tmp") or die $!;
1948
1949     my $changes = parsecontrol($changesfile,$changesfilewhat);
1950     foreach my $field (qw(Source Distribution Version)) {
1951         $changes->{$field} eq $clogp->{$field} or
1952             fail "changes field $field \`$changes->{$field}'".
1953                 " does not match changelog \`$clogp->{$field}'";
1954     }
1955
1956     my $cversion = getfield $clogp, 'Version';
1957     my $clogsuite = getfield $clogp, 'Distribution';
1958
1959     # We make the git tag by hand because (a) that makes it easier
1960     # to control the "tagger" (b) we can do remote signing
1961     my $authline = clogp_authline $clogp;
1962     my $delibs = join(" ", "",@deliberatelies);
1963     my $declaredistro = access_basedistro();
1964     open TO, '>', $tfn->('.tmp') or die $!;
1965     print TO <<END or die $!;
1966 object $head
1967 type commit
1968 tag $tag
1969 tagger $authline
1970
1971 $package release $cversion for $clogsuite ($csuite) [dgit]
1972 [dgit distro=$declaredistro$delibs]
1973 END
1974     foreach my $ref (sort keys %previously) {
1975                     print TO <<END or die $!;
1976 [dgit previously:$ref=$previously{$ref}]
1977 END
1978     }
1979
1980     close TO or die $!;
1981
1982     my $tagobjfn = $tfn->('.tmp');
1983     if ($sign) {
1984         if (!defined $keyid) {
1985             $keyid = access_cfg('keyid','RETURN-UNDEF');
1986         }
1987         if (!defined $keyid) {
1988             $keyid = getfield $clogp, 'Maintainer';
1989         }
1990         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1991         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1992         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1993         push @sign_cmd, $tfn->('.tmp');
1994         runcmd_ordryrun @sign_cmd;
1995         if (act_scary()) {
1996             $tagobjfn = $tfn->('.signed.tmp');
1997             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1998                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1999         }
2000     }
2001
2002     return ($tagobjfn);
2003 }
2004
2005 sub sign_changes ($) {
2006     my ($changesfile) = @_;
2007     if ($sign) {
2008         my @debsign_cmd = @debsign;
2009         push @debsign_cmd, "-k$keyid" if defined $keyid;
2010         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
2011         push @debsign_cmd, $changesfile;
2012         runcmd_ordryrun @debsign_cmd;
2013     }
2014 }
2015
2016 sub dopush ($) {
2017     my ($forceflag) = @_;
2018     printdebug "actually entering push\n";
2019     supplementary_message(<<'END');
2020 Push failed, while preparing your push.
2021 You can retry the push, after fixing the problem, if you like.
2022 END
2023     prep_ud();
2024
2025     access_giturl(); # check that success is vaguely likely
2026     select_tagformat();
2027
2028     my $clogpfn = ".git/dgit/changelog.822.tmp";
2029     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
2030
2031     responder_send_file('parsed-changelog', $clogpfn);
2032
2033     my ($clogp, $cversion, $tag, $dscfn) =
2034         push_parse_changelog("$clogpfn");
2035
2036     my $dscpath = "$buildproductsdir/$dscfn";
2037     stat_exists $dscpath or
2038         fail "looked for .dsc $dscfn, but $!;".
2039             " maybe you forgot to build";
2040
2041     responder_send_file('dsc', $dscpath);
2042
2043     push_parse_dsc($dscpath, $dscfn, $cversion);
2044
2045     my $format = getfield $dsc, 'Format';
2046     printdebug "format $format\n";
2047
2048     my $head = git_rev_parse('HEAD');
2049
2050     if (madformat($format)) {
2051         # user might have not used dgit build, so maybe do this now:
2052         if (quiltmode_splitbrain()) {
2053             my $upstreamversion = $clogp->{Version};
2054             $upstreamversion =~ s/-[^-]*$//;
2055             changedir $ud;
2056             quilt_make_fake_dsc($upstreamversion);
2057             my ($dgitview, $cachekey) =
2058                 quilt_check_splitbrain_cache($head, $upstreamversion);
2059             $dgitview or fail
2060  "--quilt=$quilt_mode but no cached dgit view:
2061  perhaps tree changed since dgit build[-source] ?";
2062             $split_brain = 1;
2063             changedir '../../../..';
2064             prep_ud(); # so _only_subdir() works, below
2065         } else {
2066             commit_quilty_patch();
2067         }
2068     }
2069
2070     die 'xxx fast forward (should not depend on quilt mode, but will always be needed if we did $split_brain)' if $split_brain;
2071
2072     check_not_dirty();
2073     changedir $ud;
2074     progress "checking that $dscfn corresponds to HEAD";
2075     runcmd qw(dpkg-source -x --),
2076         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
2077     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
2078     check_for_vendor_patches() if madformat($dsc->{format});
2079     changedir '../../../..';
2080     my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
2081     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
2082     debugcmd "+",@diffcmd;
2083     $!=0; $?=-1;
2084     my $r = system @diffcmd;
2085     if ($r) {
2086         if ($r==256) {
2087             fail "$dscfn specifies a different tree to your HEAD commit;".
2088                 " perhaps you forgot to build".
2089                 ($diffopt eq '--exit-code' ? "" :
2090                  " (run with -D to see full diff output)");
2091         } else {
2092             failedcmd @diffcmd;
2093         }
2094     }
2095     if (!$changesfile) {
2096         my $pat = changespat $cversion;
2097         my @cs = glob "$buildproductsdir/$pat";
2098         fail "failed to find unique changes file".
2099             " (looked for $pat in $buildproductsdir);".
2100             " perhaps you need to use dgit -C"
2101             unless @cs==1;
2102         ($changesfile) = @cs;
2103     } else {
2104         $changesfile = "$buildproductsdir/$changesfile";
2105     }
2106
2107     responder_send_file('changes',$changesfile);
2108     responder_send_command("param head $head");
2109     responder_send_command("param csuite $csuite");
2110
2111     if (deliberately_not_fast_forward) {
2112         git_for_each_ref(lrfetchrefs, sub {
2113             my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
2114             my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
2115             responder_send_command("previously $rrefname=$objid");
2116             $previously{$rrefname} = $objid;
2117         });
2118     }
2119
2120     my $tfn = sub { ".git/dgit/tag$_[0]"; };
2121     my $tagobjfn;
2122
2123     supplementary_message(<<'END');
2124 Push failed, while signing the tag.
2125 You can retry the push, after fixing the problem, if you like.
2126 END
2127     # If we manage to sign but fail to record it anywhere, it's fine.
2128     if ($we_are_responder) {
2129         $tagobjfn = $tfn->('.signed.tmp');
2130         responder_receive_files('signed-tag', $tagobjfn);
2131     } else {
2132         $tagobjfn =
2133             push_mktag($head,$clogp,$tag,
2134                        $dscpath,
2135                        $changesfile,$changesfile,
2136                        $tfn);
2137     }
2138     supplementary_message(<<'END');
2139 Push failed, *after* signing the tag.
2140 If you want to try again, you should use a new version number.
2141 END
2142
2143     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
2144     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
2145     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
2146
2147     supplementary_message(<<'END');
2148 Push failed, while updating the remote git repository - see messages above.
2149 If you want to try again, you should use a new version number.
2150 END
2151     if (!check_for_git()) {
2152         create_remote_git_repo();
2153     }
2154     runcmd_ordryrun @git, qw(push),access_giturl(),
2155         $forceflag."HEAD:".rrref(), $forceflag."refs/tags/$tag";
2156     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
2157
2158     supplementary_message(<<'END');
2159 Push failed, after updating the remote git repository.
2160 If you want to try again, you must use a new version number.
2161 END
2162     if ($we_are_responder) {
2163         my $dryrunsuffix = act_local() ? "" : ".tmp";
2164         responder_receive_files('signed-dsc-changes',
2165                                 "$dscpath$dryrunsuffix",
2166                                 "$changesfile$dryrunsuffix");
2167     } else {
2168         if (act_local()) {
2169             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
2170         } else {
2171             progress "[new .dsc left in $dscpath.tmp]";
2172         }
2173         sign_changes $changesfile;
2174     }
2175
2176     supplementary_message(<<END);
2177 Push failed, while uploading package(s) to the archive server.
2178 You can retry the upload of exactly these same files with dput of:
2179   $changesfile
2180 If that .changes file is broken, you will need to use a new version
2181 number for your next attempt at the upload.
2182 END
2183     my $host = access_cfg('upload-host','RETURN-UNDEF');
2184     my @hostarg = defined($host) ? ($host,) : ();
2185     runcmd_ordryrun @dput, @hostarg, $changesfile;
2186     printdone "pushed and uploaded $cversion";
2187
2188     supplementary_message('');
2189     responder_send_command("complete");
2190 }
2191
2192 sub cmd_clone {
2193     parseopts();
2194     notpushing();
2195     my $dstdir;
2196     badusage "-p is not allowed with clone; specify as argument instead"
2197         if defined $package;
2198     if (@ARGV==1) {
2199         ($package) = @ARGV;
2200     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
2201         ($package,$isuite) = @ARGV;
2202     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
2203         ($package,$dstdir) = @ARGV;
2204     } elsif (@ARGV==3) {
2205         ($package,$isuite,$dstdir) = @ARGV;
2206     } else {
2207         badusage "incorrect arguments to dgit clone";
2208     }
2209     $dstdir ||= "$package";
2210
2211     if (stat_exists $dstdir) {
2212         fail "$dstdir already exists";
2213     }
2214
2215     my $cwd_remove;
2216     if ($rmonerror && !$dryrun_level) {
2217         $cwd_remove= getcwd();
2218         unshift @end, sub { 
2219             return unless defined $cwd_remove;
2220             if (!chdir "$cwd_remove") {
2221                 return if $!==&ENOENT;
2222                 die "chdir $cwd_remove: $!";
2223             }
2224             if (stat $dstdir) {
2225                 rmtree($dstdir) or die "remove $dstdir: $!\n";
2226             } elsif (!grep { $! == $_ }
2227                      (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
2228             } else {
2229                 print STDERR "check whether to remove $dstdir: $!\n";
2230             }
2231         };
2232     }
2233
2234     clone($dstdir);
2235     $cwd_remove = undef;
2236 }
2237
2238 sub branchsuite () {
2239     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
2240     if ($branch =~ m#$lbranch_re#o) {
2241         return $1;
2242     } else {
2243         return undef;
2244     }
2245 }
2246
2247 sub fetchpullargs () {
2248     notpushing();
2249     if (!defined $package) {
2250         my $sourcep = parsecontrol('debian/control','debian/control');
2251         $package = getfield $sourcep, 'Source';
2252     }
2253     if (@ARGV==0) {
2254 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
2255         if (!$isuite) {
2256             my $clogp = parsechangelog();
2257             $isuite = getfield $clogp, 'Distribution';
2258         }
2259         canonicalise_suite();
2260         progress "fetching from suite $csuite";
2261     } elsif (@ARGV==1) {
2262         ($isuite) = @ARGV;
2263         canonicalise_suite();
2264     } else {
2265         badusage "incorrect arguments to dgit fetch or dgit pull";
2266     }
2267 }
2268
2269 sub cmd_fetch {
2270     parseopts();
2271     fetchpullargs();
2272     fetch();
2273 }
2274
2275 sub cmd_pull {
2276     parseopts();
2277     fetchpullargs();
2278     pull();
2279 }
2280
2281 sub cmd_push {
2282     parseopts();
2283     pushing();
2284     badusage "-p is not allowed with dgit push" if defined $package;
2285     check_not_dirty();
2286     my $clogp = parsechangelog();
2287     $package = getfield $clogp, 'Source';
2288     my $specsuite;
2289     if (@ARGV==0) {
2290     } elsif (@ARGV==1) {
2291         ($specsuite) = (@ARGV);
2292     } else {
2293         badusage "incorrect arguments to dgit push";
2294     }
2295     $isuite = getfield $clogp, 'Distribution';
2296     if ($new_package) {
2297         local ($package) = $existing_package; # this is a hack
2298         canonicalise_suite();
2299     } else {
2300         canonicalise_suite();
2301     }
2302     if (defined $specsuite &&
2303         $specsuite ne $isuite &&
2304         $specsuite ne $csuite) {
2305             fail "dgit push: changelog specifies $isuite ($csuite)".
2306                 " but command line specifies $specsuite";
2307     }
2308     supplementary_message(<<'END');
2309 Push failed, while checking state of the archive.
2310 You can retry the push, after fixing the problem, if you like.
2311 END
2312     if (check_for_git()) {
2313         git_fetch_us();
2314     }
2315     my $forceflag = '';
2316     if (fetch_from_archive()) {
2317         if (is_fast_fwd(lrref(), 'HEAD')) {
2318             # ok
2319         } elsif (deliberately_not_fast_forward) {
2320             $forceflag = '+';
2321         } else {
2322             fail "dgit push: HEAD is not a descendant".
2323                 " of the archive's version.\n".
2324                 "dgit: To overwrite its contents,".
2325                 " use git merge -s ours ".lrref().".\n".
2326                 "dgit: To rewind history, if permitted by the archive,".
2327                 " use --deliberately-not-fast-forward";
2328         }
2329     } else {
2330         $new_package or
2331             fail "package appears to be new in this suite;".
2332                 " if this is intentional, use --new";
2333     }
2334     dopush($forceflag);
2335 }
2336
2337 #---------- remote commands' implementation ----------
2338
2339 sub cmd_remote_push_build_host {
2340     my ($nrargs) = shift @ARGV;
2341     my (@rargs) = @ARGV[0..$nrargs-1];
2342     @ARGV = @ARGV[$nrargs..$#ARGV];
2343     die unless @rargs;
2344     my ($dir,$vsnwant) = @rargs;
2345     # vsnwant is a comma-separated list; we report which we have
2346     # chosen in our ready response (so other end can tell if they
2347     # offered several)
2348     $debugprefix = ' ';
2349     $we_are_responder = 1;
2350     $us .= " (build host)";
2351
2352     pushing();
2353
2354     open PI, "<&STDIN" or die $!;
2355     open STDIN, "/dev/null" or die $!;
2356     open PO, ">&STDOUT" or die $!;
2357     autoflush PO 1;
2358     open STDOUT, ">&STDERR" or die $!;
2359     autoflush STDOUT 1;
2360
2361     $vsnwant //= 1;
2362     ($protovsn) = grep {
2363         $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
2364     } @rpushprotovsn_support;
2365
2366     fail "build host has dgit rpush protocol versions ".
2367         (join ",", @rpushprotovsn_support).
2368         " but invocation host has $vsnwant"
2369         unless defined $protovsn;
2370
2371     responder_send_command("dgit-remote-push-ready $protovsn");
2372     rpush_handle_protovsn_bothends();
2373     changedir $dir;
2374     &cmd_push;
2375 }
2376
2377 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
2378 # ... for compatibility with proto vsn.1 dgit (just so that user gets
2379 #     a good error message)
2380
2381 sub rpush_handle_protovsn_bothends () {
2382     if ($protovsn < 4) {
2383         fail "rpush negotiated protocol version $protovsn".
2384             " which supports old tag format only".
2385             " but trying to use new format (".$tagformat->[1].")"
2386             if $tagformat && $tagformat->[0] ne 'old';
2387         $tagformat = ['old', "rpush negotiated protocol $protovsn", 0];
2388     }
2389     select_tagformat();
2390 }
2391
2392 our $i_tmp;
2393
2394 sub i_cleanup {
2395     local ($@, $?);
2396     my $report = i_child_report();
2397     if (defined $report) {
2398         printdebug "($report)\n";
2399     } elsif ($i_child_pid) {
2400         printdebug "(killing build host child $i_child_pid)\n";
2401         kill 15, $i_child_pid;
2402     }
2403     if (defined $i_tmp && !defined $initiator_tempdir) {
2404         changedir "/";
2405         eval { rmtree $i_tmp; };
2406     }
2407 }
2408
2409 END { i_cleanup(); }
2410
2411 sub i_method {
2412     my ($base,$selector,@args) = @_;
2413     $selector =~ s/\-/_/g;
2414     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2415 }
2416
2417 sub cmd_rpush {
2418     pushing();
2419     my $host = nextarg;
2420     my $dir;
2421     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2422         $host = $1;
2423         $dir = $'; #';
2424     } else {
2425         $dir = nextarg;
2426     }
2427     $dir =~ s{^-}{./-};
2428     my @rargs = ($dir);
2429     push @rargs, join ",", @rpushprotovsn_support;
2430     my @rdgit;
2431     push @rdgit, @dgit;
2432     push @rdgit, @ropts;
2433     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2434     push @rdgit, @ARGV;
2435     my @cmd = (@ssh, $host, shellquote @rdgit);
2436     debugcmd "+",@cmd;
2437
2438     if (defined $initiator_tempdir) {
2439         rmtree $initiator_tempdir;
2440         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2441         $i_tmp = $initiator_tempdir;
2442     } else {
2443         $i_tmp = tempdir();
2444     }
2445     $i_child_pid = open2(\*RO, \*RI, @cmd);
2446     changedir $i_tmp;
2447     ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
2448     die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
2449     $supplementary_message = '' unless $protovsn >= 3;
2450     rpush_handle_protovsn_bothends();
2451     for (;;) {
2452         my ($icmd,$iargs) = initiator_expect {
2453             m/^(\S+)(?: (.*))?$/;
2454             ($1,$2);
2455         };
2456         i_method "i_resp", $icmd, $iargs;
2457     }
2458 }
2459
2460 sub i_resp_progress ($) {
2461     my ($rhs) = @_;
2462     my $msg = protocol_read_bytes \*RO, $rhs;
2463     progress $msg;
2464 }
2465
2466 sub i_resp_supplementary_message ($) {
2467     my ($rhs) = @_;
2468     $supplementary_message = protocol_read_bytes \*RO, $rhs;
2469 }
2470
2471 sub i_resp_complete {
2472     my $pid = $i_child_pid;
2473     $i_child_pid = undef; # prevents killing some other process with same pid
2474     printdebug "waiting for build host child $pid...\n";
2475     my $got = waitpid $pid, 0;
2476     die $! unless $got == $pid;
2477     die "build host child failed $?" if $?;
2478
2479     i_cleanup();
2480     printdebug "all done\n";
2481     exit 0;
2482 }
2483
2484 sub i_resp_file ($) {
2485     my ($keyword) = @_;
2486     my $localname = i_method "i_localname", $keyword;
2487     my $localpath = "$i_tmp/$localname";
2488     stat_exists $localpath and
2489         badproto \*RO, "file $keyword ($localpath) twice";
2490     protocol_receive_file \*RO, $localpath;
2491     i_method "i_file", $keyword;
2492 }
2493
2494 our %i_param;
2495
2496 sub i_resp_param ($) {
2497     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2498     $i_param{$1} = $2;
2499 }
2500
2501 sub i_resp_previously ($) {
2502     $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2503         or badproto \*RO, "bad previously spec";
2504     my $r = system qw(git check-ref-format), $1;
2505     die "bad previously ref spec ($r)" if $r;
2506     $previously{$1} = $2;
2507 }
2508
2509 our %i_wanted;
2510
2511 sub i_resp_want ($) {
2512     my ($keyword) = @_;
2513     die "$keyword ?" if $i_wanted{$keyword}++;
2514     my @localpaths = i_method "i_want", $keyword;
2515     printdebug "[[  $keyword @localpaths\n";
2516     foreach my $localpath (@localpaths) {
2517         protocol_send_file \*RI, $localpath;
2518     }
2519     print RI "files-end\n" or die $!;
2520 }
2521
2522 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2523
2524 sub i_localname_parsed_changelog {
2525     return "remote-changelog.822";
2526 }
2527 sub i_file_parsed_changelog {
2528     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2529         push_parse_changelog "$i_tmp/remote-changelog.822";
2530     die if $i_dscfn =~ m#/|^\W#;
2531 }
2532
2533 sub i_localname_dsc {
2534     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2535     return $i_dscfn;
2536 }
2537 sub i_file_dsc { }
2538
2539 sub i_localname_changes {
2540     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2541     $i_changesfn = $i_dscfn;
2542     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2543     return $i_changesfn;
2544 }
2545 sub i_file_changes { }
2546
2547 sub i_want_signed_tag {
2548     printdebug Dumper(\%i_param, $i_dscfn);
2549     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2550         && defined $i_param{'csuite'}
2551         or badproto \*RO, "premature desire for signed-tag";
2552     my $head = $i_param{'head'};
2553     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2554
2555     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2556     $csuite = $&;
2557     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2558
2559     my $tagobjfn =
2560         push_mktag $head, $i_clogp, $i_tag,
2561             $i_dscfn,
2562             $i_changesfn, 'remote changes',
2563             sub { "tag$_[0]"; };
2564
2565     return $tagobjfn;
2566 }
2567
2568 sub i_want_signed_dsc_changes {
2569     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2570     sign_changes $i_changesfn;
2571     return ($i_dscfn, $i_changesfn);
2572 }
2573
2574 #---------- building etc. ----------
2575
2576 our $version;
2577 our $sourcechanges;
2578 our $dscfn;
2579
2580 #----- `3.0 (quilt)' handling -----
2581
2582 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2583
2584 sub quiltify_dpkg_commit ($$$;$) {
2585     my ($patchname,$author,$msg, $xinfo) = @_;
2586     $xinfo //= '';
2587
2588     mkpath '.git/dgit';
2589     my $descfn = ".git/dgit/quilt-description.tmp";
2590     open O, '>', $descfn or die "$descfn: $!";
2591     $msg =~ s/\s+$//g;
2592     $msg =~ s/\n/\n /g;
2593     $msg =~ s/^\s+$/ ./mg;
2594     print O <<END or die $!;
2595 Description: $msg
2596 Author: $author
2597 $xinfo
2598 ---
2599
2600 END
2601     close O or die $!;
2602
2603     {
2604         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2605         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2606         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2607         runcmd @dpkgsource, qw(--commit .), $patchname;
2608     }
2609 }
2610
2611 sub quiltify_trees_differ ($$;$$) {
2612     my ($x,$y,$finegrained,$ignorenamesr) = @_;
2613     # returns true iff the two tree objects differ other than in debian/
2614     # with $finegrained,
2615     # returns bitmask 01 - differ in upstream files except .gitignore
2616     #                 02 - differ in .gitignore
2617     # if $ignorenamesr is defined, $ingorenamesr->{$fn}
2618     #  is set for each modified .gitignore filename $fn
2619     local $/=undef;
2620     my @cmd = (@git, qw(diff-tree --name-only -z));
2621     push @cmd, qw(-r) if $finegrained;
2622     push @cmd, $x, $y;
2623     my $diffs= cmdoutput @cmd;
2624     my $r = 0;
2625     foreach my $f (split /\0/, $diffs) {
2626         next if $f =~ m#^debian(?:/.*)?$#s;
2627         my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
2628         $r |= $isignore ? 02 : 01;
2629         $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
2630     }
2631     printdebug "quiltify_trees_differ $x $y => $r\n";
2632     return $r;
2633 }
2634
2635 sub quiltify_tree_sentinelfiles ($) {
2636     # lists the `sentinel' files present in the tree
2637     my ($x) = @_;
2638     my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2639         qw(-- debian/rules debian/control);
2640     $r =~ s/\n/,/g;
2641     return $r;
2642 }
2643
2644 sub quiltify_splitbrain_needed () {
2645     if (!$split_brain) {
2646         progress "dgit view: changes are required...";
2647         runcmd @git, qw(checkout -q -b dgit-view);
2648         $split_brain = 1;
2649     }
2650 }
2651
2652 sub quiltify_splitbrain ($$$$$$) {
2653     my ($clogp, $unapplied, $headref, $diffbits,
2654         $editedignores, $cachekey) = @_;
2655     if ($quilt_mode !~ m/gbp|dpm/) {
2656         # treat .gitignore just like any other upstream file
2657         $diffbits = { %$diffbits };
2658         $_ = !!$_ foreach values %$diffbits;
2659     }
2660     # We would like any commits we generate to be reproducible
2661     my @authline = clogp_authline($clogp);
2662     local $ENV{GIT_COMMITTER_NAME} =  $authline[0];
2663     local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2664     local $ENV{GIT_COMMITTER_DATE} =  $authline[2];
2665         
2666     if ($quilt_mode =~ m/gbp|unapplied/ &&
2667         ($diffbits->{H2O} & 01)) {
2668         my $msg =
2669  "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
2670  " but git tree differs from orig in upstream files.";
2671         if (!stat_exists "debian/patches") {
2672             $msg .=
2673  "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
2674         }  
2675         fail $msg;
2676     }
2677     if ($quilt_mode =~ m/gbp|unapplied/ &&
2678         ($diffbits->{O2A} & 01)) { # some patches
2679         quiltify_splitbrain_needed();
2680         progress "dgit view: creating patches-applied version using gbp pq";
2681         runcmd shell_cmd 'exec >/dev/null', @gbp, qw(pq import);
2682         # gbp pq import creates a fresh branch; push back to dgit-view
2683         runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
2684         runcmd @git, qw(checkout -q dgit-view);
2685     }
2686     if (($diffbits->{H2O} & 02) && # user has modified .gitignore
2687         !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
2688         quiltify_splitbrain_needed();
2689         progress "dgit view: creating patch to represent .gitignore changes";
2690         ensuredir "debian/patches";
2691         my $gipatch = "debian/patches/auto-gitignore";
2692         open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
2693         stat GIPATCH or die "$gipatch: $!";
2694         fail "$gipatch already exists; but want to create it".
2695             " to record .gitignore changes" if (stat _)[7];
2696         print GIPATCH <<END or die "$gipatch: $!";
2697 Subject: Update .gitignore from Debian packaging branch
2698
2699 The Debian packaging git branch contains these updates to the upstream
2700 .gitignore file(s).  This patch is autogenerated, to provide these
2701 updates to users of the official Debian archive view of the package.
2702
2703 [dgit version $our_version]
2704 ---
2705 END
2706         close GIPATCH or die "$gipatch: $!";
2707         runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
2708             $unapplied, $headref, "--", sort keys %$editedignores;
2709         open SERIES, "+>>", "debian/patches/series" or die $!;
2710         defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
2711         my $newline;
2712         defined read SERIES, $newline, 1 or die $!;
2713         print SERIES "\n" or die $! unless $newline eq "\n";
2714         print SERIES "auto-gitignore\n" or die $!;
2715         close SERIES or die  $!;
2716         runcmd @git, qw(add -- debian/patches/series), $gipatch;
2717         commit_admin "Commit patch to update .gitignore";
2718     }
2719
2720     my $dgitview = git_rev_parse 'refs/heads/dgit-view';
2721
2722     changedir '../../../..';
2723     ensuredir ".git/logs/refs/dgit-intern";
2724     my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
2725       or die $!;
2726     runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
2727         $dgitview;
2728
2729     progress "dgit view: created (commit id $dgitview)";
2730
2731     changedir '.git/dgit/unpack/work';
2732 }
2733
2734 sub quiltify ($$$$) {
2735     my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
2736
2737     # Quilt patchification algorithm
2738     #
2739     # We search backwards through the history of the main tree's HEAD
2740     # (T) looking for a start commit S whose tree object is identical
2741     # to to the patch tip tree (ie the tree corresponding to the
2742     # current dpkg-committed patch series).  For these purposes
2743     # `identical' disregards anything in debian/ - this wrinkle is
2744     # necessary because dpkg-source treates debian/ specially.
2745     #
2746     # We can only traverse edges where at most one of the ancestors'
2747     # trees differs (in changes outside in debian/).  And we cannot
2748     # handle edges which change .pc/ or debian/patches.  To avoid
2749     # going down a rathole we avoid traversing edges which introduce
2750     # debian/rules or debian/control.  And we set a limit on the
2751     # number of edges we are willing to look at.
2752     #
2753     # If we succeed, we walk forwards again.  For each traversed edge
2754     # PC (with P parent, C child) (starting with P=S and ending with
2755     # C=T) to we do this:
2756     #  - git checkout C
2757     #  - dpkg-source --commit with a patch name and message derived from C
2758     # After traversing PT, we git commit the changes which
2759     # should be contained within debian/patches.
2760
2761     # The search for the path S..T is breadth-first.  We maintain a
2762     # todo list containing search nodes.  A search node identifies a
2763     # commit, and looks something like this:
2764     #  $p = {
2765     #      Commit => $git_commit_id,
2766     #      Child => $c,                          # or undef if P=T
2767     #      Whynot => $reason_edge_PC_unsuitable, # in @nots only
2768     #      Nontrivial => true iff $p..$c has relevant changes
2769     #  };
2770
2771     my @todo;
2772     my @nots;
2773     my $sref_S;
2774     my $max_work=100;
2775     my %considered; # saves being exponential on some weird graphs
2776
2777     my $t_sentinels = quiltify_tree_sentinelfiles $target;
2778
2779     my $not = sub {
2780         my ($search,$whynot) = @_;
2781         printdebug " search NOT $search->{Commit} $whynot\n";
2782         $search->{Whynot} = $whynot;
2783         push @nots, $search;
2784         no warnings qw(exiting);
2785         next;
2786     };
2787
2788     push @todo, {
2789         Commit => $target,
2790     };
2791
2792     while (@todo) {
2793         my $c = shift @todo;
2794         next if $considered{$c->{Commit}}++;
2795
2796         $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2797
2798         printdebug "quiltify investigate $c->{Commit}\n";
2799
2800         # are we done?
2801         if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2802             printdebug " search finished hooray!\n";
2803             $sref_S = $c;
2804             last;
2805         }
2806
2807         if ($quilt_mode eq 'nofix') {
2808             fail "quilt fixup required but quilt mode is \`nofix'\n".
2809                 "HEAD commit $c->{Commit} differs from tree implied by ".
2810                 " debian/patches (tree object $oldtiptree)";
2811         }
2812         if ($quilt_mode eq 'smash') {
2813             printdebug " search quitting smash\n";
2814             last;
2815         }
2816
2817         my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2818         $not->($c, "has $c_sentinels not $t_sentinels")
2819             if $c_sentinels ne $t_sentinels;
2820
2821         my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2822         $commitdata =~ m/\n\n/;
2823         $commitdata =~ $`;
2824         my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2825         @parents = map { { Commit => $_, Child => $c } } @parents;
2826
2827         $not->($c, "root commit") if !@parents;
2828
2829         foreach my $p (@parents) {
2830             $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2831         }
2832         my $ndiffers = grep { $_->{Nontrivial} } @parents;
2833         $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2834
2835         foreach my $p (@parents) {
2836             printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2837
2838             my @cmd= (@git, qw(diff-tree -r --name-only),
2839                       $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2840             my $patchstackchange = cmdoutput @cmd;
2841             if (length $patchstackchange) {
2842                 $patchstackchange =~ s/\n/,/g;
2843                 $not->($p, "changed $patchstackchange");
2844             }
2845
2846             printdebug " search queue P=$p->{Commit} ",
2847                 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2848             push @todo, $p;
2849         }
2850     }
2851
2852     if (!$sref_S) {
2853         printdebug "quiltify want to smash\n";
2854
2855         my $abbrev = sub {
2856             my $x = $_[0]{Commit};
2857             $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2858             return $x;
2859         };
2860         my $reportnot = sub {
2861             my ($notp) = @_;
2862             my $s = $abbrev->($notp);
2863             my $c = $notp->{Child};
2864             $s .= "..".$abbrev->($c) if $c;
2865             $s .= ": ".$notp->{Whynot};
2866             return $s;
2867         };
2868         if ($quilt_mode eq 'linear') {
2869             print STDERR "$us: quilt fixup cannot be linear.  Stopped at:\n";
2870             foreach my $notp (@nots) {
2871                 print STDERR "$us:  ", $reportnot->($notp), "\n";
2872             }
2873             print STDERR "$us: $_\n" foreach @$failsuggestion;
2874             fail "quilt fixup naive history linearisation failed.\n".
2875  "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2876         } elsif ($quilt_mode eq 'smash') {
2877         } elsif ($quilt_mode eq 'auto') {
2878             progress "quilt fixup cannot be linear, smashing...";
2879         } else {
2880             die "$quilt_mode ?";
2881         }
2882
2883         my $time = time;
2884         my $ncommits = 3;
2885         my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2886
2887         quiltify_dpkg_commit "auto-$version-$target-$time",
2888             (getfield $clogp, 'Maintainer'),
2889             "Automatically generated patch ($clogp->{Version})\n".
2890             "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2891         return;
2892     }
2893
2894     progress "quiltify linearisation planning successful, executing...";
2895
2896     for (my $p = $sref_S;
2897          my $c = $p->{Child};
2898          $p = $p->{Child}) {
2899         printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2900         next unless $p->{Nontrivial};
2901
2902         my $cc = $c->{Commit};
2903
2904         my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2905         $commitdata =~ m/\n\n/ or die "$c ?";
2906         $commitdata = $`;
2907         my $msg = $'; #';
2908         $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2909         my $author = $1;
2910
2911         $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2912
2913         my $title = $1;
2914         my $patchname = $title;
2915         $patchname =~ s/[.:]$//;
2916         $patchname =~ y/ A-Z/-a-z/;
2917         $patchname =~ y/-a-z0-9_.+=~//cd;
2918         $patchname =~ s/^\W/x-$&/;
2919         $patchname = substr($patchname,0,40);
2920         my $index;
2921         for ($index='';
2922              stat "debian/patches/$patchname$index";
2923              $index++) { }
2924         $!==ENOENT or die "$patchname$index $!";
2925
2926         runcmd @git, qw(checkout -q), $cc;
2927
2928         # We use the tip's changelog so that dpkg-source doesn't
2929         # produce complaining messages from dpkg-parsechangelog.  None
2930         # of the information dpkg-source gets from the changelog is
2931         # actually relevant - it gets put into the original message
2932         # which dpkg-source provides our stunt editor, and then
2933         # overwritten.
2934         runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2935
2936         quiltify_dpkg_commit "$patchname$index", $author, $msg,
2937             "X-Dgit-Generated: $clogp->{Version} $cc\n";
2938
2939         runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2940     }
2941
2942     runcmd @git, qw(checkout -q master);
2943 }
2944
2945 sub build_maybe_quilt_fixup () {
2946     my ($format,$fopts) = get_source_format;
2947     return unless madformat $format;
2948     # sigh
2949
2950     check_for_vendor_patches();
2951
2952     my $clogp = parsechangelog();
2953     my $headref = git_rev_parse('HEAD');
2954
2955     prep_ud();
2956     changedir $ud;
2957
2958     my $upstreamversion=$version;
2959     $upstreamversion =~ s/-[^-]*$//;
2960
2961     if ($fopts->{'single-debian-patch'}) {
2962         quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
2963     } else {
2964         quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
2965     }
2966
2967     die 'bug' if $split_brain && !$need_split_build_invocation;
2968
2969     changedir '../../../..';
2970     runcmd_ordryrun_local
2971         @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2972 }
2973
2974 sub quilt_fixup_mkwork ($) {
2975     my ($headref) = @_;
2976
2977     mkdir "work" or die $!;
2978     changedir "work";
2979     mktree_in_ud_here();
2980     runcmd @git, qw(reset -q --hard), $headref;
2981 }
2982
2983 sub quilt_fixup_linkorigs ($$) {
2984     my ($upstreamversion, $fn) = @_;
2985     # calls $fn->($leafname);
2986
2987     foreach my $f (<../../../../*>) { #/){
2988         my $b=$f; $b =~ s{.*/}{};
2989         {
2990             local ($debuglevel) = $debuglevel-1;
2991             printdebug "QF linkorigs $b, $f ?\n";
2992         }
2993         next unless is_orig_file $b, srcfn $upstreamversion,'';
2994         printdebug "QF linkorigs $b, $f Y\n";
2995         link_ltarget $f, $b or die "$b $!";
2996         $fn->($b);
2997     }
2998 }
2999
3000 sub quilt_fixup_delete_pc () {
3001     runcmd @git, qw(rm -rqf .pc);
3002     commit_admin "Commit removal of .pc (quilt series tracking data)";
3003 }
3004
3005 sub quilt_fixup_singlepatch ($$$) {
3006     my ($clogp, $headref, $upstreamversion) = @_;
3007
3008     progress "starting quiltify (single-debian-patch)";
3009
3010     # dpkg-source --commit generates new patches even if
3011     # single-debian-patch is in debian/source/options.  In order to
3012     # get it to generate debian/patches/debian-changes, it is
3013     # necessary to build the source package.
3014
3015     quilt_fixup_linkorigs($upstreamversion, sub { });
3016     quilt_fixup_mkwork($headref);
3017
3018     rmtree("debian/patches");
3019
3020     runcmd @dpkgsource, qw(-b .);
3021     chdir "..";
3022     runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
3023     rename srcfn("$upstreamversion", "/debian/patches"), 
3024            "work/debian/patches";
3025
3026     chdir "work";
3027     commit_quilty_patch();
3028 }
3029
3030 sub quilt_make_fake_dsc ($) {
3031     my ($upstreamversion) = @_;
3032
3033     my $fakeversion="$upstreamversion-~~DGITFAKE";
3034
3035     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
3036     print $fakedsc <<END or die $!;
3037 Format: 3.0 (quilt)
3038 Source: $package
3039 Version: $fakeversion
3040 Files:
3041 END
3042
3043     my $dscaddfile=sub {
3044         my ($b) = @_;
3045         
3046         my $md = new Digest::MD5;
3047
3048         my $fh = new IO::File $b, '<' or die "$b $!";
3049         stat $fh or die $!;
3050         my $size = -s _;
3051
3052         $md->addfile($fh);
3053         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
3054     };
3055
3056     quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
3057
3058     my @files=qw(debian/source/format debian/rules
3059                  debian/control debian/changelog);
3060     foreach my $maybe (qw(debian/patches debian/source/options
3061                           debian/tests/control)) {
3062         next unless stat_exists "../../../$maybe";
3063         push @files, $maybe;
3064     }
3065
3066     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
3067     runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
3068
3069     $dscaddfile->($debtar);
3070     close $fakedsc or die $!;
3071 }
3072
3073 sub quilt_check_splitbrain_cache ($$) {
3074     my ($headref, $upstreamversion) = @_;
3075     # Called only if we are in (potentially) split brain mode.
3076     # Called in $ud.
3077     # Computes the cache key and looks in the cache.
3078     # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
3079
3080     my $splitbrain_cachekey;
3081     
3082     progress
3083  "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
3084     # we look in the reflog of dgit-intern/quilt-cache
3085     # we look for an entry whose message is the key for the cache lookup
3086     my @cachekey = (qw(dgit), $our_version);
3087     push @cachekey, $upstreamversion;
3088     push @cachekey, $quilt_mode;
3089     push @cachekey, $headref;
3090
3091     push @cachekey, hashfile('fake.dsc');
3092
3093     my $srcshash = Digest::SHA->new(256);
3094     my %sfs = ( %INC, '$0(dgit)' => $0 );
3095     foreach my $sfk (sort keys %sfs) {
3096         next unless m/^\$0\b/ || m{^Debian/Dgit\b};
3097         $srcshash->add($sfk,"  ");
3098         $srcshash->add(hashfile($sfs{$sfk}));
3099         $srcshash->add("\n");
3100     }
3101     push @cachekey, $srcshash->hexdigest();
3102     $splitbrain_cachekey = "@cachekey";
3103
3104     my @cmd = (@git, qw(reflog), '--pretty=format:%H %gs',
3105                $splitbraincache);
3106     printdebug "splitbrain cachekey $splitbrain_cachekey\n";
3107     debugcmd "|(probably)",@cmd;
3108     my $child = open GC, "-|";  defined $child or die $!;
3109     if (!$child) {
3110         chdir '../../..' or die $!;
3111         if (!stat ".git/logs/refs/$splitbraincache") {
3112             $! == ENOENT or die $!;
3113             printdebug ">(no reflog)\n";
3114             exit 0;
3115         }
3116         exec @cmd; die $!;
3117     }
3118     while (<GC>) {
3119         chomp;
3120         printdebug ">| ", $_, "\n" if $debuglevel > 1;
3121         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
3122             
3123         my $cachehit = $1;
3124         quilt_fixup_mkwork($headref);
3125         if ($cachehit ne $headref) {
3126             progress "dgit view: found cached (commit id $cachehit)";
3127             runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
3128             $split_brain = 1;
3129             return ($cachehit, $splitbrain_cachekey);
3130         }
3131         progress "dgit view: found cached, no changes required";
3132         return ($headref, $splitbrain_cachekey);
3133     }
3134     die $! if GC->error;
3135     failedcmd unless close GC;
3136
3137     printdebug "splitbrain cache miss\n";
3138     return (undef, $splitbrain_cachekey);
3139 }
3140
3141 sub quilt_fixup_multipatch ($$$) {
3142     my ($clogp, $headref, $upstreamversion) = @_;
3143
3144     progress "examining quilt state (multiple patches, $quilt_mode mode)";
3145
3146     # Our objective is:
3147     #  - honour any existing .pc in case it has any strangeness
3148     #  - determine the git commit corresponding to the tip of
3149     #    the patch stack (if there is one)
3150     #  - if there is such a git commit, convert each subsequent
3151     #    git commit into a quilt patch with dpkg-source --commit
3152     #  - otherwise convert all the differences in the tree into
3153     #    a single git commit
3154     #
3155     # To do this we:
3156
3157     # Our git tree doesn't necessarily contain .pc.  (Some versions of
3158     # dgit would include the .pc in the git tree.)  If there isn't
3159     # one, we need to generate one by unpacking the patches that we
3160     # have.
3161     #
3162     # We first look for a .pc in the git tree.  If there is one, we
3163     # will use it.  (This is not the normal case.)
3164     #
3165     # Otherwise need to regenerate .pc so that dpkg-source --commit
3166     # can work.  We do this as follows:
3167     #     1. Collect all relevant .orig from parent directory
3168     #     2. Generate a debian.tar.gz out of
3169     #         debian/{patches,rules,source/format,source/options}
3170     #     3. Generate a fake .dsc containing just these fields:
3171     #          Format Source Version Files
3172     #     4. Extract the fake .dsc
3173     #        Now the fake .dsc has a .pc directory.
3174     # (In fact we do this in every case, because in future we will
3175     # want to search for a good base commit for generating patches.)
3176     #
3177     # Then we can actually do the dpkg-source --commit
3178     #     1. Make a new working tree with the same object
3179     #        store as our main tree and check out the main
3180     #        tree's HEAD.
3181     #     2. Copy .pc from the fake's extraction, if necessary
3182     #     3. Run dpkg-source --commit
3183     #     4. If the result has changes to debian/, then
3184     #          - git-add them them
3185     #          - git-add .pc if we had a .pc in-tree
3186     #          - git-commit
3187     #     5. If we had a .pc in-tree, delete it, and git-commit
3188     #     6. Back in the main tree, fast forward to the new HEAD
3189
3190     # Another situation we may have to cope with is gbp-style
3191     # patches-unapplied trees.
3192     #
3193     # We would want to detect these, so we know to escape into
3194     # quilt_fixup_gbp.  However, this is in general not possible.
3195     # Consider a package with a one patch which the dgit user reverts
3196     # (with git-revert or the moral equivalent).
3197     #
3198     # That is indistinguishable in contents from a patches-unapplied
3199     # tree.  And looking at the history to distinguish them is not
3200     # useful because the user might have made a confusing-looking git
3201     # history structure (which ought to produce an error if dgit can't
3202     # cope, not a silent reintroduction of an unwanted patch).
3203     #
3204     # So gbp users will have to pass an option.  But we can usually
3205     # detect their failure to do so: if the tree is not a clean
3206     # patches-applied tree, quilt linearisation fails, but the tree
3207     # _is_ a clean patches-unapplied tree, we can suggest that maybe
3208     # they want --quilt=unapplied.
3209     #
3210     # To help detect this, when we are extracting the fake dsc, we
3211     # first extract it with --skip-patches, and then apply the patches
3212     # afterwards with dpkg-source --before-build.  That lets us save a
3213     # tree object corresponding to .origs.
3214
3215     my $splitbrain_cachekey;
3216
3217     quilt_make_fake_dsc($upstreamversion);
3218
3219     if (quiltmode_splitbrain()) {
3220         my $cachehit;
3221         ($cachehit, $splitbrain_cachekey) =
3222             quilt_check_splitbrain_cache($headref, $upstreamversion);
3223         return if $cachehit;
3224     }
3225
3226     runcmd qw(sh -ec),
3227         'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
3228
3229     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
3230     rename $fakexdir, "fake" or die "$fakexdir $!";
3231
3232     changedir 'fake';
3233
3234     remove_stray_gits();
3235     mktree_in_ud_here();
3236
3237     rmtree '.pc';
3238
3239     runcmd @git, qw(add -Af .);
3240     my $unapplied=git_write_tree();
3241     printdebug "fake orig tree object $unapplied\n";
3242
3243     ensuredir '.pc';
3244
3245     runcmd qw(sh -ec),
3246         'exec dpkg-source --before-build . >/dev/null';
3247
3248     changedir '..';
3249
3250     quilt_fixup_mkwork($headref);
3251
3252     my $mustdeletepc=0;
3253     if (stat_exists ".pc") {
3254         -d _ or die;
3255         progress "Tree already contains .pc - will use it then delete it.";
3256         $mustdeletepc=1;
3257     } else {
3258         rename '../fake/.pc','.pc' or die $!;
3259     }
3260
3261     changedir '../fake';
3262     rmtree '.pc';
3263     runcmd @git, qw(add -Af .);
3264     my $oldtiptree=git_write_tree();
3265     printdebug "fake o+d/p tree object $unapplied\n";
3266     changedir '../work';
3267
3268
3269     # We calculate some guesswork now about what kind of tree this might
3270     # be.  This is mostly for error reporting.
3271
3272     my %editedignores;
3273     my $diffbits = {
3274         # H = user's HEAD
3275         # O = orig, without patches applied
3276         # A = "applied", ie orig with H's debian/patches applied
3277         H2O => quiltify_trees_differ($headref,  $unapplied, 1,\%editedignores),
3278         H2A => quiltify_trees_differ($headref,  $oldtiptree,1),
3279         O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
3280     };
3281
3282     my @dl;
3283     foreach my $b (qw(01 02)) {
3284         foreach my $v (qw(H2O O2A H2A)) {
3285             push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
3286         }
3287     }
3288     printdebug "differences \@dl @dl.\n";
3289
3290     progress sprintf
3291 "$us: quilt differences: src:  %s orig %s     gitignores:  %s orig %s\n".
3292 "$us: quilt differences:      HEAD %s o+d/p               HEAD %s o+d/p",
3293                              $dl[0], $dl[1],              $dl[3], $dl[4],
3294                                  $dl[2],                     $dl[5];
3295
3296     my @failsuggestion;
3297     if (!($diffbits->{H2O} & $diffbits->{O2A})) {
3298         push @failsuggestion, "This might be a patches-unapplied branch.";
3299     }  elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
3300         push @failsuggestion, "This might be a patches-applied branch.";
3301     }
3302     push @failsuggestion, "Maybe you need to specify one of".
3303         " --quilt=gbp --quilt=dpm --quilt=unapplied ?";
3304
3305     if (quiltmode_splitbrain()) {
3306         quiltify_splitbrain($clogp, $unapplied, $headref,
3307                             $diffbits, \%editedignores,
3308                             $splitbrain_cachekey);
3309         return;
3310     }
3311
3312     progress "starting quiltify (multiple patches, $quilt_mode mode)";
3313     quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
3314
3315     if (!open P, '>>', ".pc/applied-patches") {
3316         $!==&ENOENT or die $!;
3317     } else {
3318         close P;
3319     }
3320
3321     commit_quilty_patch();
3322
3323     if ($mustdeletepc) {
3324         quilt_fixup_delete_pc();
3325     }
3326 }
3327
3328 sub quilt_fixup_editor () {
3329     my $descfn = $ENV{$fakeeditorenv};
3330     my $editing = $ARGV[$#ARGV];
3331     open I1, '<', $descfn or die "$descfn: $!";
3332     open I2, '<', $editing or die "$editing: $!";
3333     unlink $editing or die "$editing: $!";
3334     open O, '>', $editing or die "$editing: $!";
3335     while (<I1>) { print O or die $!; } I1->error and die $!;
3336     my $copying = 0;
3337     while (<I2>) {
3338         $copying ||= m/^\-\-\- /;
3339         next unless $copying;
3340         print O or die $!;
3341     }
3342     I2->error and die $!;
3343     close O or die $1;
3344     exit 0;
3345 }
3346
3347 sub maybe_apply_patches_dirtily () {
3348     return unless $quilt_mode =~ m/gbp|unapplied/;
3349     print STDERR <<END or die $!;
3350
3351 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
3352 dgit: Have to apply the patches - making the tree dirty.
3353 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
3354
3355 END
3356     $patches_applied_dirtily = 01;
3357     $patches_applied_dirtily |= 02 unless stat_exists '.pc';
3358     runcmd qw(dpkg-source --before-build .);
3359 }
3360
3361 sub maybe_unapply_patches_again () {
3362     progress "dgit: Unapplying patches again to tidy up the tree."
3363         if $patches_applied_dirtily;
3364     runcmd qw(dpkg-source --after-build .)
3365         if $patches_applied_dirtily & 01;
3366     rmtree '.pc'
3367         if $patches_applied_dirtily & 02;
3368 }
3369
3370 #----- other building -----
3371
3372 our $clean_using_builder;
3373 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
3374 #   clean the tree before building (perhaps invoked indirectly by
3375 #   whatever we are using to run the build), rather than separately
3376 #   and explicitly by us.
3377
3378 sub clean_tree () {
3379     return if $clean_using_builder;
3380     if ($cleanmode eq 'dpkg-source') {
3381         maybe_apply_patches_dirtily();
3382         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
3383     } elsif ($cleanmode eq 'dpkg-source-d') {
3384         maybe_apply_patches_dirtily();
3385         runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
3386     } elsif ($cleanmode eq 'git') {
3387         runcmd_ordryrun_local @git, qw(clean -xdf);
3388     } elsif ($cleanmode eq 'git-ff') {
3389         runcmd_ordryrun_local @git, qw(clean -xdff);
3390     } elsif ($cleanmode eq 'check') {
3391         my $leftovers = cmdoutput @git, qw(clean -xdn);
3392         if (length $leftovers) {
3393             print STDERR $leftovers, "\n" or die $!;
3394             fail "tree contains uncommitted files and --clean=check specified";
3395         }
3396     } elsif ($cleanmode eq 'none') {
3397     } else {
3398         die "$cleanmode ?";
3399     }
3400 }
3401
3402 sub cmd_clean () {
3403     badusage "clean takes no additional arguments" if @ARGV;
3404     notpushing();
3405     clean_tree();
3406     maybe_unapply_patches_again();
3407 }
3408
3409 sub build_prep () {
3410     notpushing();
3411     badusage "-p is not allowed when building" if defined $package;
3412     check_not_dirty();
3413     clean_tree();
3414     my $clogp = parsechangelog();
3415     $isuite = getfield $clogp, 'Distribution';
3416     $package = getfield $clogp, 'Source';
3417     $version = getfield $clogp, 'Version';
3418     build_maybe_quilt_fixup();
3419     if ($rmchanges) {
3420         my $pat = changespat $version;
3421         foreach my $f (glob "$buildproductsdir/$pat") {
3422             if (act_local()) {
3423                 unlink $f or fail "remove old changes file $f: $!";
3424             } else {
3425                 progress "would remove $f";
3426             }
3427         }
3428     }
3429 }
3430
3431 sub changesopts_initial () {
3432     my @opts =@changesopts[1..$#changesopts];
3433 }
3434
3435 sub changesopts_version () {
3436     if (!defined $changes_since_version) {
3437         my @vsns = archive_query('archive_query');
3438         my @quirk = access_quirk();
3439         if ($quirk[0] eq 'backports') {
3440             local $isuite = $quirk[2];
3441             local $csuite;
3442             canonicalise_suite();
3443             push @vsns, archive_query('archive_query');
3444         }
3445         if (@vsns) {
3446             @vsns = map { $_->[0] } @vsns;
3447             @vsns = sort { -version_compare($a, $b) } @vsns;
3448             $changes_since_version = $vsns[0];
3449             progress "changelog will contain changes since $vsns[0]";
3450         } else {
3451             $changes_since_version = '_';
3452             progress "package seems new, not specifying -v<version>";
3453         }
3454     }
3455     if ($changes_since_version ne '_') {
3456         return ("-v$changes_since_version");
3457     } else {
3458         return ();
3459     }
3460 }
3461
3462 sub changesopts () {
3463     return (changesopts_initial(), changesopts_version());
3464 }
3465
3466 sub massage_dbp_args ($;$) {
3467     my ($cmd,$xargs) = @_;
3468     # We need to:
3469     #
3470     #  - if we're going to split the source build out so we can
3471     #    do strange things to it, massage the arguments to dpkg-buildpackage
3472     #    so that the main build doessn't build source (or add an argument
3473     #    to stop it building source by default).
3474     #
3475     #  - add -nc to stop dpkg-source cleaning the source tree,
3476     #    unless we're not doing a split build and want dpkg-source
3477     #    as cleanmode, in which case we can do nothing
3478     #
3479     # return values:
3480     #    0 - source will NOT need to be built separately by caller
3481     #   +1 - source will need to be built separately by caller
3482     #   +2 - source will need to be built separately by caller AND
3483     #        dpkg-buildpackage should not in fact be run at all!
3484     debugcmd '#massaging#', @$cmd if $debuglevel>1;
3485 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
3486     if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
3487         $clean_using_builder = 1;
3488         return 0;
3489     }
3490     # -nc has the side effect of specifying -b if nothing else specified
3491     # and some combinations of -S, -b, et al, are errors, rather than
3492     # later simply overriding earlie.  So we need to:
3493     #  - search the command line for these options
3494     #  - pick the last one
3495     #  - perhaps add our own as a default
3496     #  - perhaps adjust it to the corresponding non-source-building version
3497     my $dmode = '-F';
3498     foreach my $l ($cmd, $xargs) {
3499         next unless $l;
3500         @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
3501     }
3502     push @$cmd, '-nc';
3503 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
3504     my $r = 0;
3505     if ($need_split_build_invocation) {
3506         printdebug "massage split $dmode.\n";
3507         $r = $dmode =~ m/[S]/     ? +2 :
3508              $dmode =~ y/gGF/ABb/ ? +1 :
3509              $dmode =~ m/[ABb]/   ?  0 :
3510              die "$dmode ?";
3511     }
3512     printdebug "massage done $r $dmode.\n";
3513     push @$cmd, $dmode;
3514 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
3515     return $r;
3516 }
3517
3518 sub cmd_build {
3519     my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
3520     my $wantsrc = massage_dbp_args \@dbp;
3521     if ($wantsrc > 0) {
3522         build_source();
3523     } else {
3524         build_prep();
3525     }
3526     if ($wantsrc < 2) {
3527         push @dbp, changesopts_version();
3528         maybe_apply_patches_dirtily();
3529         runcmd_ordryrun_local @dbp;
3530     }
3531     maybe_unapply_patches_again();
3532     printdone "build successful\n";
3533 }
3534
3535 sub cmd_gbp_build {
3536     my @dbp = @dpkgbuildpackage;
3537
3538     my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
3539
3540     my @cmd;
3541     if (length executable_on_path('git-buildpackage')) {
3542         @cmd = qw(git-buildpackage);
3543     } else {
3544         @cmd = qw(gbp buildpackage);
3545     }
3546     push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
3547
3548     if ($wantsrc > 0) {
3549         build_source();
3550     } else {
3551         if (!$clean_using_builder) {
3552             push @cmd, '--git-cleaner=true';
3553         }
3554         build_prep();
3555     }
3556     if ($wantsrc < 2) {
3557         unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
3558             canonicalise_suite();
3559             push @cmd, "--git-debian-branch=".lbranch();
3560         }
3561         push @cmd, changesopts();
3562         maybe_apply_patches_dirtily();
3563         runcmd_ordryrun_local @cmd, @ARGV;
3564     }
3565     maybe_unapply_patches_again();
3566     printdone "build successful\n";
3567 }
3568 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
3569
3570 sub build_source {
3571     my $our_cleanmode = $cleanmode;
3572     if ($need_split_build_invocation) {
3573         # Pretend that clean is being done some other way.  This
3574         # forces us not to try to use dpkg-buildpackage to clean and
3575         # build source all in one go; and instead we run dpkg-source
3576         # (and build_prep() will do the clean since $clean_using_builder
3577         # is false).
3578         $our_cleanmode = 'ELSEWHERE';
3579     }
3580     if ($our_cleanmode =~ m/^dpkg-source/) {
3581         # dpkg-source invocation (below) will clean, so build_prep shouldn't
3582         $clean_using_builder = 1;
3583     }
3584     build_prep();
3585     $sourcechanges = changespat $version,'source';
3586     if (act_local()) {
3587         unlink "../$sourcechanges" or $!==ENOENT
3588             or fail "remove $sourcechanges: $!";
3589     }
3590     $dscfn = dscfn($version);
3591     if ($our_cleanmode eq 'dpkg-source') {
3592         maybe_apply_patches_dirtily();
3593         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
3594             changesopts();
3595     } elsif ($our_cleanmode eq 'dpkg-source-d') {
3596         maybe_apply_patches_dirtily();
3597         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
3598             changesopts();
3599     } else {
3600         my @cmd = (@dpkgsource, qw(-b --));
3601         if ($split_brain) {
3602             changedir $ud;
3603             runcmd_ordryrun_local @cmd, "work";
3604             my @udfiles = <${package}_*>;
3605             changedir "../../..";
3606             foreach my $f (@udfiles) {
3607                 printdebug "source copy, found $f\n";
3608                 next unless
3609                     $f eq $dscfn or
3610                     ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
3611                      $f eq srcfn($version, $&));
3612                 printdebug "source copy, found $f - renaming\n";
3613                 rename "$ud/$f", "../$f" or $!==ENOENT
3614                     or fail "put in place new source file ($f): $!";
3615             }
3616         } else {
3617             my $pwd = must_getcwd();
3618             my $leafdir = basename $pwd;
3619             changedir "..";
3620             runcmd_ordryrun_local @cmd, $leafdir;
3621             changedir $pwd;
3622         }
3623         runcmd_ordryrun_local qw(sh -ec),
3624             'exec >$1; shift; exec "$@"','x',
3625             "../$sourcechanges",
3626             @dpkggenchanges, qw(-S), changesopts();
3627     }
3628 }
3629
3630 sub cmd_build_source {
3631     badusage "build-source takes no additional arguments" if @ARGV;
3632     build_source();
3633     maybe_unapply_patches_again();
3634     printdone "source built, results in $dscfn and $sourcechanges";
3635 }
3636
3637 sub cmd_sbuild {
3638     build_source();
3639     my $pat = changespat $version;
3640     if (!$rmchanges) {
3641         my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
3642         @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
3643         fail "changes files other than source matching $pat".
3644             " already present (@unwanted);".
3645             " building would result in ambiguity about the intended results"
3646             if @unwanted;
3647     }
3648     changedir "..";
3649     if (act_local()) {
3650         stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
3651         stat_exists $sourcechanges
3652             or fail "$sourcechanges (in parent directory): $!";
3653     }
3654     runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
3655     my @changesfiles = glob $pat;
3656     @changesfiles = sort {
3657         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
3658             or $a cmp $b
3659     } @changesfiles;
3660     fail "wrong number of different changes files (@changesfiles)"
3661         unless @changesfiles==2;
3662     my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
3663     foreach my $l (split /\n/, getfield $binchanges, 'Files') {
3664         fail "$l found in binaries changes file $binchanges"
3665             if $l =~ m/\.dsc$/;
3666     }
3667     runcmd_ordryrun_local @mergechanges, @changesfiles;
3668     my $multichanges = changespat $version,'multi';
3669     if (act_local()) {
3670         stat_exists $multichanges or fail "$multichanges: $!";
3671         foreach my $cf (glob $pat) {
3672             next if $cf eq $multichanges;
3673             rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
3674         }
3675     }
3676     maybe_unapply_patches_again();
3677     printdone "build successful, results in $multichanges\n" or die $!;
3678 }    
3679
3680 sub cmd_quilt_fixup {
3681     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
3682     my $clogp = parsechangelog();
3683     $version = getfield $clogp, 'Version';
3684     $package = getfield $clogp, 'Source';
3685     check_not_dirty();
3686     clean_tree();
3687     build_maybe_quilt_fixup();
3688 }
3689
3690 sub cmd_archive_api_query {
3691     badusage "need only 1 subpath argument" unless @ARGV==1;
3692     my ($subpath) = @ARGV;
3693     my @cmd = archive_api_query_cmd($subpath);
3694     debugcmd ">",@cmd;
3695     exec @cmd or fail "exec curl: $!\n";
3696 }
3697
3698 sub cmd_clone_dgit_repos_server {
3699     badusage "need destination argument" unless @ARGV==1;
3700     my ($destdir) = @ARGV;
3701     $package = '_dgit-repos-server';
3702     my @cmd = (@git, qw(clone), access_giturl(), $destdir);
3703     debugcmd ">",@cmd;
3704     exec @cmd or fail "exec git clone: $!\n";
3705 }
3706
3707 sub cmd_setup_mergechangelogs {
3708     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3709     setup_mergechangelogs(1);
3710 }
3711
3712 sub cmd_setup_useremail {
3713     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3714     setup_useremail(1);
3715 }
3716
3717 sub cmd_setup_new_tree {
3718     badusage "no arguments allowed to dgit setup-tree" if @ARGV;
3719     setup_new_tree();
3720 }
3721
3722 #---------- argument parsing and main program ----------
3723
3724 sub cmd_version {
3725     print "dgit version $our_version\n" or die $!;
3726     exit 0;
3727 }
3728
3729 our (%valopts_long, %valopts_short);
3730 our @rvalopts;
3731
3732 sub defvalopt ($$$$) {
3733     my ($long,$short,$val_re,$how) = @_;
3734     my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
3735     $valopts_long{$long} = $oi;
3736     $valopts_short{$short} = $oi;
3737     # $how subref should:
3738     #   do whatever assignemnt or thing it likes with $_[0]
3739     #   if the option should not be passed on to remote, @rvalopts=()
3740     # or $how can be a scalar ref, meaning simply assign the value
3741 }
3742
3743 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
3744 defvalopt '--distro',        '-d', '.+',      \$idistro;
3745 defvalopt '',                '-k', '.+',      \$keyid;
3746 defvalopt '--existing-package','', '.*',      \$existing_package;
3747 defvalopt '--build-products-dir','','.*',     \$buildproductsdir;
3748 defvalopt '--clean',       '', $cleanmode_re, \$cleanmode;
3749 defvalopt '--quilt',     '', $quilt_modes_re, \$quilt_mode;
3750
3751 defvalopt '', '-c', '.*=.*', sub { push @git, '-c', @_; };
3752
3753 defvalopt '', '-C', '.+', sub {
3754     ($changesfile) = (@_);
3755     if ($changesfile =~ s#^(.*)/##) {
3756         $buildproductsdir = $1;
3757     }
3758 };
3759
3760 defvalopt '--initiator-tempdir','','.*', sub {
3761     ($initiator_tempdir) = (@_);
3762     $initiator_tempdir =~ m#^/# or
3763         badusage "--initiator-tempdir must be used specify an".
3764         " absolute, not relative, directory."
3765 };
3766
3767 sub parseopts () {
3768     my $om;
3769
3770     if (defined $ENV{'DGIT_SSH'}) {
3771         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
3772     } elsif (defined $ENV{'GIT_SSH'}) {
3773         @ssh = ($ENV{'GIT_SSH'});
3774     }
3775
3776     my $oi;
3777     my $val;
3778     my $valopt = sub {
3779         my ($what) = @_;
3780         @rvalopts = ($_);
3781         if (!defined $val) {
3782             badusage "$what needs a value" unless @ARGV;
3783             $val = shift @ARGV;
3784             push @rvalopts, $val;
3785         }
3786         badusage "bad value \`$val' for $what" unless
3787             $val =~ m/^$oi->{Re}$(?!\n)/s;
3788         my $how = $oi->{How};
3789         if (ref($how) eq 'SCALAR') {
3790             $$how = $val;
3791         } else {
3792             $how->($val);
3793         }
3794         push @ropts, @rvalopts;
3795     };
3796
3797     while (@ARGV) {
3798         last unless $ARGV[0] =~ m/^-/;
3799         $_ = shift @ARGV;
3800         last if m/^--?$/;
3801         if (m/^--/) {
3802             if (m/^--dry-run$/) {
3803                 push @ropts, $_;
3804                 $dryrun_level=2;
3805             } elsif (m/^--damp-run$/) {
3806                 push @ropts, $_;
3807                 $dryrun_level=1;
3808             } elsif (m/^--no-sign$/) {
3809                 push @ropts, $_;
3810                 $sign=0;
3811             } elsif (m/^--help$/) {
3812                 cmd_help();
3813             } elsif (m/^--version$/) {
3814                 cmd_version();
3815             } elsif (m/^--new$/) {
3816                 push @ropts, $_;
3817                 $new_package=1;
3818             } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
3819                      ($om = $opts_opt_map{$1}) &&
3820                      length $om->[0]) {
3821                 push @ropts, $_;
3822                 $om->[0] = $2;
3823             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
3824                      !$opts_opt_cmdonly{$1} &&
3825                      ($om = $opts_opt_map{$1})) {
3826                 push @ropts, $_;
3827                 push @$om, $2;
3828             } elsif (m/^--ignore-dirty$/s) {
3829                 push @ropts, $_;
3830                 $ignoredirty = 1;
3831             } elsif (m/^--no-quilt-fixup$/s) {
3832                 push @ropts, $_;
3833                 $quilt_mode = 'nocheck';
3834             } elsif (m/^--no-rm-on-error$/s) {
3835                 push @ropts, $_;
3836                 $rmonerror = 0;
3837             } elsif (m/^--(no-)?rm-old-changes$/s) {
3838                 push @ropts, $_;
3839                 $rmchanges = !$1;
3840             } elsif (m/^--deliberately-($deliberately_re)$/s) {
3841                 push @ropts, $_;
3842                 push @deliberatelies, $&;
3843             } elsif (m/^--dgit-tag-format=(old|new)$/s) {
3844                 # undocumented, for testing
3845                 push @ropts, $_;
3846                 $tagformat = [ $1, 'command line', 1 ];
3847                 # 1 menas overrides distro configuration
3848             } elsif (m/^--always-split-source-build$/s) {
3849                 # undocumented, for testing
3850                 push @ropts, $_;
3851                 $need_split_build_invocation = 1;
3852             } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
3853                 $val = $2 ? $' : undef; #';
3854                 $valopt->($oi->{Long});
3855             } else {
3856                 badusage "unknown long option \`$_'";
3857             }
3858         } else {
3859             while (m/^-./s) {
3860                 if (s/^-n/-/) {
3861                     push @ropts, $&;
3862                     $dryrun_level=2;
3863                 } elsif (s/^-L/-/) {
3864                     push @ropts, $&;
3865                     $dryrun_level=1;
3866                 } elsif (s/^-h/-/) {
3867                     cmd_help();
3868                 } elsif (s/^-D/-/) {
3869                     push @ropts, $&;
3870                     $debuglevel++;
3871                     enabledebug();
3872                 } elsif (s/^-N/-/) {
3873                     push @ropts, $&;
3874                     $new_package=1;
3875                 } elsif (m/^-m/) {
3876                     push @ropts, $&;
3877                     push @changesopts, $_;
3878                     $_ = '';
3879                 } elsif (s/^-wn$//s) {
3880                     push @ropts, $&;
3881                     $cleanmode = 'none';
3882                 } elsif (s/^-wg$//s) {
3883                     push @ropts, $&;
3884                     $cleanmode = 'git';
3885                 } elsif (s/^-wgf$//s) {
3886                     push @ropts, $&;
3887                     $cleanmode = 'git-ff';
3888                 } elsif (s/^-wd$//s) {
3889                     push @ropts, $&;
3890                     $cleanmode = 'dpkg-source';
3891                 } elsif (s/^-wdd$//s) {
3892                     push @ropts, $&;
3893                     $cleanmode = 'dpkg-source-d';
3894                 } elsif (s/^-wc$//s) {
3895                     push @ropts, $&;
3896                     $cleanmode = 'check';
3897                 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
3898                     $val = $'; #';
3899                     $val = undef unless length $val;
3900                     $valopt->($oi->{Short});
3901                     $_ = '';
3902                 } else {
3903                     badusage "unknown short option \`$_'";
3904                 }
3905             }
3906         }
3907     }
3908 }
3909
3910 sub finalise_opts_opts () {
3911     foreach my $k (keys %opts_opt_map) {
3912         my $om = $opts_opt_map{$k};
3913
3914         my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
3915         if (defined $v) {
3916             badcfg "cannot set command for $k"
3917                 unless length $om->[0];
3918             $om->[0] = $v;
3919         }
3920
3921         foreach my $c (access_cfg_cfgs("opts-$k")) {
3922             my $vl = $gitcfg{$c};
3923             printdebug "CL $c ",
3924                 ($vl ? join " ", map { shellquote } @$vl : ""),
3925                 "\n" if $debuglevel >= 4;
3926             next unless $vl;
3927             badcfg "cannot configure options for $k"
3928                 if $opts_opt_cmdonly{$k};
3929             my $insertpos = $opts_cfg_insertpos{$k};
3930             @$om = ( @$om[0..$insertpos-1],
3931                      @$vl,
3932                      @$om[$insertpos..$#$om] );
3933         }
3934     }
3935 }
3936
3937 if ($ENV{$fakeeditorenv}) {
3938     git_slurp_config();
3939     quilt_fixup_editor();
3940 }
3941
3942 parseopts();
3943 git_slurp_config();
3944
3945 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
3946 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
3947     if $dryrun_level == 1;
3948 if (!@ARGV) {
3949     print STDERR $helpmsg or die $!;
3950     exit 8;
3951 }
3952 my $cmd = shift @ARGV;
3953 $cmd =~ y/-/_/;
3954
3955 if (!defined $rmchanges) {
3956     local $access_forpush;
3957     $rmchanges = access_cfg_bool(0, 'rm-old-changes');
3958 }
3959
3960 if (!defined $quilt_mode) {
3961     local $access_forpush;
3962     $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
3963         // access_cfg('quilt-mode', 'RETURN-UNDEF')
3964         // 'linear';
3965     $quilt_mode =~ m/^($quilt_modes_re)$/ 
3966         or badcfg "unknown quilt-mode \`$quilt_mode'";
3967     $quilt_mode = $1;
3968 }
3969
3970 $need_split_build_invocation ||= quiltmode_splitbrain();
3971
3972 if (!defined $cleanmode) {
3973     local $access_forpush;
3974     $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
3975     $cleanmode //= 'dpkg-source';
3976
3977     badcfg "unknown clean-mode \`$cleanmode'" unless
3978         $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
3979 }
3980
3981 my $fn = ${*::}{"cmd_$cmd"};
3982 $fn or badusage "unknown operation $cmd";
3983 $fn->();