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