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