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