chiark / gitweb /
test-dummy-drs `distro': for testing dgit-push-responder. WIP.
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013 Ian Jackson
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 use strict;
21
22 use IO::Handle;
23 use Data::Dumper;
24 use LWP::UserAgent;
25 use Dpkg::Control::Hash;
26 use File::Path;
27 use File::Temp qw(tempdir);
28 use File::Basename;
29 use Dpkg::Version;
30 use POSIX;
31 use IPC::Open2;
32
33 our $our_version = 'UNRELEASED'; ###substituted###
34
35 our $isuite = 'unstable';
36 our $idistro;
37 our $package;
38 our @ropts;
39
40 our $sign = 1;
41 our $dryrun_level = 0;
42 our $changesfile;
43 our $buildproductsdir = '..';
44 our $new_package = 0;
45 our $ignoredirty = 0;
46 our $noquilt = 0;
47 our $existing_package = 'dpkg';
48 our $cleanmode = 'dpkg-source';
49 our $changes_since_version;
50 our $we_are_responder;
51 our $initiator_tempdir;
52
53 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
54
55 our (@git) = qw(git);
56 our (@dget) = qw(dget);
57 our (@dput) = qw(dput);
58 our (@debsign) = qw(debsign);
59 our (@gpg) = qw(gpg);
60 our (@sbuild) = qw(sbuild -A);
61 our (@ssh) = 'ssh';
62 our (@dgit) = qw(dgit);
63 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
64 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
65 our (@dpkggenchanges) = qw(dpkg-genchanges);
66 our (@mergechanges) = qw(mergechanges -f);
67 our (@changesopts) = ('');
68
69 our %opts_opt_map = ('dget' => \@dget,
70                      'dput' => \@dput,
71                      'debsign' => \@debsign,
72                      'gpg' => \@gpg,
73                      'sbuild' => \@sbuild,
74                      'ssh' => \@ssh,
75                      'dgit' => \@dgit,
76                      'dpkg-source' => \@dpkgsource,
77                      'dpkg-buildpackage' => \@dpkgbuildpackage,
78                      'dpkg-genchanges' => \@dpkggenchanges,
79                      'ch' => \@changesopts,
80                      'mergechanges' => \@mergechanges);
81
82 our %opts_opt_cmdonly = ('gpg' => 1);
83
84 our $keyid;
85
86 our $debug = 0;
87 open DEBUG, ">/dev/null" or die $!;
88
89 autoflush STDOUT 1;
90
91 our $remotename = 'dgit';
92 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
93 our $branchprefix = 'dgit';
94 our $csuite;
95
96 sub lbranch () { return "$branchprefix/$csuite"; }
97 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
98 sub lref () { return "refs/heads/".lbranch(); }
99 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
100 sub rrref () { return "refs/$branchprefix/$csuite"; }
101 sub debiantag ($) { 
102     my ($v) = @_;
103     $v =~ y/~:/_%/;
104     return "debian/$v";
105 }
106
107 sub stripepoch ($) {
108     my ($vsn) = @_;
109     $vsn =~ s/^\d+\://;
110     return $vsn;
111 }
112
113 sub dscfn ($) {
114     my ($vsn) = @_;
115     return "${package}_".(stripepoch $vsn).".dsc";
116 }
117
118 our $us = 'dgit';
119 our $debugprefix = '';
120
121 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
122
123 sub fail { 
124     die $us.($we_are_responder ? " (build host)" : "").": @_\n";
125 }
126
127 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
128
129 sub no_such_package () {
130     print STDERR "$us: package $package does not exist in suite $isuite\n";
131     exit 4;
132 }
133
134 sub fetchspec () {
135     local $csuite = '*';
136     return  "+".rrref().":".lrref();
137 }
138
139 sub changedir ($) {
140     my ($newdir) = @_;
141     printdebug "CD $newdir\n";
142     chdir $newdir or die "chdir: $newdir: $!";
143 }
144
145 #---------- remote protocol support, common ----------
146
147 # remote push initiator/responder protocol:
148 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
149 #
150 #  > file parsed-changelog
151 #  [indicates that output of dpkg-parsechangelog follows]
152 #  > data-block NBYTES
153 #  > [NBYTES bytes of data (no newline)]
154 #  [maybe some more blocks]
155 #  > data-end
156 #
157 #  > file dsc
158 #  [etc]
159 #
160 #  > file changes
161 #  [etc]
162 #
163 #  > param head HEAD
164 #
165 #  > want signed-tag
166 #  [indicates that signed tag is wanted]
167 #  < data-block NBYTES
168 #  < [NBYTES bytes of data (no newline)]
169 #  [maybe some more blocks]
170 #  < data-end
171 #  < files-end
172 #
173 #  > want signed-dsc-changes
174 #  < data-block NBYTES    [transfer of signed dsc]
175 #  [etc]
176 #  < data-block NBYTES    [transfer of signed changes]
177 #  [etc]
178 #  < files-end
179 #
180 #  > complete
181
182 sub badproto ($$) {
183     my ($fh, $m) = @_;
184     fail "connection lost: $!" if $fh->error;
185     fail "protocol violation; $m not expected";
186 }
187
188 sub protocol_expect (&$) {
189     my ($match, $fh) = @_;
190     local $_;
191     $_ = <$fh>;
192     defined && chomp or badproto $fh, "eof";
193     if (wantarray) {
194         my @r = &$match;
195         return @r if @r;
196     } else {
197         my $r = &$match;
198         return $r if $r;
199     }
200     badproto $fh, "\`$_'";
201 }
202
203 sub protocol_send_file ($$) {
204     my ($fh, $ourfn) = @_;
205     open PF, "<", $ourfn or die "$ourfn: $!";
206     for (;;) {
207         my $d;
208         my $got = read PF, $d, 65536;
209         die "$ourfn: $!" unless defined $got;
210         last if !$got;
211         print $fh "data-block ".length($d)."\n" or die $!;
212         print $fh $d or die $!;
213     }
214     PF->error and die "$ourfn $!";
215     print $fh "data-end\n" or die $!;
216     close PF;
217 }
218
219 sub protocol_read_bytes ($$) {
220     my ($fh, $nbytes) = @_;
221     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
222     my $d;
223     my $got = read $fh, $d, $nbytes;
224     $got==$nbytes or badproto $fh, "eof during data block";
225     return $d;
226 }
227
228 sub protocol_receive_file ($$) {
229     my ($fh, $ourfn) = @_;
230     printdebug "() $ourfn\n";
231     open PF, ">", $ourfn or die "$ourfn: $!";
232     for (;;) {
233         my ($y,$l) = protocol_expect {
234             m/^data-block (.*)$/ ? (1,$1) :
235             m/^data-end$/ ? (0,) :
236             ();
237         } $fh;
238         last unless $y;
239         my $d = protocol_read_bytes $fh, $l;
240         print PF $d or die $!;
241     }
242     close PF or die $!;
243 }
244
245 #---------- remote protocol support, responder ----------
246
247 sub responder_send_command ($) {
248     my ($command) = @_;
249     return unless $we_are_responder;
250     # called even without $we_are_responder
251     printdebug ">> $command\n";
252     print PO $command, "\n" or die $!;
253 }    
254
255 sub responder_send_file ($$) {
256     my ($keyword, $ourfn) = @_;
257     return unless $we_are_responder;
258     printdebug "]] $keyword $ourfn\n";
259     responder_send_command "file $keyword";
260     protocol_send_file \*PO, $ourfn;
261 }
262
263 sub responder_receive_files ($@) {
264     my ($keyword, @ourfns) = @_;
265     die unless $we_are_responder;
266     printdebug "[[ $keyword @ourfns\n";
267     responder_send_command "want $keyword";
268     foreach my $fn (@ourfns) {
269         protocol_receive_file \*PI, $fn;
270     }
271     printdebug "[[\$\n";
272     protocol_expect { m/^files-end$/ } \*PI;
273 }
274
275 #---------- remote protocol support, initiator ----------
276
277 sub initiator_expect (&) {
278     my ($match) = @_;
279     protocol_expect { &$match } \*RO;
280 }
281
282 #---------- end remote code ----------
283
284 sub progress {
285     if ($we_are_responder) {
286         my $m = join '', @_;
287         responder_send_command "progress ".length($m) or die $!;
288         print PO $m or die $!;
289     } else {
290         print @_, "\n";
291     }
292 }
293
294 our $ua;
295
296 sub url_get {
297     if (!$ua) {
298         $ua = LWP::UserAgent->new();
299         $ua->env_proxy;
300     }
301     my $what = $_[$#_];
302     progress "downloading $what...";
303     my $r = $ua->get(@_) or die $!;
304     return undef if $r->code == 404;
305     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
306     return $r->decoded_content();
307 }
308
309 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
310
311 sub shellquote {
312     my @out;
313     local $_;
314     foreach my $a (@_) {
315         $_ = $a;
316         if (m{[^-=_./0-9a-z]}i) {
317             s{['\\]}{'\\$&'}g;
318             push @out, "'$_'";
319         } else {
320             push @out, $_;
321         }
322     }
323     return join ' ', @out;
324 }
325
326 sub printcmd {
327     my $fh = shift @_;
328     my $intro = shift @_;
329     print $fh $intro," " or die $!;
330     print $fh shellquote @_ or die $!;
331     print $fh "\n" or die $!;
332 }
333
334 sub failedcmd {
335     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
336     if ($!) {
337         fail "failed to fork/exec: $!";
338     } elsif (!($? & 0xff)) {
339         fail "subprocess failed with error exit status ".($?>>8);
340     } elsif ($?) {
341         fail "subprocess crashed (wait status $?)";
342     } else {
343         fail "subprocess produced invalid output";
344     }
345 }
346
347 sub runcmd {
348     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
349     $!=0; $?=0;
350     failedcmd @_ if system @_;
351 }
352
353 sub act_local () { return $dryrun_level <= 1; }
354 sub act_scary () { return !$dryrun_level; }
355
356 sub printdone {
357     if (!$dryrun_level) {
358         progress "dgit ok: @_";
359     } else {
360         progress "would be ok: @_ (but dry run only)";
361     }
362 }
363
364 sub cmdoutput_errok {
365     die Dumper(\@_)." ?" if grep { !defined } @_;
366     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
367     open P, "-|", @_ or die $!;
368     my $d;
369     $!=0; $?=0;
370     { local $/ = undef; $d = <P>; }
371     die $! if P->error;
372     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
373     chomp $d;
374     $d =~ m/^.*/;
375     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
376     return $d;
377 }
378
379 sub cmdoutput {
380     my $d = cmdoutput_errok @_;
381     defined $d or failedcmd @_;
382     return $d;
383 }
384
385 sub dryrun_report {
386     printcmd(\*STDERR,$debugprefix."#",@_);
387 }
388
389 sub runcmd_ordryrun {
390     if (act_scary()) {
391         runcmd @_;
392     } else {
393         dryrun_report @_;
394     }
395 }
396
397 sub runcmd_ordryrun_local {
398     if (act_local()) {
399         runcmd @_;
400     } else {
401         dryrun_report @_;
402     }
403 }
404
405 sub shell_cmd {
406     my ($first_shell, @cmd) = @_;
407     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
408 }
409
410 our $helpmsg = <<END;
411 main usages:
412   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
413   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
414   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
415   dgit [dgit-opts] push [dgit-opts] [suite]
416   dgit [dgit-opts] rpush build-host:build-dir ...
417 important dgit options:
418   -k<keyid>           sign tag and package with <keyid> instead of default
419   --dry-run -n        do not change anything, but go through the motions
420   --damp-run -L       like --dry-run but make local changes, without signing
421   --new -N            allow introducing a new package
422   --debug -D          increase debug level
423   -c<name>=<value>    set git config option (used directly by dgit too)
424 END
425
426 our $later_warning_msg = <<END;
427 Perhaps the upload is stuck in incoming.  Using the version from git.
428 END
429
430 sub badusage {
431     print STDERR "$us: @_\n", $helpmsg or die $!;
432     exit 8;
433 }
434
435 sub nextarg {
436     @ARGV or badusage "too few arguments";
437     return scalar shift @ARGV;
438 }
439
440 sub cmd_help () {
441     print $helpmsg or die $!;
442     exit 0;
443 }
444
445 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
446
447 our %defcfg = ('dgit.default.distro' => 'debian',
448                'dgit.default.username' => '',
449                'dgit.default.archive-query-default-component' => 'main',
450                'dgit.default.ssh' => 'ssh',
451                'dgit-distro.debian.git-host' => 'git.debian.org',
452                'dgit-distro.debian.git-proto' => 'git+ssh://',
453                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
454                'dgit-distro.debian.git-check' => 'ssh-cmd',
455                'dgit-distro.debian.git-create' => 'ssh-cmd',
456                'dgit-distro.debian.sshpsql-host' => 'coccia.debian.org',
457                'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
458                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
459                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
460  'dgit-distro.debian.backports-quirk' => '%-backports*',
461  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
462                'dgit-distro.test-dummy.ssh' => "$td/ssh",
463                'dgit-distro.test-dummy.username' => "alice",
464                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
465                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
466                'dgit-distro.test-dummy.git-url' => "$td/git",
467                'dgit-distro.test-dummy.git-host' => "git",
468                'dgit-distro.test-dummy.git-path' => "$td/git",
469                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
470                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
471                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
472                'dgit-distro.test-dummy-drs.ssh' => "$td/ssh",
473                'dgit-distro.test-dummy-drs.username' => "alice",
474                'dgit-distro.test-dummy-drs.git-check' => "true",
475                'dgit-distro.test-dummy-drs.git-create' => "true",
476                'dgit-distro.test-dummy-drs.git-url' => "$td/git",
477                'dgit-distro.test-dummy-drs.archive-query' => "dummycat:$td/aq",
478                'dgit-distro.test-dummy-drs.mirror' => "file://$td/mirror/",
479                'dgit-distro.test-dummy-drs.upload-host' => 'test-dummy',
480                );
481
482 sub cfg {
483     foreach my $c (@_) {
484         return undef if $c =~ /RETURN-UNDEF/;
485         my @cmd = (@git, qw(config --), $c);
486         my $v;
487         {
488             local ($debug) = $debug-1;
489             $v = cmdoutput_errok @cmd;
490         };
491         if ($?==0) {
492             return $v;
493         } elsif ($?!=256) {
494             failedcmd @cmd;
495         }
496         my $dv = $defcfg{$c};
497         return $dv if defined $dv;
498     }
499     badcfg "need value for one of: @_";
500 }
501
502 sub access_basedistro () {
503     return cfg("dgit-suite.$isuite.distro",
504                "dgit.default.distro");
505 }
506
507 sub access_quirk () {
508     # returns (quirk name, distro to use instead, quirk-specific info)
509     my $basedistro = access_basedistro();
510     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
511                               'RETURN-UNDEF');
512     if (defined $backports_quirk) {
513         my $re = $backports_quirk;
514         $re =~ s/[^-0-9a-z_\%*]/\\$&/ig;
515         $re =~ s/\*/.*/g;
516         $re =~ s/\%/([-0-9a-z_]+)/ or badcfg "backports-quirk needs \%";
517         if ($isuite =~ m/^$re$/) {
518             return ('backports',"$basedistro-backports",$1);
519         }
520     }
521     return ('none',$basedistro);
522 }
523
524 sub access_distro () {
525     return (access_quirk())[1];
526 }
527
528 sub access_cfg (@) {
529     my (@keys) = @_;
530     my $basedistro = access_basedistro();
531     my $distro = $idistro || access_distro();
532     my $value = cfg(map {
533         ("dgit-distro.$distro.$_",
534          "dgit-distro.$basedistro.$_",
535          "dgit.default.$_")
536                     } @keys);
537     return $value;
538 }
539
540 sub string_to_ssh ($) {
541     my ($spec) = @_;
542     if ($spec =~ m/\s/) {
543         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
544     } else {
545         return ($spec);
546     }
547 }
548
549 sub access_cfg_ssh () {
550     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
551     if (!defined $gitssh) {
552         return @ssh;
553     } else {
554         return string_to_ssh $gitssh;
555     }
556 }
557
558 sub access_someuserhost ($) {
559     my ($some) = @_;
560     my $user = access_cfg("$some-user",'username');
561     my $host = access_cfg("$some-host");
562     return length($user) ? "$user\@$host" : $host;
563 }
564
565 sub access_gituserhost () {
566     return access_someuserhost('git');
567 }
568
569 sub access_giturl () {
570     my $url = access_cfg('git-url','RETURN-UNDEF');
571     if (!defined $url) {
572         $url =
573             access_cfg('git-proto').
574             access_gituserhost().
575             access_cfg('git-path');
576     }
577     return "$url/$package.git";
578 }              
579
580 sub parsecontrolfh ($$@) {
581     my ($fh, $desc, @opts) = @_;
582     my %opts = ('name' => $desc, @opts);
583     my $c = Dpkg::Control::Hash->new(%opts);
584     $c->parse($fh) or die "parsing of $desc failed";
585     return $c;
586 }
587
588 sub parsecontrol {
589     my ($file, $desc) = @_;
590     my $fh = new IO::Handle;
591     open $fh, '<', $file or die "$file: $!";
592     my $c = parsecontrolfh($fh,$desc);
593     $fh->error and die $!;
594     close $fh;
595     return $c;
596 }
597
598 sub getfield ($$) {
599     my ($dctrl,$field) = @_;
600     my $v = $dctrl->{$field};
601     return $v if defined $v;
602     fail "missing field $field in ".$v->get_option('name');
603 }
604
605 sub parsechangelog {
606     my $c = Dpkg::Control::Hash->new();
607     my $p = new IO::Handle;
608     my @cmd = (qw(dpkg-parsechangelog), @_);
609     open $p, '-|', @cmd or die $!;
610     $c->parse($p);
611     $?=0; $!=0; close $p or failedcmd @cmd;
612     return $c;
613 }
614
615 sub git_get_ref ($) {
616     my ($refname) = @_;
617     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
618     if (!defined $got) {
619         $?==256 or fail "git show-ref failed (status $?)";
620         printdebug "ref $refname= [show-ref exited 1]\n";
621         return '';
622     }
623     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
624         printdebug "ref $refname=$1\n";
625         return $1;
626     } else {
627         printdebug "ref $refname= [no match]\n";
628         return '';
629     }
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 [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
1423     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1424     my $tagobjfn;
1425
1426     if ($we_are_responder) {
1427         $tagobjfn = $tfn->('.signed.tmp');
1428         responder_receive_files('signed-tag', $tagobjfn);
1429     } else {
1430         $tagobjfn =
1431             push_mktag($head,$clogp,$tag,
1432                        $dscpath,
1433                        $changesfile,$changesfile,
1434                        $tfn);
1435     }
1436
1437     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1438     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1439     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1440     runcmd_ordryrun @git, qw(tag -v --), $tag;
1441
1442     if (!check_for_git()) {
1443         create_remote_git_repo();
1444     }
1445     runcmd_ordryrun @git, qw(push),access_giturl(),
1446         "HEAD:".rrref(), "refs/tags/$tag";
1447     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1448
1449     if ($we_are_responder) {
1450         my $dryrunsuffix = act_local() ? "" : ".tmp";
1451         responder_receive_files('signed-dsc-changes',
1452                                 "$dscpath$dryrunsuffix",
1453                                 "$changesfile$dryrunsuffix");
1454     } else {
1455         if (act_local()) {
1456             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1457         } else {
1458             progress "[new .dsc left in $dscpath.tmp]";
1459         }
1460         sign_changes $changesfile;
1461     }
1462
1463     my $host = access_cfg('upload-host','RETURN-UNDEF');
1464     my @hostarg = defined($host) ? ($host,) : ();
1465     runcmd_ordryrun @dput, @hostarg, $changesfile;
1466     printdone "pushed and uploaded $cversion";
1467
1468     responder_send_command("complete");
1469 }
1470
1471 sub cmd_clone {
1472     parseopts();
1473     my $dstdir;
1474     badusage "-p is not allowed with clone; specify as argument instead"
1475         if defined $package;
1476     if (@ARGV==1) {
1477         ($package) = @ARGV;
1478     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1479         ($package,$isuite) = @ARGV;
1480     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1481         ($package,$dstdir) = @ARGV;
1482     } elsif (@ARGV==3) {
1483         ($package,$isuite,$dstdir) = @ARGV;
1484     } else {
1485         badusage "incorrect arguments to dgit clone";
1486     }
1487     $dstdir ||= "$package";
1488     clone($dstdir);
1489 }
1490
1491 sub branchsuite () {
1492     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1493     if ($branch =~ m#$lbranch_re#o) {
1494         return $1;
1495     } else {
1496         return undef;
1497     }
1498 }
1499
1500 sub fetchpullargs () {
1501     if (!defined $package) {
1502         my $sourcep = parsecontrol('debian/control','debian/control');
1503         $package = getfield $sourcep, 'Source';
1504     }
1505     if (@ARGV==0) {
1506 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1507         if (!$isuite) {
1508             my $clogp = parsechangelog();
1509             $isuite = getfield $clogp, 'Distribution';
1510         }
1511         canonicalise_suite();
1512         progress "fetching from suite $csuite";
1513     } elsif (@ARGV==1) {
1514         ($isuite) = @ARGV;
1515         canonicalise_suite();
1516     } else {
1517         badusage "incorrect arguments to dgit fetch or dgit pull";
1518     }
1519 }
1520
1521 sub cmd_fetch {
1522     parseopts();
1523     fetchpullargs();
1524     fetch();
1525 }
1526
1527 sub cmd_pull {
1528     parseopts();
1529     fetchpullargs();
1530     pull();
1531 }
1532
1533 sub cmd_push {
1534     parseopts();
1535     badusage "-p is not allowed with dgit push" if defined $package;
1536     check_not_dirty();
1537     my $clogp = parsechangelog();
1538     $package = getfield $clogp, 'Source';
1539     my $specsuite;
1540     if (@ARGV==0) {
1541     } elsif (@ARGV==1) {
1542         ($specsuite) = (@ARGV);
1543     } else {
1544         badusage "incorrect arguments to dgit push";
1545     }
1546     $isuite = getfield $clogp, 'Distribution';
1547     if ($new_package) {
1548         local ($package) = $existing_package; # this is a hack
1549         canonicalise_suite();
1550     }
1551     if (defined $specsuite && $specsuite ne $isuite) {
1552         canonicalise_suite();
1553         $csuite eq $specsuite or
1554             fail "dgit push: changelog specifies $isuite ($csuite)".
1555                 " but command line specifies $specsuite";
1556     }
1557     if (check_for_git()) {
1558         git_fetch_us();
1559     }
1560     if (fetch_from_archive()) {
1561         is_fast_fwd(lrref(), 'HEAD') or
1562             fail "dgit push: HEAD is not a descendant".
1563                 " of the archive's version.\n".
1564                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1565     } else {
1566         $new_package or
1567             fail "package appears to be new in this suite;".
1568                 " if this is intentional, use --new";
1569     }
1570     dopush();
1571 }
1572
1573 #---------- remote commands' implementation ----------
1574
1575 sub cmd_remote_push_responder {
1576     my ($nrargs) = shift @ARGV;
1577     my (@rargs) = @ARGV[0..$nrargs-1];
1578     @ARGV = @ARGV[$nrargs..$#ARGV];
1579     die unless @rargs;
1580     my ($dir) = @rargs;
1581     $debugprefix = ' ';
1582     $we_are_responder = 1;
1583
1584     open PI, "<&STDIN" or die $!;
1585     open STDIN, "/dev/null" or die $!;
1586     open PO, ">&STDOUT" or die $!;
1587     autoflush PO 1;
1588     open STDOUT, ">&STDERR" or die $!;
1589     autoflush STDOUT 1;
1590
1591     responder_send_command("dgit-remote-push-ready");
1592
1593     changedir $dir;
1594     &cmd_push;
1595 }
1596
1597 our $i_tmp;
1598 our $i_child_pid;
1599
1600 sub i_cleanup {
1601     local ($@);
1602     if ($i_child_pid) {
1603         printdebug "(killing remote child $i_child_pid)\n";
1604         kill 15, $i_child_pid;
1605     }
1606     if (defined $i_tmp && !defined $initiator_tempdir) {
1607         changedir "/";
1608         eval { rmtree $i_tmp; };
1609     }
1610 }
1611
1612 END { i_cleanup(); }
1613
1614 sub i_method {
1615     my ($base,$selector,@args) = @_;
1616     $selector =~ s/\-/_/g;
1617     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1618 }
1619
1620 sub cmd_rpush {
1621     my $host = nextarg;
1622     my $dir;
1623     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1624         $host = $1;
1625         $dir = $'; #';
1626     } else {
1627         $dir = nextarg;
1628     }
1629     $dir =~ s{^-}{./-};
1630     my @rargs = ($dir);
1631     my @rdgit;
1632     push @rdgit, @dgit;
1633     push @rdgit, @ropts;
1634     push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1635     push @rdgit, @ARGV;
1636     my @cmd = (@ssh, $host, shellquote @rdgit);
1637     printcmd \*DEBUG,$debugprefix."+",@cmd;
1638
1639     if (defined $initiator_tempdir) {
1640         rmtree $initiator_tempdir;
1641         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1642         $i_tmp = $initiator_tempdir;
1643     } else {
1644         $i_tmp = tempdir();
1645     }
1646     $i_child_pid = open2(\*RO, \*RI, @cmd);
1647     changedir $i_tmp;
1648     initiator_expect { m/^dgit-remote-push-ready/ };
1649     for (;;) {
1650         my ($icmd,$iargs) = initiator_expect {
1651             m/^(\S+)(?: (.*))?$/;
1652             ($1,$2);
1653         };
1654         i_method "i_resp", $icmd, $iargs;
1655     }
1656 }
1657
1658 sub i_resp_progress ($) {
1659     my ($rhs) = @_;
1660     my $msg = protocol_read_bytes \*RO, $rhs;
1661     progress $msg;
1662 }
1663
1664 sub i_resp_complete {
1665     my $pid = $i_child_pid;
1666     $i_child_pid = undef; # prevents killing some other process with same pid
1667     printdebug "waiting for remote child $pid...\n";
1668     my $got = waitpid $pid, 0;
1669     die $! unless $got == $pid;
1670     die "remote child failed $?" if $?;
1671
1672     i_cleanup();
1673     printdebug "all done\n";
1674     exit 0;
1675 }
1676
1677 sub i_resp_file ($) {
1678     my ($keyword) = @_;
1679     my $localname = i_method "i_localname", $keyword;
1680     my $localpath = "$i_tmp/$localname";
1681     stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1682     protocol_receive_file \*RO, $localpath;
1683     i_method "i_file", $keyword;
1684 }
1685
1686 our %i_param;
1687
1688 sub i_resp_param ($) {
1689     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1690     $i_param{$1} = $2;
1691 }
1692
1693 our %i_wanted;
1694
1695 sub i_resp_want ($) {
1696     my ($keyword) = @_;
1697     die "$keyword ?" if $i_wanted{$keyword}++;
1698     my @localpaths = i_method "i_want", $keyword;
1699     printdebug "[[  $keyword @localpaths\n";
1700     foreach my $localpath (@localpaths) {
1701         protocol_send_file \*RI, $localpath;
1702     }
1703     print RI "files-end\n" or die $!;
1704 }
1705
1706 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1707
1708 sub i_localname_parsed_changelog {
1709     return "remote-changelog.822";
1710 }
1711 sub i_file_parsed_changelog {
1712     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1713         push_parse_changelog "$i_tmp/remote-changelog.822";
1714     die if $i_dscfn =~ m#/|^\W#;
1715 }
1716
1717 sub i_localname_dsc {
1718     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1719     return $i_dscfn;
1720 }
1721 sub i_file_dsc { }
1722
1723 sub i_localname_changes {
1724     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1725     $i_changesfn = $i_dscfn;
1726     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1727     return $i_changesfn;
1728 }
1729 sub i_file_changes { }
1730
1731 sub i_want_signed_tag {
1732     printdebug Dumper(\%i_param, $i_dscfn);
1733     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1734         or badproto \*RO, "premature desire for signed-tag";
1735     my $head = $i_param{'head'};
1736     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1737
1738     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1739
1740     my $tagobjfn =
1741         push_mktag $head, $i_clogp, $i_tag,
1742             $i_dscfn,
1743             $i_changesfn, 'remote changes',
1744             sub { "tag$_[0]"; };
1745
1746     return $tagobjfn;
1747 }
1748
1749 sub i_want_signed_dsc_changes {
1750     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1751     sign_changes $i_changesfn;
1752     return ($i_dscfn, $i_changesfn);
1753 }
1754
1755 #---------- building etc. ----------
1756
1757 our $version;
1758 our $sourcechanges;
1759 our $dscfn;
1760
1761 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1762
1763 sub build_maybe_quilt_fixup () {
1764     if (!open F, "debian/source/format") {
1765         die $! unless $!==&ENOENT;
1766         return;
1767     }
1768     $_ = <F>;
1769     F->error and die $!;
1770     chomp;
1771     return unless madformat($_);
1772     # sigh
1773     
1774     my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1775     my $problems = cmdoutput @cmd;
1776     if (length $problems) {
1777         print STDERR "problematic files:\n";
1778         print STDERR "  $_\n" foreach split /\n/, $problems;
1779         fail "Cannot do quilt fixup in tree containing ignored files.  ".
1780             "Perhaps your package's clean target is broken, in which".
1781             " case -wg (which says to use git-clean -xdf) may help.";
1782     }
1783
1784     my $clogp = parsechangelog();
1785     my $version = getfield $clogp, 'Version';
1786     my $author = getfield $clogp, 'Maintainer';
1787     my $headref = rev_parse('HEAD');
1788     my $time = time;
1789     my $ncommits = 3;
1790     my $patchname = "auto-$version-$headref-$time";
1791     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1792     mkpath '.git/dgit';
1793     my $descfn = ".git/dgit/quilt-description.tmp";
1794     open O, '>', $descfn or die "$descfn: $!";
1795     $msg =~ s/\n/\n /g;
1796     $msg =~ s/^\s+$/ ./mg;
1797     print O <<END or die $!;
1798 Description: Automatically generated patch ($clogp->{Version})
1799  Last (up to) $ncommits git changes, FYI:
1800  .
1801  $msg
1802 Author: $author
1803
1804 ---
1805
1806 END
1807     close O or die $!;
1808     {
1809         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1810         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1811         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1812         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1813     }
1814
1815     if (!open P, '>>', ".pc/applied-patches") {
1816         $!==&ENOENT or die $!;
1817     } else {
1818         close P;
1819     }
1820
1821     commit_quilty_patch();
1822 }
1823
1824 sub quilt_fixup_editor () {
1825     my $descfn = $ENV{$fakeeditorenv};
1826     my $editing = $ARGV[$#ARGV];
1827     open I1, '<', $descfn or die "$descfn: $!";
1828     open I2, '<', $editing or die "$editing: $!";
1829     unlink $editing or die "$editing: $!";
1830     open O, '>', $editing or die "$editing: $!";
1831     while (<I1>) { print O or die $!; } I1->error and die $!;
1832     my $copying = 0;
1833     while (<I2>) {
1834         $copying ||= m/^\-\-\- /;
1835         next unless $copying;
1836         print O or die $!;
1837     }
1838     I2->error and die $!;
1839     close O or die $1;
1840     exit 0;
1841 }
1842
1843 sub clean_tree () {
1844     if ($cleanmode eq 'dpkg-source') {
1845         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
1846     } elsif ($cleanmode eq 'git') {
1847         runcmd_ordryrun_local @git, qw(clean -xdf);
1848     } elsif ($cleanmode eq 'none') {
1849     } else {
1850         die "$cleanmode ?";
1851     }
1852 }
1853
1854 sub build_prep () {
1855     badusage "-p is not allowed when building" if defined $package;
1856     check_not_dirty();
1857     clean_tree();
1858     my $clogp = parsechangelog();
1859     $isuite = getfield $clogp, 'Distribution';
1860     $package = getfield $clogp, 'Source';
1861     $version = getfield $clogp, 'Version';
1862     build_maybe_quilt_fixup();
1863 }
1864
1865 sub changesopts () {
1866     my @opts =@changesopts[1..$#changesopts];
1867     if (!defined $changes_since_version) {
1868         my @vsns = archive_query('archive_query');
1869         my @quirk = access_quirk();
1870         if ($quirk[0] eq 'backports') {
1871             local $isuite = $quirk[2];
1872             local $csuite;
1873             canonicalise_suite();
1874             push @vsns, archive_query('archive_query');
1875         }
1876         if (@vsns) {
1877             @vsns = map { $_->[0] } @vsns;
1878             @vsns = sort { -version_compare_string($a, $b) } @vsns;
1879             $changes_since_version = $vsns[0];
1880             progress "changelog will contain changes since $vsns[0]";
1881         } else {
1882             $changes_since_version = '_';
1883             progress "package seems new, not specifying -v<version>";
1884         }
1885     }
1886     if ($changes_since_version ne '_') {
1887         unshift @opts, "-v$changes_since_version";
1888     }
1889     return @opts;
1890 }
1891
1892 sub cmd_build {
1893     build_prep();
1894     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1895     printdone "build successful\n";
1896 }
1897
1898 sub cmd_git_build {
1899     build_prep();
1900     my @cmd =
1901         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1902          "--git-builder=@dpkgbuildpackage");
1903     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1904         canonicalise_suite();
1905         push @cmd, "--git-debian-branch=".lbranch();
1906     }
1907     push @cmd, changesopts();
1908     runcmd_ordryrun_local @cmd, @ARGV;
1909     printdone "build successful\n";
1910 }
1911
1912 sub build_source {
1913     build_prep();
1914     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1915     $dscfn = dscfn($version);
1916     if ($cleanmode eq 'dpkg-source') {
1917         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
1918             changesopts();
1919     } else {
1920         my $pwd = cmdoutput qw(env - pwd);
1921         my $leafdir = basename $pwd;
1922         changedir "..";
1923         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
1924         changedir $pwd;
1925         runcmd_ordryrun_local qw(sh -ec),
1926             'exec >$1; shift; exec "$@"','x',
1927             "../$sourcechanges",
1928             @dpkggenchanges, qw(-S), changesopts();
1929     }
1930 }
1931
1932 sub cmd_build_source {
1933     badusage "build-source takes no additional arguments" if @ARGV;
1934     build_source();
1935     printdone "source built, results in $dscfn and $sourcechanges";
1936 }
1937
1938 sub cmd_sbuild {
1939     build_source();
1940     changedir "..";
1941     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1942     if (act_local()) {
1943         stat $dscfn or fail "$dscfn (in parent directory): $!";
1944         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1945         foreach my $cf (glob $pat) {
1946             next if $cf eq $sourcechanges;
1947             unlink $cf or fail "remove $cf: $!";
1948         }
1949     }
1950     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1951     my @changesfiles = glob $pat;
1952     @changesfiles = sort {
1953         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
1954             or $a cmp $b
1955     } @changesfiles;
1956     fail "wrong number of different changes files (@changesfiles)"
1957         unless @changesfiles;
1958     runcmd_ordryrun_local @mergechanges, @changesfiles;
1959     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1960     if (act_local()) {
1961         stat $multichanges or fail "$multichanges: $!";
1962     }
1963     printdone "build successful, results in $multichanges\n" or die $!;
1964 }    
1965
1966 sub cmd_quilt_fixup {
1967     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1968     my $clogp = parsechangelog();
1969     $version = getfield $clogp, 'Version';
1970     build_maybe_quilt_fixup();
1971 }
1972
1973 #---------- argument parsing and main program ----------
1974
1975 sub cmd_version {
1976     print "dgit version $our_version\n" or die $!;
1977     exit 0;
1978 }
1979
1980 sub parseopts () {
1981     my $om;
1982
1983     if (defined $ENV{'DGIT_SSH'}) {
1984         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1985     } elsif (defined $ENV{'GIT_SSH'}) {
1986         @ssh = ($ENV{'GIT_SSH'});
1987     }
1988
1989     while (@ARGV) {
1990         last unless $ARGV[0] =~ m/^-/;
1991         $_ = shift @ARGV;
1992         last if m/^--?$/;
1993         if (m/^--/) {
1994             if (m/^--dry-run$/) {
1995                 push @ropts, $_;
1996                 $dryrun_level=2;
1997             } elsif (m/^--damp-run$/) {
1998                 push @ropts, $_;
1999                 $dryrun_level=1;
2000             } elsif (m/^--no-sign$/) {
2001                 push @ropts, $_;
2002                 $sign=0;
2003             } elsif (m/^--help$/) {
2004                 cmd_help();
2005             } elsif (m/^--version$/) {
2006                 cmd_version();
2007             } elsif (m/^--new$/) {
2008                 push @ropts, $_;
2009                 $new_package=1;
2010             } elsif (m/^--since-version=([^_]+|_)$/) {
2011                 push @ropts, $_;
2012                 $changes_since_version = $1;
2013             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2014                      ($om = $opts_opt_map{$1}) &&
2015                      length $om->[0]) {
2016                 push @ropts, $_;
2017                 $om->[0] = $2;
2018             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2019                      !$opts_opt_cmdonly{$1} &&
2020                      ($om = $opts_opt_map{$1})) {
2021                 push @ropts, $_;
2022                 push @$om, $2;
2023             } elsif (m/^--existing-package=(.*)/s) {
2024                 push @ropts, $_;
2025                 $existing_package = $1;
2026             } elsif (m/^--initiator-tempdir=(.*)/s) {
2027                 $initiator_tempdir = $1;
2028                 $initiator_tempdir =~ m#^/# or
2029                     badusage "--initiator-tempdir must be used specify an".
2030                         " absolute, not relative, directory."
2031             } elsif (m/^--distro=(.*)/s) {
2032                 push @ropts, $_;
2033                 $idistro = $1;
2034             } elsif (m/^--build-products-dir=(.*)/s) {
2035                 push @ropts, $_;
2036                 $buildproductsdir = $1;
2037             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2038                 push @ropts, $_;
2039                 $cleanmode = $1;
2040             } elsif (m/^--clean=(.*)$/s) {
2041                 badusage "unknown cleaning mode \`$1'";
2042             } elsif (m/^--ignore-dirty$/s) {
2043                 push @ropts, $_;
2044                 $ignoredirty = 1;
2045             } elsif (m/^--no-quilt-fixup$/s) {
2046                 push @ropts, $_;
2047                 $noquilt = 1;
2048             } else {
2049                 badusage "unknown long option \`$_'";
2050             }
2051         } else {
2052             while (m/^-./s) {
2053                 if (s/^-n/-/) {
2054                     push @ropts, $&;
2055                     $dryrun_level=2;
2056                 } elsif (s/^-L/-/) {
2057                     push @ropts, $&;
2058                     $dryrun_level=1;
2059                 } elsif (s/^-h/-/) {
2060                     cmd_help();
2061                 } elsif (s/^-D/-/) {
2062                     push @ropts, $&;
2063                     open DEBUG, ">&STDERR" or die $!;
2064                     autoflush DEBUG 1;
2065                     $debug++;
2066                 } elsif (s/^-N/-/) {
2067                     push @ropts, $&;
2068                     $new_package=1;
2069                 } elsif (s/^-v([^_]+|_)$//s) {
2070                     push @ropts, $&;
2071                     $changes_since_version = $1;
2072                 } elsif (m/^-m/) {
2073                     push @ropts, $&;
2074                     push @changesopts, $_;
2075                     $_ = '';
2076                 } elsif (s/^-c(.*=.*)//s) {
2077                     push @ropts, $&;
2078                     push @git, '-c', $1;
2079                 } elsif (s/^-d(.*)//s) {
2080                     push @ropts, $&;
2081                     $idistro = $1;
2082                 } elsif (s/^-C(.*)//s) {
2083                     push @ropts, $&;
2084                     $changesfile = $1;
2085                     if ($changesfile =~ s#^(.*)/##) {
2086                         $buildproductsdir = $1;
2087                     }
2088                 } elsif (s/^-k(.*)//s) {
2089                     $keyid=$1;
2090                 } elsif (s/^-wn//s) {
2091                     push @ropts, $&;
2092                     $cleanmode = 'none';
2093                 } elsif (s/^-wg//s) {
2094                     push @ropts, $&;
2095                     $cleanmode = 'git';
2096                 } elsif (s/^-wd//s) {
2097                     push @ropts, $&;
2098                     $cleanmode = 'dpkg-source';
2099                 } else {
2100                     badusage "unknown short option \`$_'";
2101                 }
2102             }
2103         }
2104     }
2105 }
2106
2107 if ($ENV{$fakeeditorenv}) {
2108     quilt_fixup_editor();
2109 }
2110
2111 delete $ENV{'DGET_UNPACK'};
2112
2113 parseopts();
2114 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2115 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2116     if $dryrun_level == 1;
2117 if (!@ARGV) {
2118     print STDERR $helpmsg or die $!;
2119     exit 8;
2120 }
2121 my $cmd = shift @ARGV;
2122 $cmd =~ y/-/_/;
2123 { no strict qw(refs); &{"cmd_$cmd"}(); }