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