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