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