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