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