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