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