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