chiark / gitweb /
dgit-repos-server: make _tmp
[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
33 our $our_version = 'UNRELEASED'; ###substituted###
34
35 our $isuite = 'unstable';
36 our $idistro;
37 our $package;
38 our @ropts;
39
40 our $sign = 1;
41 our $dryrun_level = 0;
42 our $changesfile;
43 our $buildproductsdir = '..';
44 our $new_package = 0;
45 our $ignoredirty = 0;
46 our $noquilt = 0;
47 our $existing_package = 'dpkg';
48 our $cleanmode = 'dpkg-source';
49 our $changes_since_version;
50 our $we_are_responder;
51 our $initiator_tempdir;
52
53 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
54
55 our (@git) = qw(git);
56 our (@dget) = qw(dget);
57 our (@dput) = qw(dput);
58 our (@debsign) = qw(debsign);
59 our (@gpg) = qw(gpg);
60 our (@sbuild) = qw(sbuild -A);
61 our (@ssh) = 'ssh';
62 our (@dgit) = qw(dgit);
63 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
64 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
65 our (@dpkggenchanges) = qw(dpkg-genchanges);
66 our (@mergechanges) = qw(mergechanges -f);
67 our (@changesopts) = ('');
68
69 our %opts_opt_map = ('dget' => \@dget,
70                      'dput' => \@dput,
71                      'debsign' => \@debsign,
72                      'gpg' => \@gpg,
73                      'sbuild' => \@sbuild,
74                      'ssh' => \@ssh,
75                      'dgit' => \@dgit,
76                      'dpkg-source' => \@dpkgsource,
77                      'dpkg-buildpackage' => \@dpkgbuildpackage,
78                      'dpkg-genchanges' => \@dpkggenchanges,
79                      'ch' => \@changesopts,
80                      'mergechanges' => \@mergechanges);
81
82 our %opts_opt_cmdonly = ('gpg' => 1);
83
84 our $keyid;
85
86 our $debug = 0;
87 open DEBUG, ">/dev/null" or die $!;
88
89 autoflush STDOUT 1;
90
91 our $remotename = 'dgit';
92 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
93 our $branchprefix = 'dgit';
94 our $csuite;
95
96 sub lbranch () { return "$branchprefix/$csuite"; }
97 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
98 sub lref () { return "refs/heads/".lbranch(); }
99 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
100 sub rrref () { return "refs/$branchprefix/$csuite"; }
101 sub debiantag ($) { 
102     my ($v) = @_;
103     $v =~ y/~:/_%/;
104     return "debian/$v";
105 }
106
107 sub stripepoch ($) {
108     my ($vsn) = @_;
109     $vsn =~ s/^\d+\://;
110     return $vsn;
111 }
112
113 sub dscfn ($) {
114     my ($vsn) = @_;
115     return "${package}_".(stripepoch $vsn).".dsc";
116 }
117
118 our $us = 'dgit';
119 our $debugprefix = '';
120
121 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
122
123 sub fail { 
124     die $us.($we_are_responder ? " (build host)" : "").": @_\n";
125 }
126
127 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
128
129 sub no_such_package () {
130     print STDERR "$us: package $package does not exist in suite $isuite\n";
131     exit 4;
132 }
133
134 sub fetchspec () {
135     local $csuite = '*';
136     return  "+".rrref().":".lrref();
137 }
138
139 sub changedir ($) {
140     my ($newdir) = @_;
141     printdebug "CD $newdir\n";
142     chdir $newdir or die "chdir: $newdir: $!";
143 }
144
145 #---------- remote protocol support, common ----------
146
147 # remote push initiator/responder protocol:
148 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
149 #
150 #  > file parsed-changelog
151 #  [indicates that output of dpkg-parsechangelog follows]
152 #  > data-block NBYTES
153 #  > [NBYTES bytes of data (no newline)]
154 #  [maybe some more blocks]
155 #  > data-end
156 #
157 #  > file dsc
158 #  [etc]
159 #
160 #  > file changes
161 #  [etc]
162 #
163 #  > param head HEAD
164 #
165 #  > want signed-tag
166 #  [indicates that signed tag is wanted]
167 #  < data-block NBYTES
168 #  < [NBYTES bytes of data (no newline)]
169 #  [maybe some more blocks]
170 #  < data-end
171 #  < files-end
172 #
173 #  > want signed-dsc-changes
174 #  < data-block NBYTES    [transfer of signed dsc]
175 #  [etc]
176 #  < data-block NBYTES    [transfer of signed changes]
177 #  [etc]
178 #  < files-end
179 #
180 #  > complete
181
182 sub badproto ($$) {
183     my ($fh, $m) = @_;
184     fail "connection lost: $!" if $fh->error;
185     fail "protocol violation; $m not expected";
186 }
187
188 sub protocol_expect (&$) {
189     my ($match, $fh) = @_;
190     local $_;
191     $_ = <$fh>;
192     defined && chomp or badproto $fh, "eof";
193     if (wantarray) {
194         my @r = &$match;
195         return @r if @r;
196     } else {
197         my $r = &$match;
198         return $r if $r;
199     }
200     badproto $fh, "\`$_'";
201 }
202
203 sub protocol_send_file ($$) {
204     my ($fh, $ourfn) = @_;
205     open PF, "<", $ourfn or die "$ourfn: $!";
206     for (;;) {
207         my $d;
208         my $got = read PF, $d, 65536;
209         die "$ourfn: $!" unless defined $got;
210         last if !$got;
211         print $fh "data-block ".length($d)."\n" or die $!;
212         print $fh $d or die $!;
213     }
214     PF->error and die "$ourfn $!";
215     print $fh "data-end\n" or die $!;
216     close PF;
217 }
218
219 sub protocol_read_bytes ($$) {
220     my ($fh, $nbytes) = @_;
221     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
222     my $d;
223     my $got = read $fh, $d, $nbytes;
224     $got==$nbytes or badproto $fh, "eof during data block";
225     return $d;
226 }
227
228 sub protocol_receive_file ($$) {
229     my ($fh, $ourfn) = @_;
230     printdebug "() $ourfn\n";
231     open PF, ">", $ourfn or die "$ourfn: $!";
232     for (;;) {
233         my ($y,$l) = protocol_expect {
234             m/^data-block (.*)$/ ? (1,$1) :
235             m/^data-end$/ ? (0,) :
236             ();
237         } $fh;
238         last unless $y;
239         my $d = protocol_read_bytes $fh, $l;
240         print PF $d or die $!;
241     }
242     close PF or die $!;
243 }
244
245 #---------- remote protocol support, responder ----------
246
247 sub responder_send_command ($) {
248     my ($command) = @_;
249     return unless $we_are_responder;
250     # called even without $we_are_responder
251     printdebug ">> $command\n";
252     print PO $command, "\n" or die $!;
253 }    
254
255 sub responder_send_file ($$) {
256     my ($keyword, $ourfn) = @_;
257     return unless $we_are_responder;
258     printdebug "]] $keyword $ourfn\n";
259     responder_send_command "file $keyword";
260     protocol_send_file \*PO, $ourfn;
261 }
262
263 sub responder_receive_files ($@) {
264     my ($keyword, @ourfns) = @_;
265     die unless $we_are_responder;
266     printdebug "[[ $keyword @ourfns\n";
267     responder_send_command "want $keyword";
268     foreach my $fn (@ourfns) {
269         protocol_receive_file \*PI, $fn;
270     }
271     printdebug "[[\$\n";
272     protocol_expect { m/^files-end$/ } \*PI;
273 }
274
275 #---------- remote protocol support, initiator ----------
276
277 sub initiator_expect (&) {
278     my ($match) = @_;
279     protocol_expect { &$match } \*RO;
280 }
281
282 #---------- end remote code ----------
283
284 sub progress {
285     if ($we_are_responder) {
286         my $m = join '', @_;
287         responder_send_command "progress ".length($m) or die $!;
288         print PO $m or die $!;
289     } else {
290         print @_, "\n";
291     }
292 }
293
294 our $ua;
295
296 sub url_get {
297     if (!$ua) {
298         $ua = LWP::UserAgent->new();
299         $ua->env_proxy;
300     }
301     my $what = $_[$#_];
302     progress "downloading $what...";
303     my $r = $ua->get(@_) or die $!;
304     return undef if $r->code == 404;
305     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
306     return $r->decoded_content();
307 }
308
309 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
310
311 sub shellquote {
312     my @out;
313     local $_;
314     foreach my $a (@_) {
315         $_ = $a;
316         if (m{[^-=_./0-9a-z]}i) {
317             s{['\\]}{'\\$&'}g;
318             push @out, "'$_'";
319         } else {
320             push @out, $_;
321         }
322     }
323     return join ' ', @out;
324 }
325
326 sub printcmd {
327     my $fh = shift @_;
328     my $intro = shift @_;
329     print $fh $intro," " or die $!;
330     print $fh shellquote @_ or die $!;
331     print $fh "\n" or die $!;
332 }
333
334 sub failedcmd {
335     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
336     if ($!) {
337         fail "failed to fork/exec: $!";
338     } elsif (!($? & 0xff)) {
339         fail "subprocess failed with error exit status ".($?>>8);
340     } elsif ($?) {
341         fail "subprocess crashed (wait status $?)";
342     } else {
343         fail "subprocess produced invalid output";
344     }
345 }
346
347 sub runcmd {
348     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
349     $!=0; $?=0;
350     failedcmd @_ if system @_;
351 }
352
353 sub act_local () { return $dryrun_level <= 1; }
354 sub act_scary () { return !$dryrun_level; }
355
356 sub printdone {
357     if (!$dryrun_level) {
358         progress "dgit ok: @_";
359     } else {
360         progress "would be ok: @_ (but dry run only)";
361     }
362 }
363
364 sub cmdoutput_errok {
365     die Dumper(\@_)." ?" if grep { !defined } @_;
366     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
367     open P, "-|", @_ or die $!;
368     my $d;
369     $!=0; $?=0;
370     { local $/ = undef; $d = <P>; }
371     die $! if P->error;
372     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
373     chomp $d;
374     $d =~ m/^.*/;
375     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
376     return $d;
377 }
378
379 sub cmdoutput {
380     my $d = cmdoutput_errok @_;
381     defined $d or failedcmd @_;
382     return $d;
383 }
384
385 sub dryrun_report {
386     printcmd(\*STDERR,$debugprefix."#",@_);
387 }
388
389 sub runcmd_ordryrun {
390     if (act_scary()) {
391         runcmd @_;
392     } else {
393         dryrun_report @_;
394     }
395 }
396
397 sub runcmd_ordryrun_local {
398     if (act_local()) {
399         runcmd @_;
400     } else {
401         dryrun_report @_;
402     }
403 }
404
405 sub shell_cmd {
406     my ($first_shell, @cmd) = @_;
407     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
408 }
409
410 our $helpmsg = <<END;
411 main usages:
412   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
413   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
414   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
415   dgit [dgit-opts] push [dgit-opts] [suite]
416   dgit [dgit-opts] rpush build-host:build-dir ...
417 important dgit options:
418   -k<keyid>           sign tag and package with <keyid> instead of default
419   --dry-run -n        do not change anything, but go through the motions
420   --damp-run -L       like --dry-run but make local changes, without signing
421   --new -N            allow introducing a new package
422   --debug -D          increase debug level
423   -c<name>=<value>    set git config option (used directly by dgit too)
424 END
425
426 our $later_warning_msg = <<END;
427 Perhaps the upload is stuck in incoming.  Using the version from git.
428 END
429
430 sub badusage {
431     print STDERR "$us: @_\n", $helpmsg or die $!;
432     exit 8;
433 }
434
435 sub nextarg {
436     @ARGV or badusage "too few arguments";
437     return scalar shift @ARGV;
438 }
439
440 sub cmd_help () {
441     print $helpmsg or die $!;
442     exit 0;
443 }
444
445 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
446
447 our %defcfg = ('dgit.default.distro' => 'debian',
448                'dgit.default.username' => '',
449                'dgit.default.archive-query-default-component' => 'main',
450                'dgit.default.ssh' => 'ssh',
451                'dgit-distro.debian.git-user' => 'dgit',
452                'dgit-distro.debian.git-host' => 'git.debian.org',
453                'dgit-distro.debian.git-proto' => 'git+ssh://',
454                'dgit-distro.debian.git-path' => '/dgit-repos/',
455                'dgit-distro.debian.git-check' => 'true',
456                'dgit-distro.debian.git-create' => 'true',
457                'dgit-distro.debian.sshpsql-host' => 'coccia.debian.org',
458                'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
459                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
460                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
461  'dgit-distro.debian.backports-quirk' => '%-backports*',
462  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
463                'dgit-distro.test-dummy.ssh' => "$td/ssh",
464                'dgit-distro.test-dummy.username' => "alice",
465                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
466                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
467                'dgit-distro.test-dummy.git-url' => "$td/git",
468                'dgit-distro.test-dummy.git-host' => "git",
469                'dgit-distro.test-dummy.git-path' => "$td/git",
470                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
471                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
472                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
473                );
474
475 sub cfg {
476     foreach my $c (@_) {
477         return undef if $c =~ /RETURN-UNDEF/;
478         my @cmd = (@git, qw(config --), $c);
479         my $v;
480         {
481             local ($debug) = $debug-1;
482             $v = cmdoutput_errok @cmd;
483         };
484         if ($?==0) {
485             return $v;
486         } elsif ($?!=256) {
487             failedcmd @cmd;
488         }
489         my $dv = $defcfg{$c};
490         return $dv if defined $dv;
491     }
492     badcfg "need value for one of: @_";
493 }
494
495 sub access_basedistro () {
496     return cfg("dgit-suite.$isuite.distro",
497                "dgit.default.distro");
498 }
499
500 sub access_quirk () {
501     # returns (quirk name, distro to use instead, quirk-specific info)
502     my $basedistro = access_basedistro();
503     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
504                               'RETURN-UNDEF');
505     if (defined $backports_quirk) {
506         my $re = $backports_quirk;
507         $re =~ s/[^-0-9a-z_\%*]/\\$&/ig;
508         $re =~ s/\*/.*/g;
509         $re =~ s/\%/([-0-9a-z_]+)/ or badcfg "backports-quirk needs \%";
510         if ($isuite =~ m/^$re$/) {
511             return ('backports',"$basedistro-backports",$1);
512         }
513     }
514     return ('none',$basedistro);
515 }
516
517 sub access_distro () {
518     return (access_quirk())[1];
519 }
520
521 sub access_cfg (@) {
522     my (@keys) = @_;
523     my $basedistro = access_basedistro();
524     my $distro = $idistro || access_distro();
525     my $value = cfg(map {
526         ("dgit-distro.$distro.$_",
527          "dgit-distro.$basedistro.$_",
528          "dgit.default.$_")
529                     } @keys);
530     return $value;
531 }
532
533 sub string_to_ssh ($) {
534     my ($spec) = @_;
535     if ($spec =~ m/\s/) {
536         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
537     } else {
538         return ($spec);
539     }
540 }
541
542 sub access_cfg_ssh () {
543     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
544     if (!defined $gitssh) {
545         return @ssh;
546     } else {
547         return string_to_ssh $gitssh;
548     }
549 }
550
551 sub access_someuserhost ($) {
552     my ($some) = @_;
553     my $user = access_cfg("$some-user",'username');
554     my $host = access_cfg("$some-host");
555     return length($user) ? "$user\@$host" : $host;
556 }
557
558 sub access_gituserhost () {
559     return access_someuserhost('git');
560 }
561
562 sub access_giturl () {
563     my $url = access_cfg('git-url','RETURN-UNDEF');
564     if (!defined $url) {
565         $url =
566             access_cfg('git-proto').
567             access_gituserhost().
568             access_cfg('git-path');
569     }
570     return "$url/$package.git";
571 }              
572
573 sub parsecontrolfh ($$@) {
574     my ($fh, $desc, @opts) = @_;
575     my %opts = ('name' => $desc, @opts);
576     my $c = Dpkg::Control::Hash->new(%opts);
577     $c->parse($fh) or die "parsing of $desc failed";
578     return $c;
579 }
580
581 sub parsecontrol {
582     my ($file, $desc) = @_;
583     my $fh = new IO::Handle;
584     open $fh, '<', $file or die "$file: $!";
585     my $c = parsecontrolfh($fh,$desc);
586     $fh->error and die $!;
587     close $fh;
588     return $c;
589 }
590
591 sub getfield ($$) {
592     my ($dctrl,$field) = @_;
593     my $v = $dctrl->{$field};
594     return $v if defined $v;
595     fail "missing field $field in ".$v->get_option('name');
596 }
597
598 sub parsechangelog {
599     my $c = Dpkg::Control::Hash->new();
600     my $p = new IO::Handle;
601     my @cmd = (qw(dpkg-parsechangelog), @_);
602     open $p, '-|', @cmd or die $!;
603     $c->parse($p);
604     $?=0; $!=0; close $p or failedcmd @cmd;
605     return $c;
606 }
607
608 sub git_get_ref ($) {
609     my ($refname) = @_;
610     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
611     if (!defined $got) {
612         $?==256 or fail "git show-ref failed (status $?)";
613         printdebug "ref $refname= [show-ref exited 1]\n";
614         return '';
615     }
616     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
617         printdebug "ref $refname=$1\n";
618         return $1;
619     } else {
620         printdebug "ref $refname= [no match]\n";
621         return '';
622     }
623 }
624
625 our %rmad;
626
627 sub archive_query ($) {
628     my ($method) = @_;
629     my $query = access_cfg('archive-query','RETURN-UNDEF');
630     if (!defined $query) {
631         my $distro = access_basedistro();
632         if ($distro eq 'debian') {
633             $query = "sshpsql:".
634                 access_someuserhost('sshpsql').':'.
635                 access_cfg('sshpsql-dbname');
636         } else {
637             $query = "madison:$distro";
638         }
639     }
640     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
641     my $proto = $1;
642     my $data = $'; #';
643     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
644 }
645
646 sub pool_dsc_subpath ($$) {
647     my ($vsn,$component) = @_; # $package is implict arg
648     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
649     return "/pool/$component/$prefix/$package/".dscfn($vsn);
650 }
651
652 sub archive_query_madison ($$) {
653     my ($proto,$data) = @_;
654     die unless $proto eq 'madison';
655     $rmad{$package} ||= cmdoutput
656         qw(rmadison -asource),"-s$isuite","-u$data",$package;
657     my $rmad = $rmad{$package};
658     return madison_parse($rmad);
659 }
660
661 sub madison_parse ($) {
662     my ($rmad) = @_;
663     my @out;
664     foreach my $l (split /\n/, $rmad) {
665         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
666                   \s*( [^ \t|]+ )\s* \|
667                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
668                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
669         $1 eq $package or die "$rmad $package ?";
670         my $vsn = $2;
671         my $newsuite = $3;
672         my $component;
673         if (defined $4) {
674             $component = $4;
675         } else {
676             $component = access_cfg('archive-query-default-component');
677         }
678         $5 eq 'source' or die "$rmad ?";
679         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
680     }
681     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
682 }
683
684 sub canonicalise_suite_madison ($$) {
685     # madison canonicalises for us
686     my @r = archive_query_madison($_[0],$_[1]);
687     @r or fail
688         "unable to canonicalise suite using package $package".
689         " which does not appear to exist in suite $isuite;".
690         " --existing-package may help";
691     return $r[0][2];
692 }
693
694 sub sshpsql ($$) {
695     my ($data,$sql) = @_;
696     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
697     my ($userhost,$dbname) = ($`,$'); #';
698     my @rows;
699     my @cmd = (access_cfg_ssh, $userhost,
700                "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
701     printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
702     open P, "-|", @cmd or die $!;
703     while (<P>) {
704         chomp or die;
705         printdebug("$debugprefix>|$_|\n");
706         push @rows, $_;
707     }
708     $!=0; $?=0; close P or failedcmd @cmd;
709     @rows or die;
710     my $nrows = pop @rows;
711     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
712     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
713     @rows = map { [ split /\|/, $_ ] } @rows;
714     my $ncols = scalar @{ shift @rows };
715     die if grep { scalar @$_ != $ncols } @rows;
716     return @rows;
717 }
718
719 sub sql_injection_check {
720     foreach (@_) { die "$_ $& ?" if m/[']/; }
721 }
722
723 sub archive_query_sshpsql ($$) {
724     my ($proto,$data) = @_;
725     sql_injection_check $isuite, $package;
726     my @rows = sshpsql($data, <<END);
727         SELECT source.version, component.name, files.filename
728           FROM source
729           JOIN src_associations ON source.id = src_associations.source
730           JOIN suite ON suite.id = src_associations.suite
731           JOIN dsc_files ON dsc_files.source = source.id
732           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
733           JOIN component ON component.id = files_archive_map.component_id
734           JOIN files ON files.id = dsc_files.file
735          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
736            AND source.source='$package'
737            AND files.filename LIKE '%.dsc';
738 END
739     @rows = sort { -version_compare_string($a->[0],$b->[0]) } @rows;
740     @rows = map {
741         my ($vsn,$component,$filename) = @$_;
742         [ $vsn, "/pool/$component/$filename" ];
743     } @rows;
744     return @rows;
745 }
746
747 sub canonicalise_suite_sshpsql ($$) {
748     my ($proto,$data) = @_;
749     sql_injection_check $isuite;
750     my @rows = sshpsql($data, <<END);
751         SELECT suite.codename
752           FROM suite where suite_name='$isuite' or codename='$isuite';
753 END
754     @rows = map { $_->[0] } @rows;
755     fail "unknown suite $isuite" unless @rows;
756     die "ambiguous $isuite: @rows ?" if @rows>1;
757     return $rows[0];
758 }
759
760 sub canonicalise_suite_dummycat ($$) {
761     my ($proto,$data) = @_;
762     my $dpath = "$data/suite.$isuite";
763     if (!open C, "<", $dpath) {
764         $!==ENOENT or die "$dpath: $!";
765         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
766         return $isuite;
767     }
768     $!=0; $_ = <C>;
769     chomp or die "$dpath: $!";
770     close C;
771     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
772     return $_;
773 }
774
775 sub archive_query_dummycat ($$) {
776     my ($proto,$data) = @_;
777     canonicalise_suite();
778     my $dpath = "$data/package.$csuite.$package";
779     if (!open C, "<", $dpath) {
780         $!==ENOENT or die "$dpath: $!";
781         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
782         return ();
783     }
784     my @rows;
785     while (<C>) {
786         next if m/^\#/;
787         next unless m/\S/;
788         die unless chomp;
789         printdebug "dummycat query $csuite $package $dpath | $_\n";
790         my @row = split /\s+/, $_;
791         @row==2 or die "$dpath: $_ ?";
792         push @rows, \@row;
793     }
794     C->error and die "$dpath: $!";
795     close C;
796     return sort { -version_compare_string($a->[0],$b->[0]); } @rows;
797 }
798
799 sub canonicalise_suite () {
800     return if defined $csuite;
801     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
802     $csuite = archive_query('canonicalise_suite');
803     if ($isuite ne $csuite) {
804         progress "canonical suite name for $isuite is $csuite";
805     }
806 }
807
808 sub get_archive_dsc () {
809     canonicalise_suite();
810     my @vsns = archive_query('archive_query');
811     foreach my $vinfo (@vsns) {
812         my ($vsn,$subpath) = @$vinfo;
813         $dscurl = access_cfg('mirror').$subpath;
814         $dscdata = url_get($dscurl);
815         if (!$dscdata) {
816             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
817             next;
818         }
819         my $dscfh = new IO::File \$dscdata, '<' or die $!;
820         printdebug Dumper($dscdata) if $debug>1;
821         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
822         printdebug Dumper($dsc) if $debug>1;
823         my $fmt = getfield $dsc, 'Format';
824         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
825         return;
826     }
827     $dsc = undef;
828 }
829
830 sub check_for_git () {
831     # returns 0 or 1
832     my $how = access_cfg('git-check');
833     if ($how eq 'ssh-cmd') {
834         my @cmd =
835             (access_cfg_ssh, access_gituserhost(),
836              " set -e; cd ".access_cfg('git-path').";".
837              " if test -d $package.git; then echo 1; else echo 0; fi");
838         my $r= cmdoutput @cmd;
839         failedcmd @cmd unless $r =~ m/^[01]$/;
840         return $r+0;
841     } elsif ($how eq 'true') {
842         return 1;
843     } else {
844         badcfg "unknown git-check \`$how'";
845     }
846 }
847
848 sub create_remote_git_repo () {
849     my $how = access_cfg('git-create');
850     if ($how eq 'ssh-cmd') {
851         runcmd_ordryrun
852             (access_cfg_ssh, access_gituserhost(),
853              "set -e; cd ".access_cfg('git-path').";".
854              " cp -a _template $package.git");
855     } elsif ($how eq 'true') {
856         # nothing to do
857     } else {
858         badcfg "unknown git-create \`$how'";
859     }
860 }
861
862 our ($dsc_hash,$lastpush_hash);
863
864 our $ud = '.git/dgit/unpack';
865
866 sub prep_ud () {
867     rmtree($ud);
868     mkpath '.git/dgit';
869     mkdir $ud or die $!;
870 }
871
872 sub mktree_in_ud_from_only_subdir () {
873     # changes into the subdir
874     my (@dirs) = <*/.>;
875     die unless @dirs==1;
876     $dirs[0] =~ m#^([^/]+)/\.$# or die;
877     my $dir = $1;
878     changedir $dir;
879     fail "source package contains .git directory" if stat '.git';
880     die $! unless $!==&ENOENT;
881     runcmd qw(git init -q);
882     rmtree('.git/objects');
883     symlink '../../../../objects','.git/objects' or die $!;
884     runcmd @git, qw(add -Af);
885     my $tree = cmdoutput @git, qw(write-tree);
886     $tree =~ m/^\w+$/ or die "$tree ?";
887     return ($tree,$dir);
888 }
889
890 sub dsc_files_info () {
891     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
892                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
893                        ['Files',           'Digest::MD5', 'new()']) {
894         my ($fname, $module, $method) = @$csumi;
895         my $field = $dsc->{$fname};
896         next unless defined $field;
897         eval "use $module; 1;" or die $@;
898         my @out;
899         foreach (split /\n/, $field) {
900             next unless m/\S/;
901             m/^(\w+) (\d+) (\S+)$/ or
902                 fail "could not parse .dsc $fname line \`$_'";
903             my $digester = eval "$module"."->$method;" or die $@;
904             push @out, {
905                 Hash => $1,
906                 Bytes => $2,
907                 Filename => $3,
908                 Digester => $digester,
909             };
910         }
911         return @out;
912     }
913     fail "missing any supported Checksums-* or Files field in ".
914         $dsc->get_option('name');
915 }
916
917 sub dsc_files () {
918     map { $_->{Filename} } dsc_files_info();
919 }
920
921 sub is_orig_file ($) {
922     local ($_) = @_;
923     m/\.orig(?:-\w+)?\.tar\.\w+$/;
924 }
925
926 sub make_commit ($) {
927     my ($file) = @_;
928     return cmdoutput @git, qw(hash-object -w -t commit), $file;
929 }
930
931 sub clogp_authline ($) {
932     my ($clogp) = @_;
933     my $author = getfield $clogp, 'Maintainer';
934     $author =~ s#,.*##ms;
935     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
936     my $authline = "$author $date";
937     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
938         fail "unexpected commit author line format \`$authline'".
939         " (was generated from changelog Maintainer field)";
940     return $authline;
941 }
942
943 sub generate_commit_from_dsc () {
944     prep_ud();
945     changedir $ud;
946     my @files;
947     foreach my $f (dsc_files()) {
948         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
949         push @files, $f;
950         link "../../../$f", $f
951             or $!==&ENOENT
952             or die "$f $!";
953     }
954     runcmd @dget, qw(--), $dscurl;
955     foreach my $f (grep { is_orig_file($_) } @files) {
956         link $f, "../../../../$f"
957             or $!==&EEXIST
958             or die "$f $!";
959     }
960     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
961     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
962     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
963     my $authline = clogp_authline $clogp;
964     my $changes = getfield $clogp, 'Changes';
965     open C, ">../commit.tmp" or die $!;
966     print C <<END or die $!;
967 tree $tree
968 author $authline
969 committer $authline
970
971 $changes
972
973 # imported from the archive
974 END
975     close C or die $!;
976     my $outputhash = make_commit qw(../commit.tmp);
977     my $cversion = getfield $clogp, 'Version';
978     progress "synthesised git commit from .dsc $cversion";
979     if ($lastpush_hash) {
980         runcmd @git, qw(reset --hard), $lastpush_hash;
981         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
982         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
983         my $oversion = getfield $oldclogp, 'Version';
984         my $vcmp =
985             version_compare_string($oversion, $cversion);
986         if ($vcmp < 0) {
987             # git upload/ is earlier vsn than archive, use archive
988             open C, ">../commit2.tmp" or die $!;
989             print C <<END or die $!;
990 tree $tree
991 parent $lastpush_hash
992 parent $outputhash
993 author $authline
994 committer $authline
995
996 Record $package ($cversion) in archive suite $csuite
997 END
998             $outputhash = make_commit qw(../commit2.tmp);
999         } elsif ($vcmp > 0) {
1000             print STDERR <<END or die $!;
1001
1002 Version actually in archive:    $cversion (older)
1003 Last allegedly pushed/uploaded: $oversion (newer or same)
1004 $later_warning_msg
1005 END
1006             $outputhash = $lastpush_hash;
1007         } else {
1008             $outputhash = $lastpush_hash;
1009         }
1010     }
1011     changedir '../../../..';
1012     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1013             'DGIT_ARCHIVE', $outputhash;
1014     cmdoutput @git, qw(log -n2), $outputhash;
1015     # ... gives git a chance to complain if our commit is malformed
1016     rmtree($ud);
1017     return $outputhash;
1018 }
1019
1020 sub ensure_we_have_orig () {
1021     foreach my $fi (dsc_files_info()) {
1022         my $f = $fi->{Filename};
1023         next unless is_orig_file($f);
1024         if (open F, "<", "../$f") {
1025             $fi->{Digester}->reset();
1026             $fi->{Digester}->addfile(*F);
1027             F->error and die $!;
1028             my $got = $fi->{Digester}->hexdigest();
1029             $got eq $fi->{Hash} or
1030                 fail "existing file $f has hash $got but .dsc".
1031                     " demands hash $fi->{Hash}".
1032                     " (perhaps you should delete this file?)";
1033             progress "using existing $f";
1034             next;
1035         } else {
1036             die "$f $!" unless $!==&ENOENT;
1037         }
1038         my $origurl = $dscurl;
1039         $origurl =~ s{/[^/]+$}{};
1040         $origurl .= "/$f";
1041         die "$f ?" unless $f =~ m/^${package}_/;
1042         die "$f ?" if $f =~ m#/#;
1043         runcmd_ordryrun_local shell_cmd 'cd ..', @dget,'--',$origurl;
1044     }
1045 }
1046
1047 sub rev_parse ($) {
1048     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1049 }
1050
1051 sub is_fast_fwd ($$) {
1052     my ($ancestor,$child) = @_;
1053     my @cmd = (@git, qw(merge-base), $ancestor, $child);
1054     my $mb = cmdoutput_errok @cmd;
1055     if (defined $mb) {
1056         return rev_parse($mb) eq rev_parse($ancestor);
1057     } else {
1058         $?==256 or failedcmd @cmd;
1059         return 0;
1060     }
1061 }
1062
1063 sub git_fetch_us () {
1064     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1065 }
1066
1067 sub fetch_from_archive () {
1068     # ensures that lrref() is what is actually in the archive,
1069     #  one way or another
1070     get_archive_dsc();
1071
1072     if ($dsc) {
1073         foreach my $field (@ourdscfield) {
1074             $dsc_hash = $dsc->{$field};
1075             last if defined $dsc_hash;
1076         }
1077         if (defined $dsc_hash) {
1078             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1079             $dsc_hash = $&;
1080             progress "last upload to archive specified git hash";
1081         } else {
1082             progress "last upload to archive has NO git hash";
1083         }
1084     } else {
1085         progress "no version available from the archive";
1086     }
1087
1088     $lastpush_hash = git_get_ref(lrref());
1089     printdebug "previous reference hash=$lastpush_hash\n";
1090     my $hash;
1091     if (defined $dsc_hash) {
1092         fail "missing remote git history even though dsc has hash -".
1093             " could not find ref ".lrref().
1094             " (should have been fetched from ".access_giturl()."#".rrref().")"
1095             unless $lastpush_hash;
1096         $hash = $dsc_hash;
1097         ensure_we_have_orig();
1098         if ($dsc_hash eq $lastpush_hash) {
1099         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1100             print STDERR <<END or die $!;
1101
1102 Git commit in archive is behind the last version allegedly pushed/uploaded.
1103 Commit referred to by archive:  $dsc_hash
1104 Last allegedly pushed/uploaded: $lastpush_hash
1105 $later_warning_msg
1106 END
1107             $hash = $lastpush_hash;
1108         } else {
1109             fail "archive's .dsc refers to ".$dsc_hash.
1110                 " but this is an ancestor of ".$lastpush_hash;
1111         }
1112     } elsif ($dsc) {
1113         $hash = generate_commit_from_dsc();
1114     } elsif ($lastpush_hash) {
1115         # only in git, not in the archive yet
1116         $hash = $lastpush_hash;
1117         print STDERR <<END or die $!;
1118
1119 Package not found in the archive, but has allegedly been pushed using dgit.
1120 $later_warning_msg
1121 END
1122     } else {
1123         printdebug "nothing found!\n";
1124         if (defined $skew_warning_vsn) {
1125             print STDERR <<END or die $!;
1126
1127 Warning: relevant archive skew detected.
1128 Archive allegedly contains $skew_warning_vsn
1129 But we were not able to obtain any version from the archive or git.
1130
1131 END
1132         }
1133         return 0;
1134     }
1135     printdebug "current hash=$hash\n";
1136     if ($lastpush_hash) {
1137         fail "not fast forward on last upload branch!".
1138             " (archive's version left in DGIT_ARCHIVE)"
1139             unless is_fast_fwd($lastpush_hash, $hash);
1140     }
1141     if (defined $skew_warning_vsn) {
1142         mkpath '.git/dgit';
1143         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1144         my $clogf = ".git/dgit/changelog.tmp";
1145         runcmd shell_cmd "exec >$clogf",
1146             @git, qw(cat-file blob), "$hash:debian/changelog";
1147         my $gotclogp = parsechangelog("-l$clogf");
1148         my $got_vsn = getfield $gotclogp, 'Version';
1149         printdebug "SKEW CHECK GOT $got_vsn\n";
1150         if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
1151             print STDERR <<END or die $!;
1152
1153 Warning: archive skew detected.  Using the available version:
1154 Archive allegedly contains    $skew_warning_vsn
1155 We were able to obtain only   $got_vsn
1156
1157 END
1158         }
1159     }
1160     if ($lastpush_hash ne $hash) {
1161         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1162         if (act_local()) {
1163             cmdoutput @upd_cmd;
1164         } else {
1165             dryrun_report @upd_cmd;
1166         }
1167     }
1168     return 1;
1169 }
1170
1171 sub clone ($) {
1172     my ($dstdir) = @_;
1173     canonicalise_suite();
1174     badusage "dry run makes no sense with clone" unless act_local();
1175     mkdir $dstdir or die "$dstdir $!";
1176     changedir $dstdir;
1177     runcmd @git, qw(init -q);
1178     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1179     open H, "> .git/HEAD" or die $!;
1180     print H "ref: ".lref()."\n" or die $!;
1181     close H or die $!;
1182     runcmd @git, qw(remote add), 'origin', access_giturl();
1183     if (check_for_git()) {
1184         progress "fetching existing git history";
1185         git_fetch_us();
1186         runcmd_ordryrun_local @git, qw(fetch origin);
1187     } else {
1188         progress "starting new git history";
1189     }
1190     fetch_from_archive() or no_such_package;
1191     runcmd @git, qw(reset --hard), lrref();
1192     printdone "ready for work in $dstdir";
1193 }
1194
1195 sub fetch () {
1196     if (check_for_git()) {
1197         git_fetch_us();
1198     }
1199     fetch_from_archive() or no_such_package();
1200     printdone "fetched into ".lrref();
1201 }
1202
1203 sub pull () {
1204     fetch();
1205     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1206         lrref();
1207     printdone "fetched to ".lrref()." and merged into HEAD";
1208 }
1209
1210 sub check_not_dirty () {
1211     return if $ignoredirty;
1212     my @cmd = (@git, qw(diff --quiet HEAD));
1213     printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1214     $!=0; $?=0; system @cmd;
1215     return if !$! && !$?;
1216     if (!$! && $?==256) {
1217         fail "working tree is dirty (does not match HEAD)";
1218     } else {
1219         failedcmd @cmd;
1220     }
1221 }
1222
1223 sub commit_quilty_patch () {
1224     my $output = cmdoutput @git, qw(status --porcelain);
1225     my %adds;
1226     foreach my $l (split /\n/, $output) {
1227         next unless $l =~ m/\S/;
1228         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1229             $adds{$1}++;
1230         }
1231     }
1232     if (!%adds) {
1233         progress "nothing quilty to commit, ok.";
1234         return;
1235     }
1236     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1237     my $m = "Commit Debian 3.0 (quilt) metadata";
1238     progress "$m";
1239     runcmd_ordryrun_local @git, qw(commit -m), $m;
1240 }
1241
1242 sub madformat ($) {
1243     my ($format) = @_;
1244     return 0 unless $format eq '3.0 (quilt)';
1245     progress "Format \`$format', urgh";
1246     if ($noquilt) {
1247         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1248         return 0;
1249     }
1250     return 1;
1251 }
1252
1253 sub push_parse_changelog ($) {
1254     my ($clogpfn) = @_;
1255
1256     my $clogp = Dpkg::Control::Hash->new();
1257     $clogp->load($clogpfn) or die;
1258
1259     $package = getfield $clogp, 'Source';
1260     my $cversion = getfield $clogp, 'Version';
1261     my $tag = debiantag($cversion);
1262     runcmd @git, qw(check-ref-format), $tag;
1263
1264     my $dscfn = dscfn($cversion);
1265
1266     return ($clogp, $cversion, $tag, $dscfn);
1267 }
1268
1269 sub push_parse_dsc ($$$) {
1270     my ($dscfn,$dscfnwhat, $cversion) = @_;
1271     $dsc = parsecontrol($dscfn,$dscfnwhat);
1272     my $dversion = getfield $dsc, 'Version';
1273     my $dscpackage = getfield $dsc, 'Source';
1274     ($dscpackage eq $package && $dversion eq $cversion) or
1275         fail "$dscfn is for $dscpackage $dversion".
1276             " but debian/changelog is for $package $cversion";
1277 }
1278
1279 sub push_mktag ($$$$$$$) {
1280     my ($head,$clogp,$tag,
1281         $dscfn,
1282         $changesfile,$changesfilewhat,
1283         $tfn) = @_;
1284
1285     $dsc->{$ourdscfield[0]} = $head;
1286     $dsc->save("$dscfn.tmp") or die $!;
1287
1288     my $changes = parsecontrol($changesfile,$changesfilewhat);
1289     foreach my $field (qw(Source Distribution Version)) {
1290         $changes->{$field} eq $clogp->{$field} or
1291             fail "changes field $field \`$changes->{$field}'".
1292                 " does not match changelog \`$clogp->{$field}'";
1293     }
1294
1295     my $cversion = getfield $clogp, 'Version';
1296     my $clogsuite = getfield $clogp, 'Distribution';
1297
1298     # We make the git tag by hand because (a) that makes it easier
1299     # to control the "tagger" (b) we can do remote signing
1300     my $authline = clogp_authline $clogp;
1301     open TO, '>', $tfn->('.tmp') or die $!;
1302     print TO <<END or die $!;
1303 object $head
1304 type commit
1305 tag $tag
1306 tagger $authline
1307
1308 $package release $cversion for $clogsuite [dgit]
1309 END
1310     close TO or die $!;
1311
1312     my $tagobjfn = $tfn->('.tmp');
1313     if ($sign) {
1314         if (!defined $keyid) {
1315             $keyid = access_cfg('keyid','RETURN-UNDEF');
1316         }
1317         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1318         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1319         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1320         push @sign_cmd, $tfn->('.tmp');
1321         runcmd_ordryrun @sign_cmd;
1322         if (act_scary()) {
1323             $tagobjfn = $tfn->('.signed.tmp');
1324             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1325                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1326         }
1327     }
1328
1329     return ($tagobjfn);
1330 }
1331
1332 sub sign_changes ($) {
1333     my ($changesfile) = @_;
1334     if ($sign) {
1335         my @debsign_cmd = @debsign;
1336         push @debsign_cmd, "-k$keyid" if defined $keyid;
1337         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1338         push @debsign_cmd, $changesfile;
1339         runcmd_ordryrun @debsign_cmd;
1340     }
1341 }
1342
1343 sub dopush () {
1344     printdebug "actually entering push\n";
1345     prep_ud();
1346
1347     my $clogpfn = ".git/dgit/changelog.822.tmp";
1348     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1349
1350     responder_send_file('parsed-changelog', $clogpfn);
1351
1352     my ($clogp, $cversion, $tag, $dscfn) =
1353         push_parse_changelog("$clogpfn");
1354
1355     my $dscpath = "$buildproductsdir/$dscfn";
1356     stat $dscpath or
1357         fail "looked for .dsc $dscfn, but $!;".
1358             " maybe you forgot to build";
1359
1360     responder_send_file('dsc', $dscpath);
1361
1362     push_parse_dsc($dscpath, $dscfn, $cversion);
1363
1364     my $format = getfield $dsc, 'Format';
1365     printdebug "format $format\n";
1366     if (madformat($format)) {
1367         commit_quilty_patch();
1368     }
1369     check_not_dirty();
1370     changedir $ud;
1371     progress "checking that $dscfn corresponds to HEAD";
1372     runcmd qw(dpkg-source -x --),
1373         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1374     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1375     changedir '../../../..';
1376     my @diffcmd = (@git, qw(diff --exit-code), $tree);
1377     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1378     $!=0; $?=0;
1379     if (system @diffcmd) {
1380         if ($! && $?==256) {
1381             fail "$dscfn specifies a different tree to your HEAD commit;".
1382                 " perhaps you forgot to build";
1383         } else {
1384             failedcmd @diffcmd;
1385         }
1386     }
1387 #fetch from alioth
1388 #do fast forward check and maybe fake merge
1389 #    if (!is_fast_fwd(mainbranch
1390 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1391 #        map { lref($_).":".rref($_) }
1392 #        (uploadbranch());
1393     my $head = rev_parse('HEAD');
1394     if (!$changesfile) {
1395         my $multi = "$buildproductsdir/".
1396             "${package}_".(stripepoch $cversion)."_multi.changes";
1397         if (stat "$multi") {
1398             $changesfile = $multi;
1399         } else {
1400             $!==&ENOENT or die "$multi: $!";
1401             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1402             my @cs = glob "$buildproductsdir/$pat";
1403             fail "failed to find unique changes file".
1404                 " (looked for $pat in $buildproductsdir, or $multi);".
1405                 " perhaps you need to use dgit -C"
1406                 unless @cs==1;
1407             ($changesfile) = @cs;
1408         }
1409     } else {
1410         $changesfile = "$buildproductsdir/$changesfile";
1411     }
1412
1413     responder_send_file('changes',$changesfile);
1414     responder_send_command("param head $head");
1415
1416     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1417     my $tagobjfn;
1418
1419     if ($we_are_responder) {
1420         $tagobjfn = $tfn->('.signed.tmp');
1421         responder_receive_files('signed-tag', $tagobjfn);
1422     } else {
1423         $tagobjfn =
1424             push_mktag($head,$clogp,$tag,
1425                        $dscpath,
1426                        $changesfile,$changesfile,
1427                        $tfn);
1428     }
1429
1430     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1431     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1432     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1433     runcmd_ordryrun @git, qw(tag -v --), $tag;
1434
1435     if (!check_for_git()) {
1436         create_remote_git_repo();
1437     }
1438     runcmd_ordryrun @git, qw(push),access_giturl(),
1439         "HEAD:".rrref(), "refs/tags/$tag";
1440     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1441
1442     if ($we_are_responder) {
1443         my $dryrunsuffix = act_local() ? "" : ".tmp";
1444         responder_receive_files('signed-dsc-changes',
1445                                 "$dscpath$dryrunsuffix",
1446                                 "$changesfile$dryrunsuffix");
1447     } else {
1448         if (act_local()) {
1449             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1450         } else {
1451             progress "[new .dsc left in $dscpath.tmp]";
1452         }
1453         sign_changes $changesfile;
1454     }
1455
1456     my $host = access_cfg('upload-host','RETURN-UNDEF');
1457     my @hostarg = defined($host) ? ($host,) : ();
1458     runcmd_ordryrun @dput, @hostarg, $changesfile;
1459     printdone "pushed and uploaded $cversion";
1460
1461     responder_send_command("complete");
1462 }
1463
1464 sub cmd_clone {
1465     parseopts();
1466     my $dstdir;
1467     badusage "-p is not allowed with clone; specify as argument instead"
1468         if defined $package;
1469     if (@ARGV==1) {
1470         ($package) = @ARGV;
1471     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1472         ($package,$isuite) = @ARGV;
1473     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1474         ($package,$dstdir) = @ARGV;
1475     } elsif (@ARGV==3) {
1476         ($package,$isuite,$dstdir) = @ARGV;
1477     } else {
1478         badusage "incorrect arguments to dgit clone";
1479     }
1480     $dstdir ||= "$package";
1481     clone($dstdir);
1482 }
1483
1484 sub branchsuite () {
1485     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1486     if ($branch =~ m#$lbranch_re#o) {
1487         return $1;
1488     } else {
1489         return undef;
1490     }
1491 }
1492
1493 sub fetchpullargs () {
1494     if (!defined $package) {
1495         my $sourcep = parsecontrol('debian/control','debian/control');
1496         $package = getfield $sourcep, 'Source';
1497     }
1498     if (@ARGV==0) {
1499 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1500         if (!$isuite) {
1501             my $clogp = parsechangelog();
1502             $isuite = getfield $clogp, 'Distribution';
1503         }
1504         canonicalise_suite();
1505         progress "fetching from suite $csuite";
1506     } elsif (@ARGV==1) {
1507         ($isuite) = @ARGV;
1508         canonicalise_suite();
1509     } else {
1510         badusage "incorrect arguments to dgit fetch or dgit pull";
1511     }
1512 }
1513
1514 sub cmd_fetch {
1515     parseopts();
1516     fetchpullargs();
1517     fetch();
1518 }
1519
1520 sub cmd_pull {
1521     parseopts();
1522     fetchpullargs();
1523     pull();
1524 }
1525
1526 sub cmd_push {
1527     parseopts();
1528     badusage "-p is not allowed with dgit push" if defined $package;
1529     check_not_dirty();
1530     my $clogp = parsechangelog();
1531     $package = getfield $clogp, 'Source';
1532     my $specsuite;
1533     if (@ARGV==0) {
1534     } elsif (@ARGV==1) {
1535         ($specsuite) = (@ARGV);
1536     } else {
1537         badusage "incorrect arguments to dgit push";
1538     }
1539     $isuite = getfield $clogp, 'Distribution';
1540     if ($new_package) {
1541         local ($package) = $existing_package; # this is a hack
1542         canonicalise_suite();
1543     }
1544     if (defined $specsuite && $specsuite ne $isuite) {
1545         canonicalise_suite();
1546         $csuite eq $specsuite or
1547             fail "dgit push: changelog specifies $isuite ($csuite)".
1548                 " but command line specifies $specsuite";
1549     }
1550     if (check_for_git()) {
1551         git_fetch_us();
1552     }
1553     if (fetch_from_archive()) {
1554         is_fast_fwd(lrref(), 'HEAD') or
1555             fail "dgit push: HEAD is not a descendant".
1556                 " of the archive's version.\n".
1557                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1558     } else {
1559         $new_package or
1560             fail "package appears to be new in this suite;".
1561                 " if this is intentional, use --new";
1562     }
1563     dopush();
1564 }
1565
1566 #---------- remote commands' implementation ----------
1567
1568 sub cmd_remote_push_responder {
1569     my ($nrargs) = shift @ARGV;
1570     my (@rargs) = @ARGV[0..$nrargs-1];
1571     @ARGV = @ARGV[$nrargs..$#ARGV];
1572     die unless @rargs;
1573     my ($dir) = @rargs;
1574     $debugprefix = ' ';
1575     $we_are_responder = 1;
1576
1577     open PI, "<&STDIN" or die $!;
1578     open STDIN, "/dev/null" or die $!;
1579     open PO, ">&STDOUT" or die $!;
1580     autoflush PO 1;
1581     open STDOUT, ">&STDERR" or die $!;
1582     autoflush STDOUT 1;
1583
1584     responder_send_command("dgit-remote-push-ready");
1585
1586     changedir $dir;
1587     &cmd_push;
1588 }
1589
1590 our $i_tmp;
1591 our $i_child_pid;
1592
1593 sub i_cleanup {
1594     local ($@);
1595     if ($i_child_pid) {
1596         printdebug "(killing remote child $i_child_pid)\n";
1597         kill 15, $i_child_pid;
1598     }
1599     if (defined $i_tmp && !defined $initiator_tempdir) {
1600         changedir "/";
1601         eval { rmtree $i_tmp; };
1602     }
1603 }
1604
1605 END { i_cleanup(); }
1606
1607 sub i_method {
1608     my ($base,$selector,@args) = @_;
1609     $selector =~ s/\-/_/g;
1610     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1611 }
1612
1613 sub cmd_rpush {
1614     my $host = nextarg;
1615     my $dir;
1616     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1617         $host = $1;
1618         $dir = $'; #';
1619     } else {
1620         $dir = nextarg;
1621     }
1622     $dir =~ s{^-}{./-};
1623     my @rargs = ($dir);
1624     my @rdgit;
1625     push @rdgit, @dgit;
1626     push @rdgit, @ropts;
1627     push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1628     push @rdgit, @ARGV;
1629     my @cmd = (@ssh, $host, shellquote @rdgit);
1630     printcmd \*DEBUG,$debugprefix."+",@cmd;
1631
1632     if (defined $initiator_tempdir) {
1633         rmtree $initiator_tempdir;
1634         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1635         $i_tmp = $initiator_tempdir;
1636     } else {
1637         $i_tmp = tempdir();
1638     }
1639     $i_child_pid = open2(\*RO, \*RI, @cmd);
1640     changedir $i_tmp;
1641     initiator_expect { m/^dgit-remote-push-ready/ };
1642     for (;;) {
1643         my ($icmd,$iargs) = initiator_expect {
1644             m/^(\S+)(?: (.*))?$/;
1645             ($1,$2);
1646         };
1647         i_method "i_resp", $icmd, $iargs;
1648     }
1649 }
1650
1651 sub i_resp_progress ($) {
1652     my ($rhs) = @_;
1653     my $msg = protocol_read_bytes \*RO, $rhs;
1654     progress $msg;
1655 }
1656
1657 sub i_resp_complete {
1658     my $pid = $i_child_pid;
1659     $i_child_pid = undef; # prevents killing some other process with same pid
1660     printdebug "waiting for remote child $pid...\n";
1661     my $got = waitpid $pid, 0;
1662     die $! unless $got == $pid;
1663     die "remote child failed $?" if $?;
1664
1665     i_cleanup();
1666     printdebug "all done\n";
1667     exit 0;
1668 }
1669
1670 sub i_resp_file ($) {
1671     my ($keyword) = @_;
1672     my $localname = i_method "i_localname", $keyword;
1673     my $localpath = "$i_tmp/$localname";
1674     stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1675     protocol_receive_file \*RO, $localpath;
1676     i_method "i_file", $keyword;
1677 }
1678
1679 our %i_param;
1680
1681 sub i_resp_param ($) {
1682     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1683     $i_param{$1} = $2;
1684 }
1685
1686 our %i_wanted;
1687
1688 sub i_resp_want ($) {
1689     my ($keyword) = @_;
1690     die "$keyword ?" if $i_wanted{$keyword}++;
1691     my @localpaths = i_method "i_want", $keyword;
1692     printdebug "[[  $keyword @localpaths\n";
1693     foreach my $localpath (@localpaths) {
1694         protocol_send_file \*RI, $localpath;
1695     }
1696     print RI "files-end\n" or die $!;
1697 }
1698
1699 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1700
1701 sub i_localname_parsed_changelog {
1702     return "remote-changelog.822";
1703 }
1704 sub i_file_parsed_changelog {
1705     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1706         push_parse_changelog "$i_tmp/remote-changelog.822";
1707     die if $i_dscfn =~ m#/|^\W#;
1708 }
1709
1710 sub i_localname_dsc {
1711     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1712     return $i_dscfn;
1713 }
1714 sub i_file_dsc { }
1715
1716 sub i_localname_changes {
1717     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1718     $i_changesfn = $i_dscfn;
1719     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1720     return $i_changesfn;
1721 }
1722 sub i_file_changes { }
1723
1724 sub i_want_signed_tag {
1725     printdebug Dumper(\%i_param, $i_dscfn);
1726     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1727         or badproto \*RO, "premature desire for signed-tag";
1728     my $head = $i_param{'head'};
1729     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1730
1731     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1732
1733     my $tagobjfn =
1734         push_mktag $head, $i_clogp, $i_tag,
1735             $i_dscfn,
1736             $i_changesfn, 'remote changes',
1737             sub { "tag$_[0]"; };
1738
1739     return $tagobjfn;
1740 }
1741
1742 sub i_want_signed_dsc_changes {
1743     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1744     sign_changes $i_changesfn;
1745     return ($i_dscfn, $i_changesfn);
1746 }
1747
1748 #---------- building etc. ----------
1749
1750 our $version;
1751 our $sourcechanges;
1752 our $dscfn;
1753
1754 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1755
1756 sub build_maybe_quilt_fixup () {
1757     if (!open F, "debian/source/format") {
1758         die $! unless $!==&ENOENT;
1759         return;
1760     }
1761     $_ = <F>;
1762     F->error and die $!;
1763     chomp;
1764     return unless madformat($_);
1765     # sigh
1766     
1767     my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1768     my $problems = cmdoutput @cmd;
1769     if (length $problems) {
1770         print STDERR "problematic files:\n";
1771         print STDERR "  $_\n" foreach split /\n/, $problems;
1772         fail "Cannot do quilt fixup in tree containing ignored files.  ".
1773             "Perhaps your package's clean target is broken, in which".
1774             " case -wg (which says to use git-clean -xdf) may help.";
1775     }
1776
1777     my $clogp = parsechangelog();
1778     my $version = getfield $clogp, 'Version';
1779     my $author = getfield $clogp, 'Maintainer';
1780     my $headref = rev_parse('HEAD');
1781     my $time = time;
1782     my $ncommits = 3;
1783     my $patchname = "auto-$version-$headref-$time";
1784     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1785     mkpath '.git/dgit';
1786     my $descfn = ".git/dgit/quilt-description.tmp";
1787     open O, '>', $descfn or die "$descfn: $!";
1788     $msg =~ s/\n/\n /g;
1789     $msg =~ s/^\s+$/ ./mg;
1790     print O <<END or die $!;
1791 Description: Automatically generated patch ($clogp->{Version})
1792  Last (up to) $ncommits git changes, FYI:
1793  .
1794  $msg
1795 Author: $author
1796
1797 ---
1798
1799 END
1800     close O or die $!;
1801     {
1802         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1803         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1804         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1805         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1806     }
1807
1808     if (!open P, '>>', ".pc/applied-patches") {
1809         $!==&ENOENT or die $!;
1810     } else {
1811         close P;
1812     }
1813
1814     commit_quilty_patch();
1815 }
1816
1817 sub quilt_fixup_editor () {
1818     my $descfn = $ENV{$fakeeditorenv};
1819     my $editing = $ARGV[$#ARGV];
1820     open I1, '<', $descfn or die "$descfn: $!";
1821     open I2, '<', $editing or die "$editing: $!";
1822     unlink $editing or die "$editing: $!";
1823     open O, '>', $editing or die "$editing: $!";
1824     while (<I1>) { print O or die $!; } I1->error and die $!;
1825     my $copying = 0;
1826     while (<I2>) {
1827         $copying ||= m/^\-\-\- /;
1828         next unless $copying;
1829         print O or die $!;
1830     }
1831     I2->error and die $!;
1832     close O or die $1;
1833     exit 0;
1834 }
1835
1836 sub clean_tree () {
1837     if ($cleanmode eq 'dpkg-source') {
1838         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
1839     } elsif ($cleanmode eq 'git') {
1840         runcmd_ordryrun_local @git, qw(clean -xdf);
1841     } elsif ($cleanmode eq 'none') {
1842     } else {
1843         die "$cleanmode ?";
1844     }
1845 }
1846
1847 sub build_prep () {
1848     badusage "-p is not allowed when building" if defined $package;
1849     check_not_dirty();
1850     clean_tree();
1851     my $clogp = parsechangelog();
1852     $isuite = getfield $clogp, 'Distribution';
1853     $package = getfield $clogp, 'Source';
1854     $version = getfield $clogp, 'Version';
1855     build_maybe_quilt_fixup();
1856 }
1857
1858 sub changesopts () {
1859     my @opts =@changesopts[1..$#changesopts];
1860     if (!defined $changes_since_version) {
1861         my @vsns = archive_query('archive_query');
1862         my @quirk = access_quirk();
1863         if ($quirk[0] eq 'backports') {
1864             local $isuite = $quirk[2];
1865             local $csuite;
1866             canonicalise_suite();
1867             push @vsns, archive_query('archive_query');
1868         }
1869         if (@vsns) {
1870             @vsns = map { $_->[0] } @vsns;
1871             @vsns = sort { -version_compare_string($a, $b) } @vsns;
1872             $changes_since_version = $vsns[0];
1873             progress "changelog will contain changes since $vsns[0]";
1874         } else {
1875             $changes_since_version = '_';
1876             progress "package seems new, not specifying -v<version>";
1877         }
1878     }
1879     if ($changes_since_version ne '_') {
1880         unshift @opts, "-v$changes_since_version";
1881     }
1882     return @opts;
1883 }
1884
1885 sub cmd_build {
1886     build_prep();
1887     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1888     printdone "build successful\n";
1889 }
1890
1891 sub cmd_git_build {
1892     build_prep();
1893     my @cmd =
1894         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1895          "--git-builder=@dpkgbuildpackage");
1896     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1897         canonicalise_suite();
1898         push @cmd, "--git-debian-branch=".lbranch();
1899     }
1900     push @cmd, changesopts();
1901     runcmd_ordryrun_local @cmd, @ARGV;
1902     printdone "build successful\n";
1903 }
1904
1905 sub build_source {
1906     build_prep();
1907     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1908     $dscfn = dscfn($version);
1909     if ($cleanmode eq 'dpkg-source') {
1910         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
1911             changesopts();
1912     } else {
1913         my $pwd = cmdoutput qw(env - pwd);
1914         my $leafdir = basename $pwd;
1915         changedir "..";
1916         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
1917         changedir $pwd;
1918         runcmd_ordryrun_local qw(sh -ec),
1919             'exec >$1; shift; exec "$@"','x',
1920             "../$sourcechanges",
1921             @dpkggenchanges, qw(-S), changesopts();
1922     }
1923 }
1924
1925 sub cmd_build_source {
1926     badusage "build-source takes no additional arguments" if @ARGV;
1927     build_source();
1928     printdone "source built, results in $dscfn and $sourcechanges";
1929 }
1930
1931 sub cmd_sbuild {
1932     build_source();
1933     changedir "..";
1934     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1935     if (act_local()) {
1936         stat $dscfn or fail "$dscfn (in parent directory): $!";
1937         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1938         foreach my $cf (glob $pat) {
1939             next if $cf eq $sourcechanges;
1940             unlink $cf or fail "remove $cf: $!";
1941         }
1942     }
1943     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1944     my @changesfiles = glob $pat;
1945     @changesfiles = sort {
1946         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
1947             or $a cmp $b
1948     } @changesfiles;
1949     fail "wrong number of different changes files (@changesfiles)"
1950         unless @changesfiles;
1951     runcmd_ordryrun_local @mergechanges, @changesfiles;
1952     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1953     if (act_local()) {
1954         stat $multichanges or fail "$multichanges: $!";
1955     }
1956     printdone "build successful, results in $multichanges\n" or die $!;
1957 }    
1958
1959 sub cmd_quilt_fixup {
1960     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1961     my $clogp = parsechangelog();
1962     $version = getfield $clogp, 'Version';
1963     build_maybe_quilt_fixup();
1964 }
1965
1966 #---------- argument parsing and main program ----------
1967
1968 sub cmd_version {
1969     print "dgit version $our_version\n" or die $!;
1970     exit 0;
1971 }
1972
1973 sub parseopts () {
1974     my $om;
1975
1976     if (defined $ENV{'DGIT_SSH'}) {
1977         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1978     } elsif (defined $ENV{'GIT_SSH'}) {
1979         @ssh = ($ENV{'GIT_SSH'});
1980     }
1981
1982     while (@ARGV) {
1983         last unless $ARGV[0] =~ m/^-/;
1984         $_ = shift @ARGV;
1985         last if m/^--?$/;
1986         if (m/^--/) {
1987             if (m/^--dry-run$/) {
1988                 push @ropts, $_;
1989                 $dryrun_level=2;
1990             } elsif (m/^--damp-run$/) {
1991                 push @ropts, $_;
1992                 $dryrun_level=1;
1993             } elsif (m/^--no-sign$/) {
1994                 push @ropts, $_;
1995                 $sign=0;
1996             } elsif (m/^--help$/) {
1997                 cmd_help();
1998             } elsif (m/^--version$/) {
1999                 cmd_version();
2000             } elsif (m/^--new$/) {
2001                 push @ropts, $_;
2002                 $new_package=1;
2003             } elsif (m/^--since-version=([^_]+|_)$/) {
2004                 push @ropts, $_;
2005                 $changes_since_version = $1;
2006             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2007                      ($om = $opts_opt_map{$1}) &&
2008                      length $om->[0]) {
2009                 push @ropts, $_;
2010                 $om->[0] = $2;
2011             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2012                      !$opts_opt_cmdonly{$1} &&
2013                      ($om = $opts_opt_map{$1})) {
2014                 push @ropts, $_;
2015                 push @$om, $2;
2016             } elsif (m/^--existing-package=(.*)/s) {
2017                 push @ropts, $_;
2018                 $existing_package = $1;
2019             } elsif (m/^--initiator-tempdir=(.*)/s) {
2020                 $initiator_tempdir = $1;
2021                 $initiator_tempdir =~ m#^/# or
2022                     badusage "--initiator-tempdir must be used specify an".
2023                         " absolute, not relative, directory."
2024             } elsif (m/^--distro=(.*)/s) {
2025                 push @ropts, $_;
2026                 $idistro = $1;
2027             } elsif (m/^--build-products-dir=(.*)/s) {
2028                 push @ropts, $_;
2029                 $buildproductsdir = $1;
2030             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2031                 push @ropts, $_;
2032                 $cleanmode = $1;
2033             } elsif (m/^--clean=(.*)$/s) {
2034                 badusage "unknown cleaning mode \`$1'";
2035             } elsif (m/^--ignore-dirty$/s) {
2036                 push @ropts, $_;
2037                 $ignoredirty = 1;
2038             } elsif (m/^--no-quilt-fixup$/s) {
2039                 push @ropts, $_;
2040                 $noquilt = 1;
2041             } else {
2042                 badusage "unknown long option \`$_'";
2043             }
2044         } else {
2045             while (m/^-./s) {
2046                 if (s/^-n/-/) {
2047                     push @ropts, $&;
2048                     $dryrun_level=2;
2049                 } elsif (s/^-L/-/) {
2050                     push @ropts, $&;
2051                     $dryrun_level=1;
2052                 } elsif (s/^-h/-/) {
2053                     cmd_help();
2054                 } elsif (s/^-D/-/) {
2055                     push @ropts, $&;
2056                     open DEBUG, ">&STDERR" or die $!;
2057                     autoflush DEBUG 1;
2058                     $debug++;
2059                 } elsif (s/^-N/-/) {
2060                     push @ropts, $&;
2061                     $new_package=1;
2062                 } elsif (s/^-v([^_]+|_)$//s) {
2063                     push @ropts, $&;
2064                     $changes_since_version = $1;
2065                 } elsif (m/^-m/) {
2066                     push @ropts, $&;
2067                     push @changesopts, $_;
2068                     $_ = '';
2069                 } elsif (s/^-c(.*=.*)//s) {
2070                     push @ropts, $&;
2071                     push @git, '-c', $1;
2072                 } elsif (s/^-d(.*)//s) {
2073                     push @ropts, $&;
2074                     $idistro = $1;
2075                 } elsif (s/^-C(.*)//s) {
2076                     push @ropts, $&;
2077                     $changesfile = $1;
2078                     if ($changesfile =~ s#^(.*)/##) {
2079                         $buildproductsdir = $1;
2080                     }
2081                 } elsif (s/^-k(.*)//s) {
2082                     $keyid=$1;
2083                 } elsif (s/^-wn//s) {
2084                     push @ropts, $&;
2085                     $cleanmode = 'none';
2086                 } elsif (s/^-wg//s) {
2087                     push @ropts, $&;
2088                     $cleanmode = 'git';
2089                 } elsif (s/^-wd//s) {
2090                     push @ropts, $&;
2091                     $cleanmode = 'dpkg-source';
2092                 } else {
2093                     badusage "unknown short option \`$_'";
2094                 }
2095             }
2096         }
2097     }
2098 }
2099
2100 if ($ENV{$fakeeditorenv}) {
2101     quilt_fixup_editor();
2102 }
2103
2104 delete $ENV{'DGET_UNPACK'};
2105
2106 parseopts();
2107 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2108 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2109     if $dryrun_level == 1;
2110 if (!@ARGV) {
2111     print STDERR $helpmsg or die $!;
2112     exit 8;
2113 }
2114 my $cmd = shift @ARGV;
2115 $cmd =~ y/-/_/;
2116 { no strict qw(refs); &{"cmd_$cmd"}(); }