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