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