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