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