chiark / gitweb /
dgit: Introduce "deliberatelies"
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013 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 IO::Handle;
23 use Data::Dumper;
24 use LWP::UserAgent;
25 use Dpkg::Control::Hash;
26 use File::Path;
27 use File::Temp qw(tempdir);
28 use File::Basename;
29 use Dpkg::Version;
30 use POSIX;
31 use IPC::Open2;
32 use Digest::SHA;
33 use Digest::MD5;
34 use Config;
35
36 use Debian::Dgit;
37
38 our $our_version = 'UNRELEASED'; ###substituted###
39
40 our $rpushprotovsn = 2;
41
42 our $isuite = 'unstable';
43 our $idistro;
44 our $package;
45 our @ropts;
46
47 our $sign = 1;
48 our $dryrun_level = 0;
49 our $changesfile;
50 our $buildproductsdir = '..';
51 our $new_package = 0;
52 our $ignoredirty = 0;
53 our $rmonerror = 1;
54 our @deliberatelies;
55 our $existing_package = 'dpkg';
56 our $cleanmode = 'dpkg-source';
57 our $changes_since_version;
58 our $quilt_mode;
59 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
60 our $we_are_responder;
61 our $initiator_tempdir;
62
63 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
64
65 our $suite_re = '[-+.0-9a-z]+';
66
67 our (@git) = qw(git);
68 our (@dget) = qw(dget);
69 our (@curl) = qw(curl -f);
70 our (@dput) = qw(dput);
71 our (@debsign) = qw(debsign);
72 our (@gpg) = qw(gpg);
73 our (@sbuild) = qw(sbuild -A);
74 our (@ssh) = 'ssh';
75 our (@dgit) = qw(dgit);
76 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
77 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
78 our (@dpkggenchanges) = qw(dpkg-genchanges);
79 our (@mergechanges) = qw(mergechanges -f);
80 our (@changesopts) = ('');
81
82 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
83                      'curl' => \@curl,
84                      'dput' => \@dput,
85                      'debsign' => \@debsign,
86                      'gpg' => \@gpg,
87                      'sbuild' => \@sbuild,
88                      'ssh' => \@ssh,
89                      'dgit' => \@dgit,
90                      'dpkg-source' => \@dpkgsource,
91                      'dpkg-buildpackage' => \@dpkgbuildpackage,
92                      'dpkg-genchanges' => \@dpkggenchanges,
93                      'ch' => \@changesopts,
94                      'mergechanges' => \@mergechanges);
95
96 our %opts_opt_cmdonly = ('gpg' => 1);
97
98 our $keyid;
99
100 our $debug = 0;
101 open DEBUG, ">/dev/null" or die $!;
102
103 autoflush STDOUT 1;
104
105 our $remotename = 'dgit';
106 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
107 our $branchprefix = 'dgit';
108 our $csuite;
109 our $instead_distro;
110
111 sub lbranch () { return "$branchprefix/$csuite"; }
112 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
113 sub lref () { return "refs/heads/".lbranch(); }
114 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
115 sub rrref () { return "refs/$branchprefix/$csuite"; }
116
117 sub stripepoch ($) {
118     my ($vsn) = @_;
119     $vsn =~ s/^\d+\://;
120     return $vsn;
121 }
122
123 sub srcfn ($$) {
124     my ($vsn,$sfx) = @_;
125     return "${package}_".(stripepoch $vsn).$sfx
126 }
127
128 sub dscfn ($) {
129     my ($vsn) = @_;
130     return srcfn($vsn,".dsc");
131 }
132
133 our $us = 'dgit';
134 our $debugprefix = '';
135
136 our @end;
137 END { 
138     local ($?);
139     foreach my $f (@end) {
140         eval { $f->(); };
141         warn "$us: cleanup: $@" if length $@;
142     }
143 };
144
145 our @signames = split / /, $Config{sig_name};
146
147 sub waitstatusmsg () {
148     if (!$?) {
149         return "terminated, reporting successful completion";
150     } elsif (!($? & 255)) {
151         return "failed with error exit status ".WEXITSTATUS($?);
152     } elsif (WIFSIGNALED($?)) {
153         my $signum=WTERMSIG($?);
154         return "died due to fatal signal ".
155             ($signames[$signum] // "number $signum").
156             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
157     } else {
158         return "failed with unknown wait status ".$?;
159     }
160 }
161
162 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
163
164 sub fail { 
165     my $s = "@_\n";
166     my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
167     $s =~ s/^/$prefix/gm;
168     die $s;
169 }
170
171 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
172
173 sub no_such_package () {
174     print STDERR "$us: package $package does not exist in suite $isuite\n";
175     exit 4;
176 }
177
178 sub fetchspec () {
179     local $csuite = '*';
180     return  "+".rrref().":".lrref();
181 }
182
183 sub changedir ($) {
184     my ($newdir) = @_;
185     printdebug "CD $newdir\n";
186     chdir $newdir or die "chdir: $newdir: $!";
187 }
188
189 sub stat_exists ($) {
190     my ($f) = @_;
191     return 1 if stat $f;
192     return 0 if $!==&ENOENT;
193     die "stat $f: $!";
194 }
195
196 sub deliberately ($) {
197     return !!grep { $_[0] eq $_ } @deliberatelies;
198 }
199
200 #---------- remote protocol support, common ----------
201
202 # remote push initiator/responder protocol:
203 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
204 #
205 #  > file parsed-changelog
206 #  [indicates that output of dpkg-parsechangelog follows]
207 #  > data-block NBYTES
208 #  > [NBYTES bytes of data (no newline)]
209 #  [maybe some more blocks]
210 #  > data-end
211 #
212 #  > file dsc
213 #  [etc]
214 #
215 #  > file changes
216 #  [etc]
217 #
218 #  > param head HEAD
219 #
220 #  > want signed-tag
221 #  [indicates that signed tag is wanted]
222 #  < data-block NBYTES
223 #  < [NBYTES bytes of data (no newline)]
224 #  [maybe some more blocks]
225 #  < data-end
226 #  < files-end
227 #
228 #  > want signed-dsc-changes
229 #  < data-block NBYTES    [transfer of signed dsc]
230 #  [etc]
231 #  < data-block NBYTES    [transfer of signed changes]
232 #  [etc]
233 #  < files-end
234 #
235 #  > complete
236
237 our $i_child_pid;
238
239 sub i_child_report () {
240     # Sees if our child has died, and reap it if so.  Returns a string
241     # describing how it died if it failed, or undef otherwise.
242     return undef unless $i_child_pid;
243     my $got = waitpid $i_child_pid, WNOHANG;
244     return undef if $got <= 0;
245     die unless $got == $i_child_pid;
246     $i_child_pid = undef;
247     return undef unless $?;
248     return "build host child ".waitstatusmsg();
249 }
250
251 sub badproto ($$) {
252     my ($fh, $m) = @_;
253     fail "connection lost: $!" if $fh->error;
254     fail "protocol violation; $m not expected";
255 }
256
257 sub badproto_badread ($$) {
258     my ($fh, $wh) = @_;
259     fail "connection lost: $!" if $!;
260     my $report = i_child_report();
261     fail $report if defined $report;
262     badproto $fh, "eof (reading $wh)";
263 }
264
265 sub protocol_expect (&$) {
266     my ($match, $fh) = @_;
267     local $_;
268     $_ = <$fh>;
269     defined && chomp or badproto_badread $fh, "protocol message";
270     if (wantarray) {
271         my @r = &$match;
272         return @r if @r;
273     } else {
274         my $r = &$match;
275         return $r if $r;
276     }
277     badproto $fh, "\`$_'";
278 }
279
280 sub protocol_send_file ($$) {
281     my ($fh, $ourfn) = @_;
282     open PF, "<", $ourfn or die "$ourfn: $!";
283     for (;;) {
284         my $d;
285         my $got = read PF, $d, 65536;
286         die "$ourfn: $!" unless defined $got;
287         last if !$got;
288         print $fh "data-block ".length($d)."\n" or die $!;
289         print $fh $d or die $!;
290     }
291     PF->error and die "$ourfn $!";
292     print $fh "data-end\n" or die $!;
293     close PF;
294 }
295
296 sub protocol_read_bytes ($$) {
297     my ($fh, $nbytes) = @_;
298     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
299     my $d;
300     my $got = read $fh, $d, $nbytes;
301     $got==$nbytes or badproto_badread $fh, "data block";
302     return $d;
303 }
304
305 sub protocol_receive_file ($$) {
306     my ($fh, $ourfn) = @_;
307     printdebug "() $ourfn\n";
308     open PF, ">", $ourfn or die "$ourfn: $!";
309     for (;;) {
310         my ($y,$l) = protocol_expect {
311             m/^data-block (.*)$/ ? (1,$1) :
312             m/^data-end$/ ? (0,) :
313             ();
314         } $fh;
315         last unless $y;
316         my $d = protocol_read_bytes $fh, $l;
317         print PF $d or die $!;
318     }
319     close PF or die $!;
320 }
321
322 #---------- remote protocol support, responder ----------
323
324 sub responder_send_command ($) {
325     my ($command) = @_;
326     return unless $we_are_responder;
327     # called even without $we_are_responder
328     printdebug ">> $command\n";
329     print PO $command, "\n" or die $!;
330 }    
331
332 sub responder_send_file ($$) {
333     my ($keyword, $ourfn) = @_;
334     return unless $we_are_responder;
335     printdebug "]] $keyword $ourfn\n";
336     responder_send_command "file $keyword";
337     protocol_send_file \*PO, $ourfn;
338 }
339
340 sub responder_receive_files ($@) {
341     my ($keyword, @ourfns) = @_;
342     die unless $we_are_responder;
343     printdebug "[[ $keyword @ourfns\n";
344     responder_send_command "want $keyword";
345     foreach my $fn (@ourfns) {
346         protocol_receive_file \*PI, $fn;
347     }
348     printdebug "[[\$\n";
349     protocol_expect { m/^files-end$/ } \*PI;
350 }
351
352 #---------- remote protocol support, initiator ----------
353
354 sub initiator_expect (&) {
355     my ($match) = @_;
356     protocol_expect { &$match } \*RO;
357 }
358
359 #---------- end remote code ----------
360
361 sub progress {
362     if ($we_are_responder) {
363         my $m = join '', @_;
364         responder_send_command "progress ".length($m) or die $!;
365         print PO $m or die $!;
366     } else {
367         print @_, "\n";
368     }
369 }
370
371 our $ua;
372
373 sub url_get {
374     if (!$ua) {
375         $ua = LWP::UserAgent->new();
376         $ua->env_proxy;
377     }
378     my $what = $_[$#_];
379     progress "downloading $what...";
380     my $r = $ua->get(@_) or die $!;
381     return undef if $r->code == 404;
382     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
383     return $r->decoded_content(charset => 'none');
384 }
385
386 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
387
388 sub shellquote {
389     my @out;
390     local $_;
391     foreach my $a (@_) {
392         $_ = $a;
393         if (m{[^-=_./0-9a-z]}i) {
394             s{['\\]}{'\\$&'}g;
395             push @out, "'$_'";
396         } else {
397             push @out, $_;
398         }
399     }
400     return join ' ', @out;
401 }
402
403 sub printcmd {
404     my $fh = shift @_;
405     my $intro = shift @_;
406     print $fh $intro," " or die $!;
407     print $fh shellquote @_ or die $!;
408     print $fh "\n" or die $!;
409 }
410
411 sub failedcmd {
412     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
413     if ($!) {
414         fail "failed to fork/exec: $!";
415     } elsif ($?) {
416         fail "subprocess ".waitstatusmsg();
417     } else {
418         fail "subprocess produced invalid output";
419     }
420 }
421
422 sub runcmd {
423     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
424     $!=0; $?=0;
425     failedcmd @_ if system @_;
426 }
427
428 sub act_local () { return $dryrun_level <= 1; }
429 sub act_scary () { return !$dryrun_level; }
430
431 sub printdone {
432     if (!$dryrun_level) {
433         progress "dgit ok: @_";
434     } else {
435         progress "would be ok: @_ (but dry run only)";
436     }
437 }
438
439 sub cmdoutput_errok {
440     die Dumper(\@_)." ?" if grep { !defined } @_;
441     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
442     open P, "-|", @_ or die $!;
443     my $d;
444     $!=0; $?=0;
445     { local $/ = undef; $d = <P>; }
446     die $! if P->error;
447     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
448     chomp $d;
449     $d =~ m/^.*/;
450     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
451     return $d;
452 }
453
454 sub cmdoutput {
455     my $d = cmdoutput_errok @_;
456     defined $d or failedcmd @_;
457     return $d;
458 }
459
460 sub dryrun_report {
461     printcmd(\*STDERR,$debugprefix."#",@_);
462 }
463
464 sub runcmd_ordryrun {
465     if (act_scary()) {
466         runcmd @_;
467     } else {
468         dryrun_report @_;
469     }
470 }
471
472 sub runcmd_ordryrun_local {
473     if (act_local()) {
474         runcmd @_;
475     } else {
476         dryrun_report @_;
477     }
478 }
479
480 sub shell_cmd {
481     my ($first_shell, @cmd) = @_;
482     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
483 }
484
485 our $helpmsg = <<END;
486 main usages:
487   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
488   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
489   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
490   dgit [dgit-opts] push [dgit-opts] [suite]
491   dgit [dgit-opts] rpush build-host:build-dir ...
492 important dgit options:
493   -k<keyid>           sign tag and package with <keyid> instead of default
494   --dry-run -n        do not change anything, but go through the motions
495   --damp-run -L       like --dry-run but make local changes, without signing
496   --new -N            allow introducing a new package
497   --debug -D          increase debug level
498   -c<name>=<value>    set git config option (used directly by dgit too)
499 END
500
501 our $later_warning_msg = <<END;
502 Perhaps the upload is stuck in incoming.  Using the version from git.
503 END
504
505 sub badusage {
506     print STDERR "$us: @_\n", $helpmsg or die $!;
507     exit 8;
508 }
509
510 sub nextarg {
511     @ARGV or badusage "too few arguments";
512     return scalar shift @ARGV;
513 }
514
515 sub cmd_help () {
516     print $helpmsg or die $!;
517     exit 0;
518 }
519
520 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
521
522 our %defcfg = ('dgit.default.distro' => 'debian',
523                'dgit.default.username' => '',
524                'dgit.default.archive-query-default-component' => 'main',
525                'dgit.default.ssh' => 'ssh',
526                'dgit.default.archive-query' => 'madison:',
527                'dgit.default.sshpsql-dbname' => 'service=projectb',
528                'dgit-distro.debian.archive-query' => 'sshpsql:',
529                'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
530                'dgit-distro.debian.git-user-force' => 'dgit',
531                'dgit-distro.debian.git-proto' => 'git+ssh://',
532                'dgit-distro.debian.git-path' => '/dgit/debian/repos',
533  'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
534  'dgit-distro.debian.archive-query-tls-key',
535     '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
536                'dgit-distro.debian.diverts.alioth' => '/alioth',
537                'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
538                'dgit-distro.debian/alioth.git-user-force' => '',
539                'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
540                'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
541                'dgit-distro.debian.git-check' => 'ssh-cmd',
542                'dgit-distro.debian.git-create' => 'ssh-cmd',
543                'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
544                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
545                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
546  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
547  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
548                'dgit-distro.ubuntu.git-check' => 'false',
549  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
550                'dgit-distro.test-dummy.ssh' => "$td/ssh",
551                'dgit-distro.test-dummy.username' => "alice",
552                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
553                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
554                'dgit-distro.test-dummy.git-url' => "$td/git",
555                'dgit-distro.test-dummy.git-host' => "git",
556                'dgit-distro.test-dummy.git-path' => "$td/git",
557                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
558                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
559                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
560                );
561
562 sub cfg {
563     foreach my $c (@_) {
564         return undef if $c =~ /RETURN-UNDEF/;
565         my @cmd = (@git, qw(config --), $c);
566         my $v;
567         {
568             local ($debug) = $debug-1;
569             $v = cmdoutput_errok @cmd;
570         };
571         if ($?==0) {
572             return $v;
573         } elsif ($?!=256) {
574             failedcmd @cmd;
575         }
576         my $dv = $defcfg{$c};
577         return $dv if defined $dv;
578     }
579     badcfg "need value for one of: @_\n".
580         "$us: distro or suite appears not to be (properly) supported";
581 }
582
583 sub access_basedistro () {
584     if (defined $idistro) {
585         return $idistro;
586     } else {    
587         return cfg("dgit-suite.$isuite.distro",
588                    "dgit.default.distro");
589     }
590 }
591
592 sub access_quirk () {
593     # returns (quirk name, distro to use instead or undef, quirk-specific info)
594     my $basedistro = access_basedistro();
595     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
596                               'RETURN-UNDEF');
597     if (defined $backports_quirk) {
598         my $re = $backports_quirk;
599         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
600         $re =~ s/\*/.*/g;
601         $re =~ s/\%/([-0-9a-z_]+)/
602             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
603         if ($isuite =~ m/^$re$/) {
604             return ('backports',"$basedistro-backports",$1);
605         }
606     }
607     return ('none',undef);
608 }
609
610 sub access_distros () {
611     # Returns list of distros to try, in order
612     #
613     # We want to try:
614     #    0. `instead of' distro name(s) we have been pointed to
615     #    1. the access_quirk distro, if any
616     #    2a. the user's specified distro, or failing that  } basedistro
617     #    2b. the distro calculated from the suite          }
618     my @l = access_basedistro();
619
620     my (undef,$quirkdistro) = access_quirk();
621     unshift @l, $quirkdistro;
622     unshift @l, $instead_distro;
623     return grep { defined } @l;
624 }
625
626 sub access_cfg (@) {
627     my (@keys) = @_;
628     my @cfgs;
629     # The nesting of these loops determines the search order.  We put
630     # the key loop on the outside so that we search all the distros
631     # for each key, before going on to the next key.  That means that
632     # if access_cfg is called with a more specific, and then a less
633     # specific, key, an earlier distro can override the less specific
634     # without necessarily overriding any more specific keys.  (If the
635     # distro wants to override the more specific keys it can simply do
636     # so; whereas if we did the loop the other way around, it would be
637     # impossible to for an earlier distro to override a less specific
638     # key but not the more specific ones without restating the unknown
639     # values of the more specific keys.
640     my @realkeys;
641     my @rundef;
642     # We have to deal with RETURN-UNDEF specially, so that we don't
643     # terminate the search prematurely.
644     foreach (@keys) {
645         if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
646         push @realkeys, $_
647     }
648     foreach my $d (access_distros()) {
649         push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
650     }
651     push @cfgs, map { "dgit.default.$_" } @realkeys;
652     push @cfgs, @rundef;
653     my $value = cfg(@cfgs);
654     return $value;
655 }
656
657 sub string_to_ssh ($) {
658     my ($spec) = @_;
659     if ($spec =~ m/\s/) {
660         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
661     } else {
662         return ($spec);
663     }
664 }
665
666 sub access_cfg_ssh () {
667     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
668     if (!defined $gitssh) {
669         return @ssh;
670     } else {
671         return string_to_ssh $gitssh;
672     }
673 }
674
675 sub access_runeinfo ($) {
676     my ($info) = @_;
677     return ": dgit ".access_basedistro()." $info ;";
678 }
679
680 sub access_someuserhost ($) {
681     my ($some) = @_;
682     my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
683     defined($user) && length($user) or
684         $user = access_cfg("$some-user",'username');
685     my $host = access_cfg("$some-host");
686     return length($user) ? "$user\@$host" : $host;
687 }
688
689 sub access_gituserhost () {
690     return access_someuserhost('git');
691 }
692
693 sub access_giturl (;$) {
694     my ($optional) = @_;
695     my $url = access_cfg('git-url','RETURN-UNDEF');
696     if (!defined $url) {
697         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
698         return undef unless defined $proto;
699         $url =
700             $proto.
701             access_gituserhost().
702             access_cfg('git-path');
703     }
704     return "$url/$package.git";
705 }              
706
707 sub parsecontrolfh ($$;$) {
708     my ($fh, $desc, $allowsigned) = @_;
709     our $dpkgcontrolhash_noissigned;
710     my $c;
711     for (;;) {
712         my %opts = ('name' => $desc);
713         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
714         $c = Dpkg::Control::Hash->new(%opts);
715         $c->parse($fh,$desc) or die "parsing of $desc failed";
716         last if $allowsigned;
717         last if $dpkgcontrolhash_noissigned;
718         my $issigned= $c->get_option('is_pgp_signed');
719         if (!defined $issigned) {
720             $dpkgcontrolhash_noissigned= 1;
721             seek $fh, 0,0 or die "seek $desc: $!";
722         } elsif ($issigned) {
723             fail "control file $desc is (already) PGP-signed. ".
724                 " Note that dgit push needs to modify the .dsc and then".
725                 " do the signature itself";
726         } else {
727             last;
728         }
729     }
730     return $c;
731 }
732
733 sub parsecontrol {
734     my ($file, $desc) = @_;
735     my $fh = new IO::Handle;
736     open $fh, '<', $file or die "$file: $!";
737     my $c = parsecontrolfh($fh,$desc);
738     $fh->error and die $!;
739     close $fh;
740     return $c;
741 }
742
743 sub getfield ($$) {
744     my ($dctrl,$field) = @_;
745     my $v = $dctrl->{$field};
746     return $v if defined $v;
747     fail "missing field $field in ".$v->get_option('name');
748 }
749
750 sub parsechangelog {
751     my $c = Dpkg::Control::Hash->new();
752     my $p = new IO::Handle;
753     my @cmd = (qw(dpkg-parsechangelog), @_);
754     open $p, '-|', @cmd or die $!;
755     $c->parse($p);
756     $?=0; $!=0; close $p or failedcmd @cmd;
757     return $c;
758 }
759
760 sub git_get_ref ($) {
761     my ($refname) = @_;
762     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
763     if (!defined $got) {
764         $?==256 or fail "git show-ref failed (status $?)";
765         printdebug "ref $refname= [show-ref exited 1]\n";
766         return '';
767     }
768     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
769         printdebug "ref $refname=$1\n";
770         return $1;
771     } else {
772         printdebug "ref $refname= [no match]\n";
773         return '';
774     }
775 }
776
777 sub must_getcwd () {
778     my $d = getcwd();
779     defined $d or fail "getcwd failed: $!";
780     return $d;
781 }
782
783 sub archive_api_query_cmd ($) {
784     my ($subpath) = @_;
785     my @cmd = qw(curl -sS);
786     my $url = access_cfg('archive-query-url');
787     if ($url =~ m#^https://([-.0-9a-z]+)/#) {
788         my $host = $1;
789         my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
790         foreach my $key (split /\:/, $keys) {
791             $key =~ s/\%HOST\%/$host/g;
792             if (!stat $key) {
793                 fail "for $url: stat $key: $!" unless $!==ENOENT;
794                 next;
795             }
796             push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
797             last;
798         }
799     }
800     push @cmd, $url.$subpath;
801     return @cmd;
802 }
803
804 our %rmad;
805
806 sub archive_query ($) {
807     my ($method) = @_;
808     my $query = access_cfg('archive-query','RETURN-UNDEF');
809     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
810     my $proto = $1;
811     my $data = $'; #';
812     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
813 }
814
815 sub pool_dsc_subpath ($$) {
816     my ($vsn,$component) = @_; # $package is implict arg
817     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
818     return "/pool/$component/$prefix/$package/".dscfn($vsn);
819 }
820
821 sub archive_query_madison {
822     return map { [ @$_[0..1] ] } madison_get_parse(@_);
823 }
824
825 sub madison_get_parse {
826     my ($proto,$data) = @_;
827     die unless $proto eq 'madison';
828     if (!length $data) {
829         $data= access_cfg('madison-distro','RETURN-UNDEF');
830         $data //= access_basedistro();
831     }
832     $rmad{$proto,$data,$package} ||= cmdoutput
833         qw(rmadison -asource),"-s$isuite","-u$data",$package;
834     my $rmad = $rmad{$proto,$data,$package};
835
836     my @out;
837     foreach my $l (split /\n/, $rmad) {
838         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
839                   \s*( [^ \t|]+ )\s* \|
840                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
841                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
842         $1 eq $package or die "$rmad $package ?";
843         my $vsn = $2;
844         my $newsuite = $3;
845         my $component;
846         if (defined $4) {
847             $component = $4;
848         } else {
849             $component = access_cfg('archive-query-default-component');
850         }
851         $5 eq 'source' or die "$rmad ?";
852         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
853     }
854     return sort { -version_compare($a->[0],$b->[0]); } @out;
855 }
856
857 sub canonicalise_suite_madison {
858     # madison canonicalises for us
859     my @r = madison_get_parse(@_);
860     @r or fail
861         "unable to canonicalise suite using package $package".
862         " which does not appear to exist in suite $isuite;".
863         " --existing-package may help";
864     return $r[0][2];
865 }
866
867 sub sshpsql ($$$) {
868     my ($data,$runeinfo,$sql) = @_;
869     if (!length $data) {
870         $data= access_someuserhost('sshpsql').':'.
871             access_cfg('sshpsql-dbname');
872     }
873     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
874     my ($userhost,$dbname) = ($`,$'); #';
875     my @rows;
876     my @cmd = (access_cfg_ssh, $userhost,
877                access_runeinfo("ssh-psql $runeinfo").
878                " export LANG=C;".
879                " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
880     printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
881     open P, "-|", @cmd or die $!;
882     while (<P>) {
883         chomp or die;
884         printdebug("$debugprefix>|$_|\n");
885         push @rows, $_;
886     }
887     $!=0; $?=0; close P or failedcmd @cmd;
888     @rows or die;
889     my $nrows = pop @rows;
890     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
891     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
892     @rows = map { [ split /\|/, $_ ] } @rows;
893     my $ncols = scalar @{ shift @rows };
894     die if grep { scalar @$_ != $ncols } @rows;
895     return @rows;
896 }
897
898 sub sql_injection_check {
899     foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
900 }
901
902 sub archive_query_sshpsql ($$) {
903     my ($proto,$data) = @_;
904     sql_injection_check $isuite, $package;
905     my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
906         SELECT source.version, component.name, files.filename, files.sha256sum
907           FROM source
908           JOIN src_associations ON source.id = src_associations.source
909           JOIN suite ON suite.id = src_associations.suite
910           JOIN dsc_files ON dsc_files.source = source.id
911           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
912           JOIN component ON component.id = files_archive_map.component_id
913           JOIN files ON files.id = dsc_files.file
914          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
915            AND source.source='$package'
916            AND files.filename LIKE '%.dsc';
917 END
918     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
919     my $digester = Digest::SHA->new(256);
920     @rows = map {
921         my ($vsn,$component,$filename,$sha256sum) = @$_;
922         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
923     } @rows;
924     return @rows;
925 }
926
927 sub canonicalise_suite_sshpsql ($$) {
928     my ($proto,$data) = @_;
929     sql_injection_check $isuite;
930     my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
931         SELECT suite.codename
932           FROM suite where suite_name='$isuite' or codename='$isuite';
933 END
934     @rows = map { $_->[0] } @rows;
935     fail "unknown suite $isuite" unless @rows;
936     die "ambiguous $isuite: @rows ?" if @rows>1;
937     return $rows[0];
938 }
939
940 sub canonicalise_suite_dummycat ($$) {
941     my ($proto,$data) = @_;
942     my $dpath = "$data/suite.$isuite";
943     if (!open C, "<", $dpath) {
944         $!==ENOENT or die "$dpath: $!";
945         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
946         return $isuite;
947     }
948     $!=0; $_ = <C>;
949     chomp or die "$dpath: $!";
950     close C;
951     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
952     return $_;
953 }
954
955 sub archive_query_dummycat ($$) {
956     my ($proto,$data) = @_;
957     canonicalise_suite();
958     my $dpath = "$data/package.$csuite.$package";
959     if (!open C, "<", $dpath) {
960         $!==ENOENT or die "$dpath: $!";
961         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
962         return ();
963     }
964     my @rows;
965     while (<C>) {
966         next if m/^\#/;
967         next unless m/\S/;
968         die unless chomp;
969         printdebug "dummycat query $csuite $package $dpath | $_\n";
970         my @row = split /\s+/, $_;
971         @row==2 or die "$dpath: $_ ?";
972         push @rows, \@row;
973     }
974     C->error and die "$dpath: $!";
975     close C;
976     return sort { -version_compare($a->[0],$b->[0]); } @rows;
977 }
978
979 sub canonicalise_suite () {
980     return if defined $csuite;
981     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
982     $csuite = archive_query('canonicalise_suite');
983     if ($isuite ne $csuite) {
984         progress "canonical suite name for $isuite is $csuite";
985     }
986 }
987
988 sub get_archive_dsc () {
989     canonicalise_suite();
990     my @vsns = archive_query('archive_query');
991     foreach my $vinfo (@vsns) {
992         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
993         $dscurl = access_cfg('mirror').$subpath;
994         $dscdata = url_get($dscurl);
995         if (!$dscdata) {
996             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
997             next;
998         }
999         if ($digester) {
1000             $digester->reset();
1001             $digester->add($dscdata);
1002             my $got = $digester->hexdigest();
1003             $got eq $digest or
1004                 fail "$dscurl has hash $got but".
1005                     " archive told us to expect $digest";
1006         }
1007         my $dscfh = new IO::File \$dscdata, '<' or die $!;
1008         printdebug Dumper($dscdata) if $debug>1;
1009         $dsc = parsecontrolfh($dscfh,$dscurl,1);
1010         printdebug Dumper($dsc) if $debug>1;
1011         my $fmt = getfield $dsc, 'Format';
1012         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1013         $dsc_checked = !!$digester;
1014         return;
1015     }
1016     $dsc = undef;
1017 }
1018
1019 sub check_for_git ();
1020 sub check_for_git () {
1021     # returns 0 or 1
1022     my $how = access_cfg('git-check');
1023     if ($how eq 'ssh-cmd') {
1024         my @cmd =
1025             (access_cfg_ssh, access_gituserhost(),
1026              access_runeinfo("git-check $package").
1027              " set -e; cd ".access_cfg('git-path').";".
1028              " if test -d $package.git; then echo 1; else echo 0; fi");
1029         my $r= cmdoutput @cmd;
1030         if ($r =~ m/^divert (\w+)$/) {
1031             my $divert=$1;
1032             my ($usedistro,) = access_distros();
1033             $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1034             $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1035             printdebug "diverting $divert so using distro $instead_distro\n";
1036             return check_for_git();
1037         }
1038         failedcmd @cmd unless $r =~ m/^[01]$/;
1039         return $r+0;
1040     } elsif ($how eq 'true') {
1041         return 1;
1042     } elsif ($how eq 'false') {
1043         return 0;
1044     } else {
1045         badcfg "unknown git-check \`$how'";
1046     }
1047 }
1048
1049 sub create_remote_git_repo () {
1050     my $how = access_cfg('git-create');
1051     if ($how eq 'ssh-cmd') {
1052         runcmd_ordryrun
1053             (access_cfg_ssh, access_gituserhost(),
1054              access_runeinfo("git-create $package").
1055              "set -e; cd ".access_cfg('git-path').";".
1056              " cp -a _template $package.git");
1057     } elsif ($how eq 'true') {
1058         # nothing to do
1059     } else {
1060         badcfg "unknown git-create \`$how'";
1061     }
1062 }
1063
1064 our ($dsc_hash,$lastpush_hash);
1065
1066 our $ud = '.git/dgit/unpack';
1067
1068 sub prep_ud () {
1069     rmtree($ud);
1070     mkpath '.git/dgit';
1071     mkdir $ud or die $!;
1072 }
1073
1074 sub mktree_in_ud_here () {
1075     runcmd qw(git init -q);
1076     rmtree('.git/objects');
1077     symlink '../../../../objects','.git/objects' or die $!;
1078 }
1079
1080 sub git_write_tree () {
1081     my $tree = cmdoutput @git, qw(write-tree);
1082     $tree =~ m/^\w+$/ or die "$tree ?";
1083     return $tree;
1084 }
1085
1086 sub mktree_in_ud_from_only_subdir () {
1087     # changes into the subdir
1088     my (@dirs) = <*/.>;
1089     die unless @dirs==1;
1090     $dirs[0] =~ m#^([^/]+)/\.$# or die;
1091     my $dir = $1;
1092     changedir $dir;
1093     fail "source package contains .git directory" if stat_exists '.git';
1094     mktree_in_ud_here();
1095     my $format=get_source_format();
1096     if (madformat($format)) {
1097         rmtree '.pc';
1098     }
1099     runcmd @git, qw(add -Af);
1100     my $tree=git_write_tree();
1101     return ($tree,$dir);
1102 }
1103
1104 sub dsc_files_info () {
1105     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1106                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
1107                        ['Files',           'Digest::MD5', 'new()']) {
1108         my ($fname, $module, $method) = @$csumi;
1109         my $field = $dsc->{$fname};
1110         next unless defined $field;
1111         eval "use $module; 1;" or die $@;
1112         my @out;
1113         foreach (split /\n/, $field) {
1114             next unless m/\S/;
1115             m/^(\w+) (\d+) (\S+)$/ or
1116                 fail "could not parse .dsc $fname line \`$_'";
1117             my $digester = eval "$module"."->$method;" or die $@;
1118             push @out, {
1119                 Hash => $1,
1120                 Bytes => $2,
1121                 Filename => $3,
1122                 Digester => $digester,
1123             };
1124         }
1125         return @out;
1126     }
1127     fail "missing any supported Checksums-* or Files field in ".
1128         $dsc->get_option('name');
1129 }
1130
1131 sub dsc_files () {
1132     map { $_->{Filename} } dsc_files_info();
1133 }
1134
1135 sub is_orig_file ($;$) {
1136     local ($_) = $_[0];
1137     my $base = $_[1];
1138     m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1139     defined $base or return 1;
1140     return $` eq $base;
1141 }
1142
1143 sub make_commit ($) {
1144     my ($file) = @_;
1145     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1146 }
1147
1148 sub clogp_authline ($) {
1149     my ($clogp) = @_;
1150     my $author = getfield $clogp, 'Maintainer';
1151     $author =~ s#,.*##ms;
1152     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1153     my $authline = "$author $date";
1154     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1155         fail "unexpected commit author line format \`$authline'".
1156         " (was generated from changelog Maintainer field)";
1157     return $authline;
1158 }
1159
1160 sub generate_commit_from_dsc () {
1161     prep_ud();
1162     changedir $ud;
1163
1164     foreach my $fi (dsc_files_info()) {
1165         my $f = $fi->{Filename};
1166         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1167
1168         link "../../../$f", $f
1169             or $!==&ENOENT
1170             or die "$f $!";
1171
1172         complete_file_from_dsc('.', $fi);
1173
1174         if (is_orig_file($f)) {
1175             link $f, "../../../../$f"
1176                 or $!==&EEXIST
1177                 or die "$f $!";
1178         }
1179     }
1180
1181     my $dscfn = "$package.dsc";
1182
1183     open D, ">", $dscfn or die "$dscfn: $!";
1184     print D $dscdata or die "$dscfn: $!";
1185     close D or die "$dscfn: $!";
1186     my @cmd = qw(dpkg-source);
1187     push @cmd, '--no-check' if $dsc_checked;
1188     push @cmd, qw(-x --), $dscfn;
1189     runcmd @cmd;
1190
1191     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1192     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1193     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1194     my $authline = clogp_authline $clogp;
1195     my $changes = getfield $clogp, 'Changes';
1196     open C, ">../commit.tmp" or die $!;
1197     print C <<END or die $!;
1198 tree $tree
1199 author $authline
1200 committer $authline
1201
1202 $changes
1203
1204 # imported from the archive
1205 END
1206     close C or die $!;
1207     my $outputhash = make_commit qw(../commit.tmp);
1208     my $cversion = getfield $clogp, 'Version';
1209     progress "synthesised git commit from .dsc $cversion";
1210     if ($lastpush_hash) {
1211         runcmd @git, qw(reset --hard), $lastpush_hash;
1212         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1213         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1214         my $oversion = getfield $oldclogp, 'Version';
1215         my $vcmp =
1216             version_compare($oversion, $cversion);
1217         if ($vcmp < 0) {
1218             # git upload/ is earlier vsn than archive, use archive
1219             open C, ">../commit2.tmp" or die $!;
1220             print C <<END or die $!;
1221 tree $tree
1222 parent $lastpush_hash
1223 parent $outputhash
1224 author $authline
1225 committer $authline
1226
1227 Record $package ($cversion) in archive suite $csuite
1228 END
1229             $outputhash = make_commit qw(../commit2.tmp);
1230         } elsif ($vcmp > 0) {
1231             print STDERR <<END or die $!;
1232
1233 Version actually in archive:    $cversion (older)
1234 Last allegedly pushed/uploaded: $oversion (newer or same)
1235 $later_warning_msg
1236 END
1237             $outputhash = $lastpush_hash;
1238         } else {
1239             $outputhash = $lastpush_hash;
1240         }
1241     }
1242     changedir '../../../..';
1243     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1244             'DGIT_ARCHIVE', $outputhash;
1245     cmdoutput @git, qw(log -n2), $outputhash;
1246     # ... gives git a chance to complain if our commit is malformed
1247     rmtree($ud);
1248     return $outputhash;
1249 }
1250
1251 sub complete_file_from_dsc ($$) {
1252     our ($dstdir, $fi) = @_;
1253     # Ensures that we have, in $dir, the file $fi, with the correct
1254     # contents.  (Downloading it from alongside $dscurl if necessary.)
1255
1256     my $f = $fi->{Filename};
1257     my $tf = "$dstdir/$f";
1258     my $downloaded = 0;
1259
1260     if (stat_exists $tf) {
1261         progress "using existing $f";
1262     } else {
1263         my $furl = $dscurl;
1264         $furl =~ s{/[^/]+$}{};
1265         $furl .= "/$f";
1266         die "$f ?" unless $f =~ m/^${package}_/;
1267         die "$f ?" if $f =~ m#/#;
1268         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1269         next if !act_local();
1270         $downloaded = 1;
1271     }
1272
1273     open F, "<", "$tf" or die "$tf: $!";
1274     $fi->{Digester}->reset();
1275     $fi->{Digester}->addfile(*F);
1276     F->error and die $!;
1277     my $got = $fi->{Digester}->hexdigest();
1278     $got eq $fi->{Hash} or
1279         fail "file $f has hash $got but .dsc".
1280             " demands hash $fi->{Hash} ".
1281             ($downloaded ? "(got wrong file from archive!)"
1282              : "(perhaps you should delete this file?)");
1283 }
1284
1285 sub ensure_we_have_orig () {
1286     foreach my $fi (dsc_files_info()) {
1287         my $f = $fi->{Filename};
1288         next unless is_orig_file($f);
1289         complete_file_from_dsc('..', $fi);
1290     }
1291 }
1292
1293 sub rev_parse ($) {
1294     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1295 }
1296
1297 sub is_fast_fwd ($$) {
1298     my ($ancestor,$child) = @_;
1299     my @cmd = (@git, qw(merge-base), $ancestor, $child);
1300     my $mb = cmdoutput_errok @cmd;
1301     if (defined $mb) {
1302         return rev_parse($mb) eq rev_parse($ancestor);
1303     } else {
1304         $?==256 or failedcmd @cmd;
1305         return 0;
1306     }
1307 }
1308
1309 sub git_fetch_us () {
1310     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1311 }
1312
1313 sub fetch_from_archive () {
1314     # ensures that lrref() is what is actually in the archive,
1315     #  one way or another
1316     get_archive_dsc();
1317
1318     if ($dsc) {
1319         foreach my $field (@ourdscfield) {
1320             $dsc_hash = $dsc->{$field};
1321             last if defined $dsc_hash;
1322         }
1323         if (defined $dsc_hash) {
1324             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1325             $dsc_hash = $&;
1326             progress "last upload to archive specified git hash";
1327         } else {
1328             progress "last upload to archive has NO git hash";
1329         }
1330     } else {
1331         progress "no version available from the archive";
1332     }
1333
1334     $lastpush_hash = git_get_ref(lrref());
1335     printdebug "previous reference hash=$lastpush_hash\n";
1336     my $hash;
1337     if (defined $dsc_hash) {
1338         fail "missing remote git history even though dsc has hash -".
1339             " could not find ref ".lrref().
1340             " (should have been fetched from ".access_giturl()."#".rrref().")"
1341             unless $lastpush_hash;
1342         $hash = $dsc_hash;
1343         ensure_we_have_orig();
1344         if ($dsc_hash eq $lastpush_hash) {
1345         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1346             print STDERR <<END or die $!;
1347
1348 Git commit in archive is behind the last version allegedly pushed/uploaded.
1349 Commit referred to by archive:  $dsc_hash
1350 Last allegedly pushed/uploaded: $lastpush_hash
1351 $later_warning_msg
1352 END
1353             $hash = $lastpush_hash;
1354         } else {
1355             fail "archive's .dsc refers to ".$dsc_hash.
1356                 " but this is an ancestor of ".$lastpush_hash;
1357         }
1358     } elsif ($dsc) {
1359         $hash = generate_commit_from_dsc();
1360     } elsif ($lastpush_hash) {
1361         # only in git, not in the archive yet
1362         $hash = $lastpush_hash;
1363         print STDERR <<END or die $!;
1364
1365 Package not found in the archive, but has allegedly been pushed using dgit.
1366 $later_warning_msg
1367 END
1368     } else {
1369         printdebug "nothing found!\n";
1370         if (defined $skew_warning_vsn) {
1371             print STDERR <<END or die $!;
1372
1373 Warning: relevant archive skew detected.
1374 Archive allegedly contains $skew_warning_vsn
1375 But we were not able to obtain any version from the archive or git.
1376
1377 END
1378         }
1379         return 0;
1380     }
1381     printdebug "current hash=$hash\n";
1382     if ($lastpush_hash) {
1383         fail "not fast forward on last upload branch!".
1384             " (archive's version left in DGIT_ARCHIVE)"
1385             unless is_fast_fwd($lastpush_hash, $hash);
1386     }
1387     if (defined $skew_warning_vsn) {
1388         mkpath '.git/dgit';
1389         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1390         my $clogf = ".git/dgit/changelog.tmp";
1391         runcmd shell_cmd "exec >$clogf",
1392             @git, qw(cat-file blob), "$hash:debian/changelog";
1393         my $gotclogp = parsechangelog("-l$clogf");
1394         my $got_vsn = getfield $gotclogp, 'Version';
1395         printdebug "SKEW CHECK GOT $got_vsn\n";
1396         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1397             print STDERR <<END or die $!;
1398
1399 Warning: archive skew detected.  Using the available version:
1400 Archive allegedly contains    $skew_warning_vsn
1401 We were able to obtain only   $got_vsn
1402
1403 END
1404         }
1405     }
1406     if ($lastpush_hash ne $hash) {
1407         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1408         if (act_local()) {
1409             cmdoutput @upd_cmd;
1410         } else {
1411             dryrun_report @upd_cmd;
1412         }
1413     }
1414     return 1;
1415 }
1416
1417 sub clone ($) {
1418     my ($dstdir) = @_;
1419     canonicalise_suite();
1420     badusage "dry run makes no sense with clone" unless act_local();
1421     my $hasgit = check_for_git();
1422     mkdir $dstdir or die "$dstdir $!";
1423     changedir $dstdir;
1424     runcmd @git, qw(init -q);
1425     my $giturl = access_giturl(1);
1426     if (defined $giturl) {
1427         runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1428         open H, "> .git/HEAD" or die $!;
1429         print H "ref: ".lref()."\n" or die $!;
1430         close H or die $!;
1431         runcmd @git, qw(remote add), 'origin', $giturl;
1432     }
1433     if ($hasgit) {
1434         progress "fetching existing git history";
1435         git_fetch_us();
1436         runcmd_ordryrun_local @git, qw(fetch origin);
1437     } else {
1438         progress "starting new git history";
1439     }
1440     fetch_from_archive() or no_such_package;
1441     my $vcsgiturl = $dsc->{'Vcs-Git'};
1442     $vcsgiturl =~ s/\s+-b\s+\S+//g;
1443     if (length $vcsgiturl) {
1444         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1445     }
1446     runcmd @git, qw(reset --hard), lrref();
1447     printdone "ready for work in $dstdir";
1448 }
1449
1450 sub fetch () {
1451     if (check_for_git()) {
1452         git_fetch_us();
1453     }
1454     fetch_from_archive() or no_such_package();
1455     printdone "fetched into ".lrref();
1456 }
1457
1458 sub pull () {
1459     fetch();
1460     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1461         lrref();
1462     printdone "fetched to ".lrref()." and merged into HEAD";
1463 }
1464
1465 sub check_not_dirty () {
1466     return if $ignoredirty;
1467     my @cmd = (@git, qw(diff --quiet HEAD));
1468     printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1469     $!=0; $?=0; system @cmd;
1470     return if !$! && !$?;
1471     if (!$! && $?==256) {
1472         fail "working tree is dirty (does not match HEAD)";
1473     } else {
1474         failedcmd @cmd;
1475     }
1476 }
1477
1478 sub commit_admin ($) {
1479     my ($m) = @_;
1480     progress "$m";
1481     runcmd_ordryrun_local @git, qw(commit -m), $m;
1482 }
1483
1484 sub commit_quilty_patch () {
1485     my $output = cmdoutput @git, qw(status --porcelain);
1486     my %adds;
1487     foreach my $l (split /\n/, $output) {
1488         next unless $l =~ m/\S/;
1489         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1490             $adds{$1}++;
1491         }
1492     }
1493     delete $adds{'.pc'}; # if there wasn't one before, don't add it
1494     if (!%adds) {
1495         progress "nothing quilty to commit, ok.";
1496         return;
1497     }
1498     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1499     commit_admin "Commit Debian 3.0 (quilt) metadata";
1500 }
1501
1502 sub get_source_format () {
1503     if (!open F, "debian/source/format") {
1504         die $! unless $!==&ENOENT;
1505         return '';
1506     }
1507     $_ = <F>;
1508     F->error and die $!;
1509     chomp;
1510     return $_;
1511 }
1512
1513 sub madformat ($) {
1514     my ($format) = @_;
1515     return 0 unless $format eq '3.0 (quilt)';
1516     if ($quilt_mode eq 'nocheck') {
1517         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1518         return 0;
1519     }
1520     progress "Format \`$format', checking/updating patch stack";
1521     return 1;
1522 }
1523
1524 sub push_parse_changelog ($) {
1525     my ($clogpfn) = @_;
1526
1527     my $clogp = Dpkg::Control::Hash->new();
1528     $clogp->load($clogpfn) or die;
1529
1530     $package = getfield $clogp, 'Source';
1531     my $cversion = getfield $clogp, 'Version';
1532     my $tag = debiantag($cversion);
1533     runcmd @git, qw(check-ref-format), $tag;
1534
1535     my $dscfn = dscfn($cversion);
1536
1537     return ($clogp, $cversion, $tag, $dscfn);
1538 }
1539
1540 sub push_parse_dsc ($$$) {
1541     my ($dscfn,$dscfnwhat, $cversion) = @_;
1542     $dsc = parsecontrol($dscfn,$dscfnwhat);
1543     my $dversion = getfield $dsc, 'Version';
1544     my $dscpackage = getfield $dsc, 'Source';
1545     ($dscpackage eq $package && $dversion eq $cversion) or
1546         fail "$dscfn is for $dscpackage $dversion".
1547             " but debian/changelog is for $package $cversion";
1548 }
1549
1550 sub push_mktag ($$$$$$$) {
1551     my ($head,$clogp,$tag,
1552         $dscfn,
1553         $changesfile,$changesfilewhat,
1554         $tfn) = @_;
1555
1556     $dsc->{$ourdscfield[0]} = $head;
1557     $dsc->save("$dscfn.tmp") or die $!;
1558
1559     my $changes = parsecontrol($changesfile,$changesfilewhat);
1560     foreach my $field (qw(Source Distribution Version)) {
1561         $changes->{$field} eq $clogp->{$field} or
1562             fail "changes field $field \`$changes->{$field}'".
1563                 " does not match changelog \`$clogp->{$field}'";
1564     }
1565
1566     my $cversion = getfield $clogp, 'Version';
1567     my $clogsuite = getfield $clogp, 'Distribution';
1568
1569     # We make the git tag by hand because (a) that makes it easier
1570     # to control the "tagger" (b) we can do remote signing
1571     my $authline = clogp_authline $clogp;
1572     my $delibs = join(" ", "",@deliberatelies);
1573     open TO, '>', $tfn->('.tmp') or die $!;
1574     print TO <<END or die $!;
1575 object $head
1576 type commit
1577 tag $tag
1578 tagger $authline
1579
1580 $package release $cversion for $clogsuite ($csuite) [dgit]
1581 [dgit distro=$distro$delibs]
1582 END
1583     close TO or die $!;
1584
1585     my $tagobjfn = $tfn->('.tmp');
1586     if ($sign) {
1587         if (!defined $keyid) {
1588             $keyid = access_cfg('keyid','RETURN-UNDEF');
1589         }
1590         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1591         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1592         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1593         push @sign_cmd, $tfn->('.tmp');
1594         runcmd_ordryrun @sign_cmd;
1595         if (act_scary()) {
1596             $tagobjfn = $tfn->('.signed.tmp');
1597             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1598                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1599         }
1600     }
1601
1602     return ($tagobjfn);
1603 }
1604
1605 sub sign_changes ($) {
1606     my ($changesfile) = @_;
1607     if ($sign) {
1608         my @debsign_cmd = @debsign;
1609         push @debsign_cmd, "-k$keyid" if defined $keyid;
1610         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1611         push @debsign_cmd, $changesfile;
1612         runcmd_ordryrun @debsign_cmd;
1613     }
1614 }
1615
1616 sub dopush () {
1617     printdebug "actually entering push\n";
1618     prep_ud();
1619
1620     access_giturl(); # check that success is vaguely likely
1621
1622     my $clogpfn = ".git/dgit/changelog.822.tmp";
1623     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1624
1625     responder_send_file('parsed-changelog', $clogpfn);
1626
1627     my ($clogp, $cversion, $tag, $dscfn) =
1628         push_parse_changelog("$clogpfn");
1629
1630     my $dscpath = "$buildproductsdir/$dscfn";
1631     stat_exists $dscpath or
1632         fail "looked for .dsc $dscfn, but $!;".
1633             " maybe you forgot to build";
1634
1635     responder_send_file('dsc', $dscpath);
1636
1637     push_parse_dsc($dscpath, $dscfn, $cversion);
1638
1639     my $format = getfield $dsc, 'Format';
1640     printdebug "format $format\n";
1641     if (madformat($format)) {
1642         commit_quilty_patch();
1643     }
1644     check_not_dirty();
1645     changedir $ud;
1646     progress "checking that $dscfn corresponds to HEAD";
1647     runcmd qw(dpkg-source -x --),
1648         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1649     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1650     changedir '../../../..';
1651     my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1652     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1653     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1654     $!=0; $?=0;
1655     my $r = system @diffcmd;
1656     if ($r) {
1657         if ($r==256) {
1658             fail "$dscfn specifies a different tree to your HEAD commit;".
1659                 " perhaps you forgot to build".
1660                 ($diffopt eq '--exit-code' ? "" :
1661                  " (run with -D to see full diff output)");
1662         } else {
1663             failedcmd @diffcmd;
1664         }
1665     }
1666 #fetch from alioth
1667 #do fast forward check and maybe fake merge
1668 #    if (!is_fast_fwd(mainbranch
1669 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1670 #        map { lref($_).":".rref($_) }
1671 #        (uploadbranch());
1672     my $head = rev_parse('HEAD');
1673     if (!$changesfile) {
1674         my $multi = "$buildproductsdir/".
1675             "${package}_".(stripepoch $cversion)."_multi.changes";
1676         if (stat_exists "$multi") {
1677             $changesfile = $multi;
1678         } else {
1679             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1680             my @cs = glob "$buildproductsdir/$pat";
1681             fail "failed to find unique changes file".
1682                 " (looked for $pat in $buildproductsdir, or $multi);".
1683                 " perhaps you need to use dgit -C"
1684                 unless @cs==1;
1685             ($changesfile) = @cs;
1686         }
1687     } else {
1688         $changesfile = "$buildproductsdir/$changesfile";
1689     }
1690
1691     responder_send_file('changes',$changesfile);
1692     responder_send_command("param head $head");
1693     responder_send_command("param csuite $csuite");
1694
1695     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1696     my $tagobjfn;
1697
1698     if ($we_are_responder) {
1699         $tagobjfn = $tfn->('.signed.tmp');
1700         responder_receive_files('signed-tag', $tagobjfn);
1701     } else {
1702         $tagobjfn =
1703             push_mktag($head,$clogp,$tag,
1704                        $dscpath,
1705                        $changesfile,$changesfile,
1706                        $tfn);
1707     }
1708
1709     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1710     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1711     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1712     runcmd_ordryrun @git, qw(tag -v --), $tag;
1713
1714     if (!check_for_git()) {
1715         create_remote_git_repo();
1716     }
1717     runcmd_ordryrun @git, qw(push),access_giturl(),
1718         "HEAD:".rrref(), "refs/tags/$tag";
1719     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1720
1721     if ($we_are_responder) {
1722         my $dryrunsuffix = act_local() ? "" : ".tmp";
1723         responder_receive_files('signed-dsc-changes',
1724                                 "$dscpath$dryrunsuffix",
1725                                 "$changesfile$dryrunsuffix");
1726     } else {
1727         if (act_local()) {
1728             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1729         } else {
1730             progress "[new .dsc left in $dscpath.tmp]";
1731         }
1732         sign_changes $changesfile;
1733     }
1734
1735     my $host = access_cfg('upload-host','RETURN-UNDEF');
1736     my @hostarg = defined($host) ? ($host,) : ();
1737     runcmd_ordryrun @dput, @hostarg, $changesfile;
1738     printdone "pushed and uploaded $cversion";
1739
1740     responder_send_command("complete");
1741 }
1742
1743 sub cmd_clone {
1744     parseopts();
1745     my $dstdir;
1746     badusage "-p is not allowed with clone; specify as argument instead"
1747         if defined $package;
1748     if (@ARGV==1) {
1749         ($package) = @ARGV;
1750     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1751         ($package,$isuite) = @ARGV;
1752     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1753         ($package,$dstdir) = @ARGV;
1754     } elsif (@ARGV==3) {
1755         ($package,$isuite,$dstdir) = @ARGV;
1756     } else {
1757         badusage "incorrect arguments to dgit clone";
1758     }
1759     $dstdir ||= "$package";
1760
1761     if (stat_exists $dstdir) {
1762         fail "$dstdir already exists";
1763     }
1764
1765     my $cwd_remove;
1766     if ($rmonerror && !$dryrun_level) {
1767         $cwd_remove= getcwd();
1768         unshift @end, sub { 
1769             return unless defined $cwd_remove;
1770             if (!chdir "$cwd_remove") {
1771                 return if $!==&ENOENT;
1772                 die "chdir $cwd_remove: $!";
1773             }
1774             rmtree($dstdir) or die "remove $dstdir: $!\n";
1775         };
1776     }
1777
1778     clone($dstdir);
1779     $cwd_remove = undef;
1780 }
1781
1782 sub branchsuite () {
1783     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1784     if ($branch =~ m#$lbranch_re#o) {
1785         return $1;
1786     } else {
1787         return undef;
1788     }
1789 }
1790
1791 sub fetchpullargs () {
1792     if (!defined $package) {
1793         my $sourcep = parsecontrol('debian/control','debian/control');
1794         $package = getfield $sourcep, 'Source';
1795     }
1796     if (@ARGV==0) {
1797 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1798         if (!$isuite) {
1799             my $clogp = parsechangelog();
1800             $isuite = getfield $clogp, 'Distribution';
1801         }
1802         canonicalise_suite();
1803         progress "fetching from suite $csuite";
1804     } elsif (@ARGV==1) {
1805         ($isuite) = @ARGV;
1806         canonicalise_suite();
1807     } else {
1808         badusage "incorrect arguments to dgit fetch or dgit pull";
1809     }
1810 }
1811
1812 sub cmd_fetch {
1813     parseopts();
1814     fetchpullargs();
1815     fetch();
1816 }
1817
1818 sub cmd_pull {
1819     parseopts();
1820     fetchpullargs();
1821     pull();
1822 }
1823
1824 sub cmd_push {
1825     parseopts();
1826     badusage "-p is not allowed with dgit push" if defined $package;
1827     check_not_dirty();
1828     my $clogp = parsechangelog();
1829     $package = getfield $clogp, 'Source';
1830     my $specsuite;
1831     if (@ARGV==0) {
1832     } elsif (@ARGV==1) {
1833         ($specsuite) = (@ARGV);
1834     } else {
1835         badusage "incorrect arguments to dgit push";
1836     }
1837     $isuite = getfield $clogp, 'Distribution';
1838     if ($new_package) {
1839         local ($package) = $existing_package; # this is a hack
1840         canonicalise_suite();
1841     }
1842     if (defined $specsuite && $specsuite ne $isuite) {
1843         canonicalise_suite();
1844         $csuite eq $specsuite or
1845             fail "dgit push: changelog specifies $isuite ($csuite)".
1846                 " but command line specifies $specsuite";
1847     }
1848     if (check_for_git()) {
1849         git_fetch_us();
1850     }
1851     if (fetch_from_archive()) {
1852         is_fast_fwd(lrref(), 'HEAD') or
1853             fail "dgit push: HEAD is not a descendant".
1854                 " of the archive's version.\n".
1855                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1856     } else {
1857         $new_package or
1858             fail "package appears to be new in this suite;".
1859                 " if this is intentional, use --new";
1860     }
1861     dopush();
1862 }
1863
1864 #---------- remote commands' implementation ----------
1865
1866 sub cmd_remote_push_build_host {
1867     my ($nrargs) = shift @ARGV;
1868     my (@rargs) = @ARGV[0..$nrargs-1];
1869     @ARGV = @ARGV[$nrargs..$#ARGV];
1870     die unless @rargs;
1871     my ($dir,$vsnwant) = @rargs;
1872     # vsnwant is a comma-separated list; we report which we have
1873     # chosen in our ready response (so other end can tell if they
1874     # offered several)
1875     $debugprefix = ' ';
1876     $we_are_responder = 1;
1877
1878     open PI, "<&STDIN" or die $!;
1879     open STDIN, "/dev/null" or die $!;
1880     open PO, ">&STDOUT" or die $!;
1881     autoflush PO 1;
1882     open STDOUT, ">&STDERR" or die $!;
1883     autoflush STDOUT 1;
1884
1885     $vsnwant //= 1;
1886     fail "build host has dgit rpush protocol version".
1887         " $rpushprotovsn but invocation host has $vsnwant"
1888         unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1889
1890     responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1891
1892     changedir $dir;
1893     &cmd_push;
1894 }
1895
1896 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1897 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1898 #     a good error message)
1899
1900 our $i_tmp;
1901
1902 sub i_cleanup {
1903     local ($@, $?);
1904     my $report = i_child_report();
1905     if (defined $report) {
1906         printdebug "($report)\n";
1907     } elsif ($i_child_pid) {
1908         printdebug "(killing build host child $i_child_pid)\n";
1909         kill 15, $i_child_pid;
1910     }
1911     if (defined $i_tmp && !defined $initiator_tempdir) {
1912         changedir "/";
1913         eval { rmtree $i_tmp; };
1914     }
1915 }
1916
1917 END { i_cleanup(); }
1918
1919 sub i_method {
1920     my ($base,$selector,@args) = @_;
1921     $selector =~ s/\-/_/g;
1922     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1923 }
1924
1925 sub cmd_rpush {
1926     my $host = nextarg;
1927     my $dir;
1928     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1929         $host = $1;
1930         $dir = $'; #';
1931     } else {
1932         $dir = nextarg;
1933     }
1934     $dir =~ s{^-}{./-};
1935     my @rargs = ($dir,$rpushprotovsn);
1936     my @rdgit;
1937     push @rdgit, @dgit;
1938     push @rdgit, @ropts;
1939     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1940     push @rdgit, @ARGV;
1941     my @cmd = (@ssh, $host, shellquote @rdgit);
1942     printcmd \*DEBUG,$debugprefix."+",@cmd;
1943
1944     if (defined $initiator_tempdir) {
1945         rmtree $initiator_tempdir;
1946         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1947         $i_tmp = $initiator_tempdir;
1948     } else {
1949         $i_tmp = tempdir();
1950     }
1951     $i_child_pid = open2(\*RO, \*RI, @cmd);
1952     changedir $i_tmp;
1953     initiator_expect { m/^dgit-remote-push-ready/ };
1954     for (;;) {
1955         my ($icmd,$iargs) = initiator_expect {
1956             m/^(\S+)(?: (.*))?$/;
1957             ($1,$2);
1958         };
1959         i_method "i_resp", $icmd, $iargs;
1960     }
1961 }
1962
1963 sub i_resp_progress ($) {
1964     my ($rhs) = @_;
1965     my $msg = protocol_read_bytes \*RO, $rhs;
1966     progress $msg;
1967 }
1968
1969 sub i_resp_complete {
1970     my $pid = $i_child_pid;
1971     $i_child_pid = undef; # prevents killing some other process with same pid
1972     printdebug "waiting for build host child $pid...\n";
1973     my $got = waitpid $pid, 0;
1974     die $! unless $got == $pid;
1975     die "build host child failed $?" if $?;
1976
1977     i_cleanup();
1978     printdebug "all done\n";
1979     exit 0;
1980 }
1981
1982 sub i_resp_file ($) {
1983     my ($keyword) = @_;
1984     my $localname = i_method "i_localname", $keyword;
1985     my $localpath = "$i_tmp/$localname";
1986     stat_exists $localpath and
1987         badproto \*RO, "file $keyword ($localpath) twice";
1988     protocol_receive_file \*RO, $localpath;
1989     i_method "i_file", $keyword;
1990 }
1991
1992 our %i_param;
1993
1994 sub i_resp_param ($) {
1995     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1996     $i_param{$1} = $2;
1997 }
1998
1999 our %i_wanted;
2000
2001 sub i_resp_want ($) {
2002     my ($keyword) = @_;
2003     die "$keyword ?" if $i_wanted{$keyword}++;
2004     my @localpaths = i_method "i_want", $keyword;
2005     printdebug "[[  $keyword @localpaths\n";
2006     foreach my $localpath (@localpaths) {
2007         protocol_send_file \*RI, $localpath;
2008     }
2009     print RI "files-end\n" or die $!;
2010 }
2011
2012 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2013
2014 sub i_localname_parsed_changelog {
2015     return "remote-changelog.822";
2016 }
2017 sub i_file_parsed_changelog {
2018     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2019         push_parse_changelog "$i_tmp/remote-changelog.822";
2020     die if $i_dscfn =~ m#/|^\W#;
2021 }
2022
2023 sub i_localname_dsc {
2024     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2025     return $i_dscfn;
2026 }
2027 sub i_file_dsc { }
2028
2029 sub i_localname_changes {
2030     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2031     $i_changesfn = $i_dscfn;
2032     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2033     return $i_changesfn;
2034 }
2035 sub i_file_changes { }
2036
2037 sub i_want_signed_tag {
2038     printdebug Dumper(\%i_param, $i_dscfn);
2039     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2040         && defined $i_param{'csuite'}
2041         or badproto \*RO, "premature desire for signed-tag";
2042     my $head = $i_param{'head'};
2043     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2044
2045     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2046     $csuite = $&;
2047     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2048
2049     my $tagobjfn =
2050         push_mktag $head, $i_clogp, $i_tag,
2051             $i_dscfn,
2052             $i_changesfn, 'remote changes',
2053             sub { "tag$_[0]"; };
2054
2055     return $tagobjfn;
2056 }
2057
2058 sub i_want_signed_dsc_changes {
2059     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2060     sign_changes $i_changesfn;
2061     return ($i_dscfn, $i_changesfn);
2062 }
2063
2064 #---------- building etc. ----------
2065
2066 our $version;
2067 our $sourcechanges;
2068 our $dscfn;
2069
2070 #----- `3.0 (quilt)' handling -----
2071
2072 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2073
2074 sub quiltify_dpkg_commit ($$$;$) {
2075     my ($patchname,$author,$msg, $xinfo) = @_;
2076     $xinfo //= '';
2077
2078     mkpath '.git/dgit';
2079     my $descfn = ".git/dgit/quilt-description.tmp";
2080     open O, '>', $descfn or die "$descfn: $!";
2081     $msg =~ s/\s+$//g;
2082     $msg =~ s/\n/\n /g;
2083     $msg =~ s/^\s+$/ ./mg;
2084     print O <<END or die $!;
2085 Description: $msg
2086 Author: $author
2087 $xinfo
2088 ---
2089
2090 END
2091     close O or die $!;
2092
2093     {
2094         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2095         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2096         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2097         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2098     }
2099 }
2100
2101 sub quiltify_trees_differ ($$) {
2102     my ($x,$y) = @_;
2103     # returns 1 iff the two tree objects differ other than in debian/
2104     local $/=undef;
2105     my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2106     my $diffs= cmdoutput @cmd;
2107     foreach my $f (split /\0/, $diffs) {
2108         next if $f eq 'debian';
2109         return 1;
2110     }
2111     return 0;
2112 }
2113
2114 sub quiltify_tree_sentinelfiles ($) {
2115     # lists the `sentinel' files present in the tree
2116     my ($x) = @_;
2117     my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2118         qw(-- debian/rules debian/control);
2119     $r =~ s/\n/,/g;
2120     return $r;
2121 }
2122
2123 sub quiltify ($$) {
2124     my ($clogp,$target) = @_;
2125
2126     # Quilt patchification algorithm
2127     #
2128     # We search backwards through the history of the main tree's HEAD
2129     # (T) looking for a start commit S whose tree object is identical
2130     # to to the patch tip tree (ie the tree corresponding to the
2131     # current dpkg-committed patch series).  For these purposes
2132     # `identical' disregards anything in debian/ - this wrinkle is
2133     # necessary because dpkg-source treates debian/ specially.
2134     #
2135     # We can only traverse edges where at most one of the ancestors'
2136     # trees differs (in changes outside in debian/).  And we cannot
2137     # handle edges which change .pc/ or debian/patches.  To avoid
2138     # going down a rathole we avoid traversing edges which introduce
2139     # debian/rules or debian/control.  And we set a limit on the
2140     # number of edges we are willing to look at.
2141     #
2142     # If we succeed, we walk forwards again.  For each traversed edge
2143     # PC (with P parent, C child) (starting with P=S and ending with
2144     # C=T) to we do this:
2145     #  - git checkout C
2146     #  - dpkg-source --commit with a patch name and message derived from C
2147     # After traversing PT, we git commit the changes which
2148     # should be contained within debian/patches.
2149
2150     changedir '../fake';
2151     mktree_in_ud_here();
2152     rmtree '.pc';
2153     runcmd @git, 'add', '.';
2154     my $oldtiptree=git_write_tree();
2155     changedir '../work';
2156
2157     # The search for the path S..T is breadth-first.  We maintain a
2158     # todo list containing search nodes.  A search node identifies a
2159     # commit, and looks something like this:
2160     #  $p = {
2161     #      Commit => $git_commit_id,
2162     #      Child => $c,                          # or undef if P=T
2163     #      Whynot => $reason_edge_PC_unsuitable, # in @nots only
2164     #      Nontrivial => true iff $p..$c has relevant changes
2165     #  };
2166
2167     my @todo;
2168     my @nots;
2169     my $sref_S;
2170     my $max_work=100;
2171     my %considered; # saves being exponential on some weird graphs
2172
2173     my $t_sentinels = quiltify_tree_sentinelfiles $target;
2174
2175     my $not = sub {
2176         my ($search,$whynot) = @_;
2177         printdebug " search NOT $search->{Commit} $whynot\n";
2178         $search->{Whynot} = $whynot;
2179         push @nots, $search;
2180         no warnings qw(exiting);
2181         next;
2182     };
2183
2184     push @todo, {
2185         Commit => $target,
2186     };
2187
2188     while (@todo) {
2189         my $c = shift @todo;
2190         next if $considered{$c->{Commit}}++;
2191
2192         $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2193
2194         printdebug "quiltify investigate $c->{Commit}\n";
2195
2196         # are we done?
2197         if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2198             printdebug " search finished hooray!\n";
2199             $sref_S = $c;
2200             last;
2201         }
2202
2203         if ($quilt_mode eq 'nofix') {
2204             fail "quilt fixup required but quilt mode is \`nofix'\n".
2205                 "HEAD commit $c->{Commit} differs from tree implied by ".
2206                 " debian/patches (tree object $oldtiptree)";
2207         }
2208         if ($quilt_mode eq 'smash') {
2209             printdebug " search quitting smash\n";
2210             last;
2211         }
2212
2213         my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2214         $not->($c, "has $c_sentinels not $t_sentinels")
2215             if $c_sentinels ne $t_sentinels;
2216
2217         my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2218         $commitdata =~ m/\n\n/;
2219         $commitdata =~ $`;
2220         my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2221         @parents = map { { Commit => $_, Child => $c } } @parents;
2222
2223         $not->($c, "root commit") if !@parents;
2224
2225         foreach my $p (@parents) {
2226             $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2227         }
2228         my $ndiffers = grep { $_->{Nontrivial} } @parents;
2229         $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2230
2231         foreach my $p (@parents) {
2232             printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2233
2234             my @cmd= (@git, qw(diff-tree -r --name-only),
2235                       $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2236             my $patchstackchange = cmdoutput @cmd;
2237             if (length $patchstackchange) {
2238                 $patchstackchange =~ s/\n/,/g;
2239                 $not->($p, "changed $patchstackchange");
2240             }
2241
2242             printdebug " search queue P=$p->{Commit} ",
2243                 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2244             push @todo, $p;
2245         }
2246     }
2247
2248     if (!$sref_S) {
2249         printdebug "quiltify want to smash\n";
2250
2251         my $abbrev = sub {
2252             my $x = $_[0]{Commit};
2253             $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2254             return $;
2255         };
2256         my $reportnot = sub {
2257             my ($notp) = @_;
2258             my $s = $abbrev->($notp);
2259             my $c = $notp->{Child};
2260             $s .= "..".$abbrev->($c) if $c;
2261             $s .= ": ".$c->{Whynot};
2262             return $s;
2263         };
2264         if ($quilt_mode eq 'linear') {
2265             print STDERR "$us: quilt fixup cannot be linear.  Stopped at:\n";
2266             foreach my $notp (@nots) {
2267                 print STDERR "$us:  ", $reportnot->($notp), "\n";
2268             }
2269             fail "quilt fixup naive history linearisation failed.\n".
2270  "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2271         } elsif ($quilt_mode eq 'smash') {
2272         } elsif ($quilt_mode eq 'auto') {
2273             progress "quilt fixup cannot be linear, smashing...";
2274         } else {
2275             die "$quilt_mode ?";
2276         }
2277
2278         my $time = time;
2279         my $ncommits = 3;
2280         my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2281
2282         quiltify_dpkg_commit "auto-$version-$target-$time",
2283             (getfield $clogp, 'Maintainer'),
2284             "Automatically generated patch ($clogp->{Version})\n".
2285             "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2286         return;
2287     }
2288
2289     progress "quiltify linearisation planning successful, executing...";
2290
2291     for (my $p = $sref_S;
2292          my $c = $p->{Child};
2293          $p = $p->{Child}) {
2294         printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2295         next unless $p->{Nontrivial};
2296
2297         my $cc = $c->{Commit};
2298
2299         my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2300         $commitdata =~ m/\n\n/ or die "$c ?";
2301         $commitdata = $`;
2302         my $msg = $'; #';
2303         $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2304         my $author = $1;
2305
2306         $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2307
2308         my $title = $1;
2309         my $patchname = $title;
2310         $patchname =~ s/[.:]$//;
2311         $patchname =~ y/ A-Z/-a-z/;
2312         $patchname =~ y/-a-z0-9_.+=~//cd;
2313         $patchname =~ s/^\W/x-$&/;
2314         $patchname = substr($patchname,0,40);
2315         my $index;
2316         for ($index='';
2317              stat "debian/patches/$patchname$index";
2318              $index++) { }
2319         $!==ENOENT or die "$patchname$index $!";
2320
2321         runcmd @git, qw(checkout -q), $cc;
2322
2323         # We use the tip's changelog so that dpkg-source doesn't
2324         # produce complaining messages from dpkg-parsechangelog.  None
2325         # of the information dpkg-source gets from the changelog is
2326         # actually relevant - it gets put into the original message
2327         # which dpkg-source provides our stunt editor, and then
2328         # overwritten.
2329         runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2330
2331         quiltify_dpkg_commit "$patchname$index", $author, $msg,
2332             "X-Dgit-Generated: $clogp->{Version} $cc\n";
2333
2334         runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2335     }
2336
2337     runcmd @git, qw(checkout -q master);
2338 }
2339
2340 sub build_maybe_quilt_fixup () {
2341     my $format=get_source_format;
2342     return unless madformat $format;
2343     # sigh
2344
2345     # Our objective is:
2346     #  - honour any existing .pc in case it has any strangeness
2347     #  - determine the git commit corresponding to the tip of
2348     #    the patch stack (if there is one)
2349     #  - if there is such a git commit, convert each subsequent
2350     #    git commit into a quilt patch with dpkg-source --commit
2351     #  - otherwise convert all the differences in the tree into
2352     #    a single git commit
2353     #
2354     # To do this we:
2355
2356     # Our git tree doesn't necessarily contain .pc.  (Some versions of
2357     # dgit would include the .pc in the git tree.)  If there isn't
2358     # one, we need to generate one by unpacking the patches that we
2359     # have.
2360     #
2361     # We first look for a .pc in the git tree.  If there is one, we
2362     # will use it.  (This is not the normal case.)
2363     #
2364     # Otherwise need to regenerate .pc so that dpkg-source --commit
2365     # can work.  We do this as follows:
2366     #     1. Collect all relevant .orig from parent directory
2367     #     2. Generate a debian.tar.gz out of
2368     #         debian/{patches,rules,source/format}
2369     #     3. Generate a fake .dsc containing just these fields:
2370     #          Format Source Version Files
2371     #     4. Extract the fake .dsc
2372     #        Now the fake .dsc has a .pc directory.
2373     # (In fact we do this in every case, because in future we will
2374     # want to search for a good base commit for generating patches.)
2375     #
2376     # Then we can actually do the dpkg-source --commit
2377     #     1. Make a new working tree with the same object
2378     #        store as our main tree and check out the main
2379     #        tree's HEAD.
2380     #     2. Copy .pc from the fake's extraction, if necessary
2381     #     3. Run dpkg-source --commit
2382     #     4. If the result has changes to debian/, then
2383     #          - git-add them them
2384     #          - git-add .pc if we had a .pc in-tree
2385     #          - git-commit
2386     #     5. If we had a .pc in-tree, delete it, and git-commit
2387     #     6. Back in the main tree, fast forward to the new HEAD
2388
2389     my $clogp = parsechangelog();
2390     my $headref = rev_parse('HEAD');
2391
2392     prep_ud();
2393     changedir $ud;
2394
2395     my $upstreamversion=$version;
2396     $upstreamversion =~ s/-[^-]*$//;
2397
2398     my $fakeversion="$upstreamversion-~~DGITFAKE";
2399
2400     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2401     print $fakedsc <<END or die $!;
2402 Format: 3.0 (quilt)
2403 Source: $package
2404 Version: $fakeversion
2405 Files:
2406 END
2407
2408     my $dscaddfile=sub {
2409         my ($b) = @_;
2410         
2411         my $md = new Digest::MD5;
2412
2413         my $fh = new IO::File $b, '<' or die "$b $!";
2414         stat $fh or die $!;
2415         my $size = -s _;
2416
2417         $md->addfile($fh);
2418         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2419     };
2420
2421     foreach my $f (<../../../../*>) { #/){
2422         my $b=$f; $b =~ s{.*/}{};
2423         next unless is_orig_file $b, srcfn $upstreamversion,'';
2424         link $f, $b or die "$b $!";
2425         $dscaddfile->($b);
2426     }
2427
2428     my @files=qw(debian/source/format debian/rules);
2429     if (stat_exists '../../../debian/patches') {
2430         push @files, 'debian/patches';
2431     }
2432
2433     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2434     runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2435
2436     $dscaddfile->($debtar);
2437     close $fakedsc or die $!;
2438
2439     runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2440
2441     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2442     rename $fakexdir, "fake" or die "$fakexdir $!";
2443
2444     mkdir "work" or die $!;
2445     changedir "work";
2446     mktree_in_ud_here();
2447     runcmd @git, qw(reset --hard), $headref;
2448
2449     my $mustdeletepc=0;
2450     if (stat_exists ".pc") {
2451         -d _ or die;
2452         progress "Tree already contains .pc - will use it then delete it.";
2453         $mustdeletepc=1;
2454     } else {
2455         rename '../fake/.pc','.pc' or die $!;
2456     }
2457
2458     quiltify($clogp,$headref);
2459
2460     if (!open P, '>>', ".pc/applied-patches") {
2461         $!==&ENOENT or die $!;
2462     } else {
2463         close P;
2464     }
2465
2466     commit_quilty_patch();
2467
2468     if ($mustdeletepc) {
2469         runcmd @git, qw(rm -rq .pc);
2470         commit_admin "Commit removal of .pc (quilt series tracking data)";
2471     }
2472
2473     changedir '../../../..';
2474     runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2475 }
2476
2477 sub quilt_fixup_editor () {
2478     my $descfn = $ENV{$fakeeditorenv};
2479     my $editing = $ARGV[$#ARGV];
2480     open I1, '<', $descfn or die "$descfn: $!";
2481     open I2, '<', $editing or die "$editing: $!";
2482     unlink $editing or die "$editing: $!";
2483     open O, '>', $editing or die "$editing: $!";
2484     while (<I1>) { print O or die $!; } I1->error and die $!;
2485     my $copying = 0;
2486     while (<I2>) {
2487         $copying ||= m/^\-\-\- /;
2488         next unless $copying;
2489         print O or die $!;
2490     }
2491     I2->error and die $!;
2492     close O or die $1;
2493     exit 0;
2494 }
2495
2496 #----- other building -----
2497
2498 sub clean_tree () {
2499     if ($cleanmode eq 'dpkg-source') {
2500         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2501     } elsif ($cleanmode eq 'git') {
2502         runcmd_ordryrun_local @git, qw(clean -xdf);
2503     } elsif ($cleanmode eq 'none') {
2504     } else {
2505         die "$cleanmode ?";
2506     }
2507 }
2508
2509 sub cmd_clean () {
2510     badusage "clean takes no additional arguments" if @ARGV;
2511     clean_tree();
2512 }
2513
2514 sub build_prep () {
2515     badusage "-p is not allowed when building" if defined $package;
2516     check_not_dirty();
2517     clean_tree();
2518     my $clogp = parsechangelog();
2519     $isuite = getfield $clogp, 'Distribution';
2520     $package = getfield $clogp, 'Source';
2521     $version = getfield $clogp, 'Version';
2522     build_maybe_quilt_fixup();
2523 }
2524
2525 sub changesopts () {
2526     my @opts =@changesopts[1..$#changesopts];
2527     if (!defined $changes_since_version) {
2528         my @vsns = archive_query('archive_query');
2529         my @quirk = access_quirk();
2530         if ($quirk[0] eq 'backports') {
2531             local $isuite = $quirk[2];
2532             local $csuite;
2533             canonicalise_suite();
2534             push @vsns, archive_query('archive_query');
2535         }
2536         if (@vsns) {
2537             @vsns = map { $_->[0] } @vsns;
2538             @vsns = sort { -version_compare($a, $b) } @vsns;
2539             $changes_since_version = $vsns[0];
2540             progress "changelog will contain changes since $vsns[0]";
2541         } else {
2542             $changes_since_version = '_';
2543             progress "package seems new, not specifying -v<version>";
2544         }
2545     }
2546     if ($changes_since_version ne '_') {
2547         unshift @opts, "-v$changes_since_version";
2548     }
2549     return @opts;
2550 }
2551
2552 sub cmd_build {
2553     build_prep();
2554     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2555     printdone "build successful\n";
2556 }
2557
2558 sub cmd_git_build {
2559     build_prep();
2560     my @cmd =
2561         (qw(git-buildpackage -us -uc --git-no-sign-tags),
2562          "--git-builder=@dpkgbuildpackage");
2563     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2564         canonicalise_suite();
2565         push @cmd, "--git-debian-branch=".lbranch();
2566     }
2567     push @cmd, changesopts();
2568     runcmd_ordryrun_local @cmd, @ARGV;
2569     printdone "build successful\n";
2570 }
2571
2572 sub build_source {
2573     build_prep();
2574     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2575     $dscfn = dscfn($version);
2576     if ($cleanmode eq 'dpkg-source') {
2577         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2578             changesopts();
2579     } else {
2580         my $pwd = must_getcwd();
2581         my $leafdir = basename $pwd;
2582         changedir "..";
2583         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2584         changedir $pwd;
2585         runcmd_ordryrun_local qw(sh -ec),
2586             'exec >$1; shift; exec "$@"','x',
2587             "../$sourcechanges",
2588             @dpkggenchanges, qw(-S), changesopts();
2589     }
2590 }
2591
2592 sub cmd_build_source {
2593     badusage "build-source takes no additional arguments" if @ARGV;
2594     build_source();
2595     printdone "source built, results in $dscfn and $sourcechanges";
2596 }
2597
2598 sub cmd_sbuild {
2599     build_source();
2600     changedir "..";
2601     my $pat = "${package}_".(stripepoch $version)."_*.changes";
2602     if (act_local()) {
2603         stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2604         stat_exists $sourcechanges
2605             or fail "$sourcechanges (in parent directory): $!";
2606         foreach my $cf (glob $pat) {
2607             next if $cf eq $sourcechanges;
2608             unlink $cf or fail "remove $cf: $!";
2609         }
2610     }
2611     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2612     my @changesfiles = glob $pat;
2613     @changesfiles = sort {
2614         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2615             or $a cmp $b
2616     } @changesfiles;
2617     fail "wrong number of different changes files (@changesfiles)"
2618         unless @changesfiles;
2619     runcmd_ordryrun_local @mergechanges, @changesfiles;
2620     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2621     if (act_local()) {
2622         stat_exists $multichanges or fail "$multichanges: $!";
2623     }
2624     printdone "build successful, results in $multichanges\n" or die $!;
2625 }    
2626
2627 sub cmd_quilt_fixup {
2628     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2629     my $clogp = parsechangelog();
2630     $version = getfield $clogp, 'Version';
2631     $package = getfield $clogp, 'Source';
2632     build_maybe_quilt_fixup();
2633 }
2634
2635 sub cmd_archive_api_query {
2636     badusage "need only 1 subpath argument" unless @ARGV==1;
2637     my ($subpath) = @ARGV;
2638     my @cmd = archive_api_query_cmd($subpath);
2639     exec @cmd or fail "exec curl: $!\n";
2640 }
2641
2642 #---------- argument parsing and main program ----------
2643
2644 sub cmd_version {
2645     print "dgit version $our_version\n" or die $!;
2646     exit 0;
2647 }
2648
2649 sub parseopts () {
2650     my $om;
2651
2652     if (defined $ENV{'DGIT_SSH'}) {
2653         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2654     } elsif (defined $ENV{'GIT_SSH'}) {
2655         @ssh = ($ENV{'GIT_SSH'});
2656     }
2657
2658     while (@ARGV) {
2659         last unless $ARGV[0] =~ m/^-/;
2660         $_ = shift @ARGV;
2661         last if m/^--?$/;
2662         if (m/^--/) {
2663             if (m/^--dry-run$/) {
2664                 push @ropts, $_;
2665                 $dryrun_level=2;
2666             } elsif (m/^--damp-run$/) {
2667                 push @ropts, $_;
2668                 $dryrun_level=1;
2669             } elsif (m/^--no-sign$/) {
2670                 push @ropts, $_;
2671                 $sign=0;
2672             } elsif (m/^--help$/) {
2673                 cmd_help();
2674             } elsif (m/^--version$/) {
2675                 cmd_version();
2676             } elsif (m/^--new$/) {
2677                 push @ropts, $_;
2678                 $new_package=1;
2679             } elsif (m/^--since-version=([^_]+|_)$/) {
2680                 push @ropts, $_;
2681                 $changes_since_version = $1;
2682             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2683                      ($om = $opts_opt_map{$1}) &&
2684                      length $om->[0]) {
2685                 push @ropts, $_;
2686                 $om->[0] = $2;
2687             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2688                      !$opts_opt_cmdonly{$1} &&
2689                      ($om = $opts_opt_map{$1})) {
2690                 push @ropts, $_;
2691                 push @$om, $2;
2692             } elsif (m/^--existing-package=(.*)/s) {
2693                 push @ropts, $_;
2694                 $existing_package = $1;
2695             } elsif (m/^--initiator-tempdir=(.*)/s) {
2696                 $initiator_tempdir = $1;
2697                 $initiator_tempdir =~ m#^/# or
2698                     badusage "--initiator-tempdir must be used specify an".
2699                         " absolute, not relative, directory."
2700             } elsif (m/^--distro=(.*)/s) {
2701                 push @ropts, $_;
2702                 $idistro = $1;
2703             } elsif (m/^--build-products-dir=(.*)/s) {
2704                 push @ropts, $_;
2705                 $buildproductsdir = $1;
2706             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2707                 push @ropts, $_;
2708                 $cleanmode = $1;
2709             } elsif (m/^--clean=(.*)$/s) {
2710                 badusage "unknown cleaning mode \`$1'";
2711             } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2712                 push @ropts, $_;
2713                 $quilt_mode = $1;
2714             } elsif (m/^--quilt=(.*)$/s) {
2715                 badusage "unknown quilt fixup mode \`$1'";
2716             } elsif (m/^--ignore-dirty$/s) {
2717                 push @ropts, $_;
2718                 $ignoredirty = 1;
2719             } elsif (m/^--no-quilt-fixup$/s) {
2720                 push @ropts, $_;
2721                 $quilt_mode = 'nocheck';
2722             } elsif (m/^--no-rm-on-error$/s) {
2723                 push @ropts, $_;
2724                 $rmonerror = 0;
2725             } elsif (m/^--deliberately-($suite_re)$/s) {
2726                 push @ropts, $_;
2727                 push @deliberatelies, $&;
2728             } else {
2729                 badusage "unknown long option \`$_'";
2730             }
2731         } else {
2732             while (m/^-./s) {
2733                 if (s/^-n/-/) {
2734                     push @ropts, $&;
2735                     $dryrun_level=2;
2736                 } elsif (s/^-L/-/) {
2737                     push @ropts, $&;
2738                     $dryrun_level=1;
2739                 } elsif (s/^-h/-/) {
2740                     cmd_help();
2741                 } elsif (s/^-D/-/) {
2742                     push @ropts, $&;
2743                     open DEBUG, ">&STDERR" or die $!;
2744                     autoflush DEBUG 1;
2745                     $debug++;
2746                 } elsif (s/^-N/-/) {
2747                     push @ropts, $&;
2748                     $new_package=1;
2749                 } elsif (s/^-v([^_]+|_)$//s) {
2750                     push @ropts, $&;
2751                     $changes_since_version = $1;
2752                 } elsif (m/^-m/) {
2753                     push @ropts, $&;
2754                     push @changesopts, $_;
2755                     $_ = '';
2756                 } elsif (s/^-c(.*=.*)//s) {
2757                     push @ropts, $&;
2758                     push @git, '-c', $1;
2759                 } elsif (s/^-d(.+)//s) {
2760                     push @ropts, $&;
2761                     $idistro = $1;
2762                 } elsif (s/^-C(.+)//s) {
2763                     push @ropts, $&;
2764                     $changesfile = $1;
2765                     if ($changesfile =~ s#^(.*)/##) {
2766                         $buildproductsdir = $1;
2767                     }
2768                 } elsif (s/^-k(.+)//s) {
2769                     $keyid=$1;
2770                 } elsif (m/^-[vdCk]$/) {
2771                     badusage
2772  "option \`$_' requires an argument (and no space before the argument)";
2773                 } elsif (s/^-wn$//s) {
2774                     push @ropts, $&;
2775                     $cleanmode = 'none';
2776                 } elsif (s/^-wg$//s) {
2777                     push @ropts, $&;
2778                     $cleanmode = 'git';
2779                 } elsif (s/^-wd$//s) {
2780                     push @ropts, $&;
2781                     $cleanmode = 'dpkg-source';
2782                 } else {
2783                     badusage "unknown short option \`$_'";
2784                 }
2785             }
2786         }
2787     }
2788 }
2789
2790 if ($ENV{$fakeeditorenv}) {
2791     quilt_fixup_editor();
2792 }
2793
2794 parseopts();
2795 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2796 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2797     if $dryrun_level == 1;
2798 if (!@ARGV) {
2799     print STDERR $helpmsg or die $!;
2800     exit 8;
2801 }
2802 my $cmd = shift @ARGV;
2803 $cmd =~ y/-/_/;
2804
2805 if (!defined $quilt_mode) {
2806     $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2807         // access_cfg('quilt-mode', 'RETURN-UNDEF')
2808         // 'linear';
2809     $quilt_mode =~ m/^($quilt_modes_re)$/ 
2810         or badcfg "unknown quilt-mode \`$quilt_mode'";
2811     $quilt_mode = $1;
2812 }
2813
2814 my $fn = ${*::}{"cmd_$cmd"};
2815 $fn or badusage "unknown operation $cmd";
2816 $fn->();