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