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