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