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