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