chiark / gitweb /
dgit-repos-policy-debian: Fix misleading varible name
[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 Digest::MD5;
34 use Config;
35
36 use Debian::Dgit;
37
38 our $our_version = 'UNRELEASED'; ###substituted###
39
40 our $rpushprotovsn = 2;
41
42 our $isuite = 'unstable';
43 our $idistro;
44 our $package;
45 our @ropts;
46
47 our $sign = 1;
48 our $dryrun_level = 0;
49 our $changesfile;
50 our $buildproductsdir = '..';
51 our $new_package = 0;
52 our $ignoredirty = 0;
53 our $rmonerror = 1;
54 our @deliberatelies;
55 our %supersedes;
56 our $existing_package = 'dpkg';
57 our $cleanmode = 'dpkg-source';
58 our $changes_since_version;
59 our $quilt_mode;
60 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck';
61 our $we_are_responder;
62 our $initiator_tempdir;
63
64 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
65
66 our $suite_re = '[-+.0-9a-z]+';
67
68 our (@git) = qw(git);
69 our (@dget) = qw(dget);
70 our (@curl) = qw(curl -f);
71 our (@dput) = qw(dput);
72 our (@debsign) = qw(debsign);
73 our (@gpg) = qw(gpg);
74 our (@sbuild) = qw(sbuild -A);
75 our (@ssh) = 'ssh';
76 our (@dgit) = qw(dgit);
77 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
78 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
79 our (@dpkggenchanges) = qw(dpkg-genchanges);
80 our (@mergechanges) = qw(mergechanges -f);
81 our (@changesopts) = ('');
82
83 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
84                      'curl' => \@curl,
85                      'dput' => \@dput,
86                      'debsign' => \@debsign,
87                      'gpg' => \@gpg,
88                      'sbuild' => \@sbuild,
89                      'ssh' => \@ssh,
90                      'dgit' => \@dgit,
91                      'dpkg-source' => \@dpkgsource,
92                      'dpkg-buildpackage' => \@dpkgbuildpackage,
93                      'dpkg-genchanges' => \@dpkggenchanges,
94                      'ch' => \@changesopts,
95                      'mergechanges' => \@mergechanges);
96
97 our %opts_opt_cmdonly = ('gpg' => 1);
98
99 our $keyid;
100
101 our $debug = 0;
102 open DEBUG, ">/dev/null" or die $!;
103
104 autoflush STDOUT 1;
105
106 our $remotename = 'dgit';
107 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
108 our $csuite;
109 our $instead_distro;
110
111 sub lbranch () { return "$branchprefix/$csuite"; }
112 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
113 sub lref () { return "refs/heads/".lbranch(); }
114 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
115 sub rrref () { return server_ref($csuite); }
116
117 sub stripepoch ($) {
118     my ($vsn) = @_;
119     $vsn =~ s/^\d+\://;
120     return $vsn;
121 }
122
123 sub srcfn ($$) {
124     my ($vsn,$sfx) = @_;
125     return "${package}_".(stripepoch $vsn).$sfx
126 }
127
128 sub dscfn ($) {
129     my ($vsn) = @_;
130     return srcfn($vsn,".dsc");
131 }
132
133 our $us = 'dgit';
134 our $debugprefix = '';
135
136 our @end;
137 END { 
138     local ($?);
139     foreach my $f (@end) {
140         eval { $f->(); };
141         warn "$us: cleanup: $@" if length $@;
142     }
143 };
144
145 our @signames = split / /, $Config{sig_name};
146
147 sub waitstatusmsg () {
148     if (!$?) {
149         return "terminated, reporting successful completion";
150     } elsif (!($? & 255)) {
151         return "failed with error exit status ".WEXITSTATUS($?);
152     } elsif (WIFSIGNALED($?)) {
153         my $signum=WTERMSIG($?);
154         return "died due to fatal signal ".
155             ($signames[$signum] // "number $signum").
156             ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
157     } else {
158         return "failed with unknown wait status ".$?;
159     }
160 }
161
162 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
163
164 sub fail { 
165     my $s = "@_\n";
166     my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
167     $s =~ s/^/$prefix/gm;
168     die $s;
169 }
170
171 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
172
173 sub no_such_package () {
174     print STDERR "$us: package $package does not exist in suite $isuite\n";
175     exit 4;
176 }
177
178 sub fetchspec () {
179     local $csuite = '*';
180     return  "+".rrref().":".lrref();
181 }
182
183 sub changedir ($) {
184     my ($newdir) = @_;
185     printdebug "CD $newdir\n";
186     chdir $newdir or die "chdir: $newdir: $!";
187 }
188
189 sub deliberately ($) {
190     return !!grep { $_[0] eq $_ } @deliberatelies;
191 }
192
193 #---------- remote protocol support, common ----------
194
195 # remote push initiator/responder protocol:
196 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
197 #
198 #  > file parsed-changelog
199 #  [indicates that output of dpkg-parsechangelog follows]
200 #  > data-block NBYTES
201 #  > [NBYTES bytes of data (no newline)]
202 #  [maybe some more blocks]
203 #  > data-end
204 #
205 #  > file dsc
206 #  [etc]
207 #
208 #  > file changes
209 #  [etc]
210 #
211 #  > param head HEAD
212 #
213 #  > want signed-tag
214 #  [indicates that signed tag is wanted]
215 #  < data-block NBYTES
216 #  < [NBYTES bytes of data (no newline)]
217 #  [maybe some more blocks]
218 #  < data-end
219 #  < files-end
220 #
221 #  > want signed-dsc-changes
222 #  < data-block NBYTES    [transfer of signed dsc]
223 #  [etc]
224 #  < data-block NBYTES    [transfer of signed changes]
225 #  [etc]
226 #  < files-end
227 #
228 #  > complete
229
230 our $i_child_pid;
231
232 sub i_child_report () {
233     # Sees if our child has died, and reap it if so.  Returns a string
234     # describing how it died if it failed, or undef otherwise.
235     return undef unless $i_child_pid;
236     my $got = waitpid $i_child_pid, WNOHANG;
237     return undef if $got <= 0;
238     die unless $got == $i_child_pid;
239     $i_child_pid = undef;
240     return undef unless $?;
241     return "build host child ".waitstatusmsg();
242 }
243
244 sub badproto ($$) {
245     my ($fh, $m) = @_;
246     fail "connection lost: $!" if $fh->error;
247     fail "protocol violation; $m not expected";
248 }
249
250 sub badproto_badread ($$) {
251     my ($fh, $wh) = @_;
252     fail "connection lost: $!" if $!;
253     my $report = i_child_report();
254     fail $report if defined $report;
255     badproto $fh, "eof (reading $wh)";
256 }
257
258 sub protocol_expect (&$) {
259     my ($match, $fh) = @_;
260     local $_;
261     $_ = <$fh>;
262     defined && chomp or badproto_badread $fh, "protocol message";
263     if (wantarray) {
264         my @r = &$match;
265         return @r if @r;
266     } else {
267         my $r = &$match;
268         return $r if $r;
269     }
270     badproto $fh, "\`$_'";
271 }
272
273 sub protocol_send_file ($$) {
274     my ($fh, $ourfn) = @_;
275     open PF, "<", $ourfn or die "$ourfn: $!";
276     for (;;) {
277         my $d;
278         my $got = read PF, $d, 65536;
279         die "$ourfn: $!" unless defined $got;
280         last if !$got;
281         print $fh "data-block ".length($d)."\n" or die $!;
282         print $fh $d or die $!;
283     }
284     PF->error and die "$ourfn $!";
285     print $fh "data-end\n" or die $!;
286     close PF;
287 }
288
289 sub protocol_read_bytes ($$) {
290     my ($fh, $nbytes) = @_;
291     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
292     my $d;
293     my $got = read $fh, $d, $nbytes;
294     $got==$nbytes or badproto_badread $fh, "data block";
295     return $d;
296 }
297
298 sub protocol_receive_file ($$) {
299     my ($fh, $ourfn) = @_;
300     printdebug "() $ourfn\n";
301     open PF, ">", $ourfn or die "$ourfn: $!";
302     for (;;) {
303         my ($y,$l) = protocol_expect {
304             m/^data-block (.*)$/ ? (1,$1) :
305             m/^data-end$/ ? (0,) :
306             ();
307         } $fh;
308         last unless $y;
309         my $d = protocol_read_bytes $fh, $l;
310         print PF $d or die $!;
311     }
312     close PF or die $!;
313 }
314
315 #---------- remote protocol support, responder ----------
316
317 sub responder_send_command ($) {
318     my ($command) = @_;
319     return unless $we_are_responder;
320     # called even without $we_are_responder
321     printdebug ">> $command\n";
322     print PO $command, "\n" or die $!;
323 }    
324
325 sub responder_send_file ($$) {
326     my ($keyword, $ourfn) = @_;
327     return unless $we_are_responder;
328     printdebug "]] $keyword $ourfn\n";
329     responder_send_command "file $keyword";
330     protocol_send_file \*PO, $ourfn;
331 }
332
333 sub responder_receive_files ($@) {
334     my ($keyword, @ourfns) = @_;
335     die unless $we_are_responder;
336     printdebug "[[ $keyword @ourfns\n";
337     responder_send_command "want $keyword";
338     foreach my $fn (@ourfns) {
339         protocol_receive_file \*PI, $fn;
340     }
341     printdebug "[[\$\n";
342     protocol_expect { m/^files-end$/ } \*PI;
343 }
344
345 #---------- remote protocol support, initiator ----------
346
347 sub initiator_expect (&) {
348     my ($match) = @_;
349     protocol_expect { &$match } \*RO;
350 }
351
352 #---------- end remote code ----------
353
354 sub progress {
355     if ($we_are_responder) {
356         my $m = join '', @_;
357         responder_send_command "progress ".length($m) or die $!;
358         print PO $m or die $!;
359     } else {
360         print @_, "\n";
361     }
362 }
363
364 our $ua;
365
366 sub url_get {
367     if (!$ua) {
368         $ua = LWP::UserAgent->new();
369         $ua->env_proxy;
370     }
371     my $what = $_[$#_];
372     progress "downloading $what...";
373     my $r = $ua->get(@_) or die $!;
374     return undef if $r->code == 404;
375     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
376     return $r->decoded_content(charset => 'none');
377 }
378
379 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
380
381 sub shellquote {
382     my @out;
383     local $_;
384     foreach my $a (@_) {
385         $_ = $a;
386         if (m{[^-=_./0-9a-z]}i) {
387             s{['\\]}{'\\$&'}g;
388             push @out, "'$_'";
389         } else {
390             push @out, $_;
391         }
392     }
393     return join ' ', @out;
394 }
395
396 sub printcmd {
397     my $fh = shift @_;
398     my $intro = shift @_;
399     print $fh $intro," " or die $!;
400     print $fh shellquote @_ or die $!;
401     print $fh "\n" or die $!;
402 }
403
404 sub failedcmd {
405     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
406     if ($!) {
407         fail "failed to fork/exec: $!";
408     } elsif ($?) {
409         fail "subprocess ".waitstatusmsg();
410     } else {
411         fail "subprocess produced invalid output";
412     }
413 }
414
415 sub runcmd {
416     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
417     $!=0; $?=0;
418     failedcmd @_ if system @_;
419 }
420
421 sub act_local () { return $dryrun_level <= 1; }
422 sub act_scary () { return !$dryrun_level; }
423
424 sub printdone {
425     if (!$dryrun_level) {
426         progress "dgit ok: @_";
427     } else {
428         progress "would be ok: @_ (but dry run only)";
429     }
430 }
431
432 sub cmdoutput_errok {
433     die Dumper(\@_)." ?" if grep { !defined } @_;
434     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
435     open P, "-|", @_ or die $!;
436     my $d;
437     $!=0; $?=0;
438     { local $/ = undef; $d = <P>; }
439     die $! if P->error;
440     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
441     chomp $d;
442     $d =~ m/^.*/;
443     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
444     return $d;
445 }
446
447 sub cmdoutput {
448     my $d = cmdoutput_errok @_;
449     defined $d or failedcmd @_;
450     return $d;
451 }
452
453 sub dryrun_report {
454     printcmd(\*STDERR,$debugprefix."#",@_);
455 }
456
457 sub runcmd_ordryrun {
458     if (act_scary()) {
459         runcmd @_;
460     } else {
461         dryrun_report @_;
462     }
463 }
464
465 sub runcmd_ordryrun_local {
466     if (act_local()) {
467         runcmd @_;
468     } else {
469         dryrun_report @_;
470     }
471 }
472
473 sub shell_cmd {
474     my ($first_shell, @cmd) = @_;
475     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
476 }
477
478 our $helpmsg = <<END;
479 main usages:
480   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
481   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
482   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
483   dgit [dgit-opts] push [dgit-opts] [suite]
484   dgit [dgit-opts] rpush build-host:build-dir ...
485 important dgit options:
486   -k<keyid>           sign tag and package with <keyid> instead of default
487   --dry-run -n        do not change anything, but go through the motions
488   --damp-run -L       like --dry-run but make local changes, without signing
489   --new -N            allow introducing a new package
490   --debug -D          increase debug level
491   -c<name>=<value>    set git config option (used directly by dgit too)
492 END
493
494 our $later_warning_msg = <<END;
495 Perhaps the upload is stuck in incoming.  Using the version from git.
496 END
497
498 sub badusage {
499     print STDERR "$us: @_\n", $helpmsg or die $!;
500     exit 8;
501 }
502
503 sub nextarg {
504     @ARGV or badusage "too few arguments";
505     return scalar shift @ARGV;
506 }
507
508 sub cmd_help () {
509     print $helpmsg or die $!;
510     exit 0;
511 }
512
513 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
514
515 our %defcfg = ('dgit.default.distro' => 'debian',
516                'dgit.default.username' => '',
517                'dgit.default.archive-query-default-component' => 'main',
518                'dgit.default.ssh' => 'ssh',
519                'dgit.default.archive-query' => 'madison:',
520                'dgit.default.sshpsql-dbname' => 'service=projectb',
521                'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
522                'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
523                'dgit-distro.debian.git-user-force' => 'dgit',
524                'dgit-distro.debian.git-proto' => 'git+ssh://',
525                'dgit-distro.debian.git-path' => '/dgit/debian/repos',
526                'dgit-distro.debian.git-check' => 'ssh-cmd',
527  'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
528  'dgit-distro.debian.archive-query-tls-key',
529     '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
530                'dgit-distro.debian.diverts.alioth' => '/alioth',
531                'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
532                'dgit-distro.debian/alioth.git-user-force' => '',
533                'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
534                'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
535                'dgit-distro.debian/alioth.git-create' => 'ssh-cmd',
536                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
537                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
538  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
539  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
540                'dgit-distro.ubuntu.git-check' => 'false',
541  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
542                'dgit-distro.test-dummy.ssh' => "$td/ssh",
543                'dgit-distro.test-dummy.username' => "alice",
544                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
545                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
546                'dgit-distro.test-dummy.git-url' => "$td/git",
547                'dgit-distro.test-dummy.git-host' => "git",
548                'dgit-distro.test-dummy.git-path' => "$td/git",
549                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
550                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
551                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
552                );
553
554 sub cfg {
555     foreach my $c (@_) {
556         return undef if $c =~ /RETURN-UNDEF/;
557         my @cmd = (@git, qw(config --), $c);
558         my $v;
559         {
560             local ($debug) = $debug-1;
561             $v = cmdoutput_errok @cmd;
562         };
563         if ($?==0) {
564             return $v;
565         } elsif ($?!=256) {
566             failedcmd @cmd;
567         }
568         my $dv = $defcfg{$c};
569         return $dv if defined $dv;
570     }
571     badcfg "need value for one of: @_\n".
572         "$us: distro or suite appears not to be (properly) supported";
573 }
574
575 sub access_basedistro () {
576     if (defined $idistro) {
577         return $idistro;
578     } else {    
579         return cfg("dgit-suite.$isuite.distro",
580                    "dgit.default.distro");
581     }
582 }
583
584 sub access_quirk () {
585     # returns (quirk name, distro to use instead or undef, quirk-specific info)
586     my $basedistro = access_basedistro();
587     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
588                               'RETURN-UNDEF');
589     if (defined $backports_quirk) {
590         my $re = $backports_quirk;
591         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
592         $re =~ s/\*/.*/g;
593         $re =~ s/\%/([-0-9a-z_]+)/
594             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
595         if ($isuite =~ m/^$re$/) {
596             return ('backports',"$basedistro-backports",$1);
597         }
598     }
599     return ('none',undef);
600 }
601
602 sub access_distros () {
603     # Returns list of distros to try, in order
604     #
605     # We want to try:
606     #    0. `instead of' distro name(s) we have been pointed to
607     #    1. the access_quirk distro, if any
608     #    2a. the user's specified distro, or failing that  } basedistro
609     #    2b. the distro calculated from the suite          }
610     my @l = access_basedistro();
611
612     my (undef,$quirkdistro) = access_quirk();
613     unshift @l, $quirkdistro;
614     unshift @l, $instead_distro;
615     return grep { defined } @l;
616 }
617
618 sub access_cfg (@) {
619     my (@keys) = @_;
620     my @cfgs;
621     # The nesting of these loops determines the search order.  We put
622     # the key loop on the outside so that we search all the distros
623     # for each key, before going on to the next key.  That means that
624     # if access_cfg is called with a more specific, and then a less
625     # specific, key, an earlier distro can override the less specific
626     # without necessarily overriding any more specific keys.  (If the
627     # distro wants to override the more specific keys it can simply do
628     # so; whereas if we did the loop the other way around, it would be
629     # impossible to for an earlier distro to override a less specific
630     # key but not the more specific ones without restating the unknown
631     # values of the more specific keys.
632     my @realkeys;
633     my @rundef;
634     # We have to deal with RETURN-UNDEF specially, so that we don't
635     # terminate the search prematurely.
636     foreach (@keys) {
637         if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
638         push @realkeys, $_
639     }
640     foreach my $d (access_distros()) {
641         push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
642     }
643     push @cfgs, map { "dgit.default.$_" } @realkeys;
644     push @cfgs, @rundef;
645     my $value = cfg(@cfgs);
646     return $value;
647 }
648
649 sub string_to_ssh ($) {
650     my ($spec) = @_;
651     if ($spec =~ m/\s/) {
652         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
653     } else {
654         return ($spec);
655     }
656 }
657
658 sub access_cfg_ssh () {
659     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
660     if (!defined $gitssh) {
661         return @ssh;
662     } else {
663         return string_to_ssh $gitssh;
664     }
665 }
666
667 sub access_runeinfo ($) {
668     my ($info) = @_;
669     return ": dgit ".access_basedistro()." $info ;";
670 }
671
672 sub access_someuserhost ($) {
673     my ($some) = @_;
674     my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
675     defined($user) && length($user) or
676         $user = access_cfg("$some-user",'username');
677     my $host = access_cfg("$some-host");
678     return length($user) ? "$user\@$host" : $host;
679 }
680
681 sub access_gituserhost () {
682     return access_someuserhost('git');
683 }
684
685 sub access_giturl (;$) {
686     my ($optional) = @_;
687     my $url = access_cfg('git-url','RETURN-UNDEF');
688     if (!defined $url) {
689         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
690         return undef unless defined $proto;
691         $url =
692             $proto.
693             access_gituserhost().
694             access_cfg('git-path');
695     }
696     return "$url/$package.git";
697 }              
698
699 sub parsecontrolfh ($$;$) {
700     my ($fh, $desc, $allowsigned) = @_;
701     our $dpkgcontrolhash_noissigned;
702     my $c;
703     for (;;) {
704         my %opts = ('name' => $desc);
705         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
706         $c = Dpkg::Control::Hash->new(%opts);
707         $c->parse($fh,$desc) or die "parsing of $desc failed";
708         last if $allowsigned;
709         last if $dpkgcontrolhash_noissigned;
710         my $issigned= $c->get_option('is_pgp_signed');
711         if (!defined $issigned) {
712             $dpkgcontrolhash_noissigned= 1;
713             seek $fh, 0,0 or die "seek $desc: $!";
714         } elsif ($issigned) {
715             fail "control file $desc is (already) PGP-signed. ".
716                 " Note that dgit push needs to modify the .dsc and then".
717                 " do the signature itself";
718         } else {
719             last;
720         }
721     }
722     return $c;
723 }
724
725 sub parsecontrol {
726     my ($file, $desc) = @_;
727     my $fh = new IO::Handle;
728     open $fh, '<', $file or die "$file: $!";
729     my $c = parsecontrolfh($fh,$desc);
730     $fh->error and die $!;
731     close $fh;
732     return $c;
733 }
734
735 sub getfield ($$) {
736     my ($dctrl,$field) = @_;
737     my $v = $dctrl->{$field};
738     return $v if defined $v;
739     fail "missing field $field in ".$v->get_option('name');
740 }
741
742 sub parsechangelog {
743     my $c = Dpkg::Control::Hash->new();
744     my $p = new IO::Handle;
745     my @cmd = (qw(dpkg-parsechangelog), @_);
746     open $p, '-|', @cmd or die $!;
747     $c->parse($p);
748     $?=0; $!=0; close $p or failedcmd @cmd;
749     return $c;
750 }
751
752 sub git_get_ref ($) {
753     my ($refname) = @_;
754     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
755     if (!defined $got) {
756         $?==256 or fail "git show-ref failed (status $?)";
757         printdebug "ref $refname= [show-ref exited 1]\n";
758         return '';
759     }
760     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
761         printdebug "ref $refname=$1\n";
762         return $1;
763     } else {
764         printdebug "ref $refname= [no match]\n";
765         return '';
766     }
767 }
768
769 sub must_getcwd () {
770     my $d = getcwd();
771     defined $d or fail "getcwd failed: $!";
772     return $d;
773 }
774
775 our %rmad;
776
777 sub archive_query ($) {
778     my ($method) = @_;
779     my $query = access_cfg('archive-query','RETURN-UNDEF');
780     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
781     my $proto = $1;
782     my $data = $'; #';
783     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
784 }
785
786 sub pool_dsc_subpath ($$) {
787     my ($vsn,$component) = @_; # $package is implict arg
788     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
789     return "/pool/$component/$prefix/$package/".dscfn($vsn);
790 }
791
792 #---------- `ftpmasterapi' archive query method (nascent) ----------
793
794 sub archive_api_query_cmd ($) {
795     my ($subpath) = @_;
796     my @cmd = qw(curl -sS);
797     my $url = access_cfg('archive-query-url');
798     if ($url =~ m#^https://([-.0-9a-z]+)/#) {
799         my $host = $1;
800         my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF');
801         foreach my $key (split /\:/, $keys) {
802             $key =~ s/\%HOST\%/$host/g;
803             if (!stat $key) {
804                 fail "for $url: stat $key: $!" unless $!==ENOENT;
805                 next;
806             }
807             push @cmd, "--ca-certificate=$key", "--ca-directory=/dev/enoent";
808             last;
809         }
810     }
811     push @cmd, $url.$subpath;
812     return @cmd;
813 }
814
815 sub api_query ($$) {
816     use JSON;
817     my ($data, $subpath) = @_;
818     badcfg "ftpmasterapi archive query method takes no data part"
819         if length $data;
820     my @cmd = archive_api_query_cmd($subpath);
821     my $json = cmdoutput @cmd;
822     return decode_json($json);
823 }
824
825 sub canonicalise_suite_ftpmasterapi () {
826     my ($proto,$data) = @_;
827     my $suites = api_query($data, 'suites');
828     my @matched;
829     foreach my $entry (@$suites) {
830         next unless grep { 
831             my $v = $entry->{$_};
832             defined $v && $v eq $isuite;
833         } qw(codename name);
834         push @matched, $entry;
835     }
836     fail "unknown suite $isuite" unless @matched;
837     my $cn;
838     eval {
839         @matched==1 or die "multiple matches for suite $isuite\n";
840         $cn = "$matched[0]{codename}";
841         defined $cn or die "suite $isuite info has no codename\n";
842         $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
843     };
844     die "bad ftpmaster api response: $@\n".Dumper(\@matched)
845         if length $@;
846     return $cn;
847 }
848
849 sub archive_query_ftpmasterapi () {
850     my ($proto,$data) = @_;
851     my $info = api_query($data, "dsc_in_suite/$isuite/$package");
852     my @rows;
853     my $digester = Digest::SHA->new(256);
854     foreach my $entry (@$info) {
855         eval {
856             my $vsn = "$entry->{version}";
857             my ($ok,$msg) = version_check $vsn;
858             die "bad version: $msg\n" unless $ok;
859             my $component = "$entry->{component}";
860             $component =~ m/^$component_re$/ or die "bad component";
861             my $filename = "$entry->{filename}";
862             $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
863                 or die "bad filename";
864             my $sha256sum = "$entry->{sha256sum}";
865             $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
866             push @rows, [ $vsn, "/pool/$component/$filename",
867                           $digester, $sha256sum ];
868         };
869         die "bad ftpmaster api response: $@\n".Dumper($entry)
870             if length $@;
871     }
872     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
873     return @rows;
874 }
875
876 #---------- `madison' archive query method ----------
877
878 sub archive_query_madison {
879     return map { [ @$_[0..1] ] } madison_get_parse(@_);
880 }
881
882 sub madison_get_parse {
883     my ($proto,$data) = @_;
884     die unless $proto eq 'madison';
885     if (!length $data) {
886         $data= access_cfg('madison-distro','RETURN-UNDEF');
887         $data //= access_basedistro();
888     }
889     $rmad{$proto,$data,$package} ||= cmdoutput
890         qw(rmadison -asource),"-s$isuite","-u$data",$package;
891     my $rmad = $rmad{$proto,$data,$package};
892
893     my @out;
894     foreach my $l (split /\n/, $rmad) {
895         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
896                   \s*( [^ \t|]+ )\s* \|
897                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
898                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
899         $1 eq $package or die "$rmad $package ?";
900         my $vsn = $2;
901         my $newsuite = $3;
902         my $component;
903         if (defined $4) {
904             $component = $4;
905         } else {
906             $component = access_cfg('archive-query-default-component');
907         }
908         $5 eq 'source' or die "$rmad ?";
909         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
910     }
911     return sort { -version_compare($a->[0],$b->[0]); } @out;
912 }
913
914 sub canonicalise_suite_madison {
915     # madison canonicalises for us
916     my @r = madison_get_parse(@_);
917     @r or fail
918         "unable to canonicalise suite using package $package".
919         " which does not appear to exist in suite $isuite;".
920         " --existing-package may help";
921     return $r[0][2];
922 }
923
924 #---------- `sshpsql' archive query method ----------
925
926 sub sshpsql ($$$) {
927     my ($data,$runeinfo,$sql) = @_;
928     if (!length $data) {
929         $data= access_someuserhost('sshpsql').':'.
930             access_cfg('sshpsql-dbname');
931     }
932     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
933     my ($userhost,$dbname) = ($`,$'); #';
934     my @rows;
935     my @cmd = (access_cfg_ssh, $userhost,
936                access_runeinfo("ssh-psql $runeinfo").
937                " export LANG=C;".
938                " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
939     printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
940     open P, "-|", @cmd or die $!;
941     while (<P>) {
942         chomp or die;
943         printdebug("$debugprefix>|$_|\n");
944         push @rows, $_;
945     }
946     $!=0; $?=0; close P or failedcmd @cmd;
947     @rows or die;
948     my $nrows = pop @rows;
949     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
950     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
951     @rows = map { [ split /\|/, $_ ] } @rows;
952     my $ncols = scalar @{ shift @rows };
953     die if grep { scalar @$_ != $ncols } @rows;
954     return @rows;
955 }
956
957 sub sql_injection_check {
958     foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
959 }
960
961 sub archive_query_sshpsql ($$) {
962     my ($proto,$data) = @_;
963     sql_injection_check $isuite, $package;
964     my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
965         SELECT source.version, component.name, files.filename, files.sha256sum
966           FROM source
967           JOIN src_associations ON source.id = src_associations.source
968           JOIN suite ON suite.id = src_associations.suite
969           JOIN dsc_files ON dsc_files.source = source.id
970           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
971           JOIN component ON component.id = files_archive_map.component_id
972           JOIN files ON files.id = dsc_files.file
973          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
974            AND source.source='$package'
975            AND files.filename LIKE '%.dsc';
976 END
977     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
978     my $digester = Digest::SHA->new(256);
979     @rows = map {
980         my ($vsn,$component,$filename,$sha256sum) = @$_;
981         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
982     } @rows;
983     return @rows;
984 }
985
986 sub canonicalise_suite_sshpsql ($$) {
987     my ($proto,$data) = @_;
988     sql_injection_check $isuite;
989     my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
990         SELECT suite.codename
991           FROM suite where suite_name='$isuite' or codename='$isuite';
992 END
993     @rows = map { $_->[0] } @rows;
994     fail "unknown suite $isuite" unless @rows;
995     die "ambiguous $isuite: @rows ?" if @rows>1;
996     return $rows[0];
997 }
998
999 #---------- `dummycat' archive query method ----------
1000
1001 sub canonicalise_suite_dummycat ($$) {
1002     my ($proto,$data) = @_;
1003     my $dpath = "$data/suite.$isuite";
1004     if (!open C, "<", $dpath) {
1005         $!==ENOENT or die "$dpath: $!";
1006         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1007         return $isuite;
1008     }
1009     $!=0; $_ = <C>;
1010     chomp or die "$dpath: $!";
1011     close C;
1012     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1013     return $_;
1014 }
1015
1016 sub archive_query_dummycat ($$) {
1017     my ($proto,$data) = @_;
1018     canonicalise_suite();
1019     my $dpath = "$data/package.$csuite.$package";
1020     if (!open C, "<", $dpath) {
1021         $!==ENOENT or die "$dpath: $!";
1022         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1023         return ();
1024     }
1025     my @rows;
1026     while (<C>) {
1027         next if m/^\#/;
1028         next unless m/\S/;
1029         die unless chomp;
1030         printdebug "dummycat query $csuite $package $dpath | $_\n";
1031         my @row = split /\s+/, $_;
1032         @row==2 or die "$dpath: $_ ?";
1033         push @rows, \@row;
1034     }
1035     C->error and die "$dpath: $!";
1036     close C;
1037     return sort { -version_compare($a->[0],$b->[0]); } @rows;
1038 }
1039
1040 #---------- archive query entrypoints and rest of program ----------
1041
1042 sub canonicalise_suite () {
1043     return if defined $csuite;
1044     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1045     $csuite = archive_query('canonicalise_suite');
1046     if ($isuite ne $csuite) {
1047         progress "canonical suite name for $isuite is $csuite";
1048     }
1049 }
1050
1051 sub get_archive_dsc () {
1052     canonicalise_suite();
1053     my @vsns = archive_query('archive_query');
1054     foreach my $vinfo (@vsns) {
1055         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1056         $dscurl = access_cfg('mirror').$subpath;
1057         $dscdata = url_get($dscurl);
1058         if (!$dscdata) {
1059             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1060             next;
1061         }
1062         if ($digester) {
1063             $digester->reset();
1064             $digester->add($dscdata);
1065             my $got = $digester->hexdigest();
1066             $got eq $digest or
1067                 fail "$dscurl has hash $got but".
1068                     " archive told us to expect $digest";
1069         }
1070         my $dscfh = new IO::File \$dscdata, '<' or die $!;
1071         printdebug Dumper($dscdata) if $debug>1;
1072         $dsc = parsecontrolfh($dscfh,$dscurl,1);
1073         printdebug Dumper($dsc) if $debug>1;
1074         my $fmt = getfield $dsc, 'Format';
1075         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1076         $dsc_checked = !!$digester;
1077         return;
1078     }
1079     $dsc = undef;
1080 }
1081
1082 sub check_for_git ();
1083 sub check_for_git () {
1084     # returns 0 or 1
1085     my $how = access_cfg('git-check');
1086     if ($how eq 'ssh-cmd') {
1087         my @cmd =
1088             (access_cfg_ssh, access_gituserhost(),
1089              access_runeinfo("git-check $package").
1090              " set -e; cd ".access_cfg('git-path').";".
1091              " if test -d $package.git; then echo 1; else echo 0; fi");
1092         my $r= cmdoutput @cmd;
1093         if ($r =~ m/^divert (\w+)$/) {
1094             my $divert=$1;
1095             my ($usedistro,) = access_distros();
1096             $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1097             $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1098             printdebug "diverting $divert so using distro $instead_distro\n";
1099             return check_for_git();
1100         }
1101         failedcmd @cmd unless $r =~ m/^[01]$/;
1102         return $r+0;
1103     } elsif ($how eq 'true') {
1104         return 1;
1105     } elsif ($how eq 'false') {
1106         return 0;
1107     } else {
1108         badcfg "unknown git-check \`$how'";
1109     }
1110 }
1111
1112 sub create_remote_git_repo () {
1113     my $how = access_cfg('git-create');
1114     if ($how eq 'ssh-cmd') {
1115         runcmd_ordryrun
1116             (access_cfg_ssh, access_gituserhost(),
1117              access_runeinfo("git-create $package").
1118              "set -e; cd ".access_cfg('git-path').";".
1119              " cp -a _template $package.git");
1120     } elsif ($how eq 'true') {
1121         # nothing to do
1122     } else {
1123         badcfg "unknown git-create \`$how'";
1124     }
1125 }
1126
1127 our ($dsc_hash,$lastpush_hash);
1128
1129 our $ud = '.git/dgit/unpack';
1130
1131 sub prep_ud () {
1132     rmtree($ud);
1133     mkpath '.git/dgit';
1134     mkdir $ud or die $!;
1135 }
1136
1137 sub mktree_in_ud_here () {
1138     runcmd qw(git init -q);
1139     rmtree('.git/objects');
1140     symlink '../../../../objects','.git/objects' or die $!;
1141 }
1142
1143 sub git_write_tree () {
1144     my $tree = cmdoutput @git, qw(write-tree);
1145     $tree =~ m/^\w+$/ or die "$tree ?";
1146     return $tree;
1147 }
1148
1149 sub mktree_in_ud_from_only_subdir () {
1150     # changes into the subdir
1151     my (@dirs) = <*/.>;
1152     die unless @dirs==1;
1153     $dirs[0] =~ m#^([^/]+)/\.$# or die;
1154     my $dir = $1;
1155     changedir $dir;
1156     fail "source package contains .git directory" if stat_exists '.git';
1157     mktree_in_ud_here();
1158     my $format=get_source_format();
1159     if (madformat($format)) {
1160         rmtree '.pc';
1161     }
1162     runcmd @git, qw(add -Af);
1163     my $tree=git_write_tree();
1164     return ($tree,$dir);
1165 }
1166
1167 sub dsc_files_info () {
1168     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1169                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
1170                        ['Files',           'Digest::MD5', 'new()']) {
1171         my ($fname, $module, $method) = @$csumi;
1172         my $field = $dsc->{$fname};
1173         next unless defined $field;
1174         eval "use $module; 1;" or die $@;
1175         my @out;
1176         foreach (split /\n/, $field) {
1177             next unless m/\S/;
1178             m/^(\w+) (\d+) (\S+)$/ or
1179                 fail "could not parse .dsc $fname line \`$_'";
1180             my $digester = eval "$module"."->$method;" or die $@;
1181             push @out, {
1182                 Hash => $1,
1183                 Bytes => $2,
1184                 Filename => $3,
1185                 Digester => $digester,
1186             };
1187         }
1188         return @out;
1189     }
1190     fail "missing any supported Checksums-* or Files field in ".
1191         $dsc->get_option('name');
1192 }
1193
1194 sub dsc_files () {
1195     map { $_->{Filename} } dsc_files_info();
1196 }
1197
1198 sub is_orig_file ($;$) {
1199     local ($_) = $_[0];
1200     my $base = $_[1];
1201     m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1202     defined $base or return 1;
1203     return $` eq $base;
1204 }
1205
1206 sub make_commit ($) {
1207     my ($file) = @_;
1208     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1209 }
1210
1211 sub clogp_authline ($) {
1212     my ($clogp) = @_;
1213     my $author = getfield $clogp, 'Maintainer';
1214     $author =~ s#,.*##ms;
1215     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1216     my $authline = "$author $date";
1217     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1218         fail "unexpected commit author line format \`$authline'".
1219         " (was generated from changelog Maintainer field)";
1220     return $authline;
1221 }
1222
1223 sub generate_commit_from_dsc () {
1224     prep_ud();
1225     changedir $ud;
1226
1227     foreach my $fi (dsc_files_info()) {
1228         my $f = $fi->{Filename};
1229         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1230
1231         link "../../../$f", $f
1232             or $!==&ENOENT
1233             or die "$f $!";
1234
1235         complete_file_from_dsc('.', $fi);
1236
1237         if (is_orig_file($f)) {
1238             link $f, "../../../../$f"
1239                 or $!==&EEXIST
1240                 or die "$f $!";
1241         }
1242     }
1243
1244     my $dscfn = "$package.dsc";
1245
1246     open D, ">", $dscfn or die "$dscfn: $!";
1247     print D $dscdata or die "$dscfn: $!";
1248     close D or die "$dscfn: $!";
1249     my @cmd = qw(dpkg-source);
1250     push @cmd, '--no-check' if $dsc_checked;
1251     push @cmd, qw(-x --), $dscfn;
1252     runcmd @cmd;
1253
1254     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1255     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1256     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1257     my $authline = clogp_authline $clogp;
1258     my $changes = getfield $clogp, 'Changes';
1259     open C, ">../commit.tmp" or die $!;
1260     print C <<END or die $!;
1261 tree $tree
1262 author $authline
1263 committer $authline
1264
1265 $changes
1266
1267 # imported from the archive
1268 END
1269     close C or die $!;
1270     my $outputhash = make_commit qw(../commit.tmp);
1271     my $cversion = getfield $clogp, 'Version';
1272     progress "synthesised git commit from .dsc $cversion";
1273     if ($lastpush_hash) {
1274         runcmd @git, qw(reset --hard), $lastpush_hash;
1275         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1276         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1277         my $oversion = getfield $oldclogp, 'Version';
1278         my $vcmp =
1279             version_compare($oversion, $cversion);
1280         if ($vcmp < 0) {
1281             # git upload/ is earlier vsn than archive, use archive
1282             open C, ">../commit2.tmp" or die $!;
1283             print C <<END or die $!;
1284 tree $tree
1285 parent $lastpush_hash
1286 parent $outputhash
1287 author $authline
1288 committer $authline
1289
1290 Record $package ($cversion) in archive suite $csuite
1291 END
1292             $outputhash = make_commit qw(../commit2.tmp);
1293         } elsif ($vcmp > 0) {
1294             print STDERR <<END or die $!;
1295
1296 Version actually in archive:    $cversion (older)
1297 Last allegedly pushed/uploaded: $oversion (newer or same)
1298 $later_warning_msg
1299 END
1300             $outputhash = $lastpush_hash;
1301         } else {
1302             $outputhash = $lastpush_hash;
1303         }
1304     }
1305     changedir '../../../..';
1306     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1307             'DGIT_ARCHIVE', $outputhash;
1308     cmdoutput @git, qw(log -n2), $outputhash;
1309     # ... gives git a chance to complain if our commit is malformed
1310     rmtree($ud);
1311     return $outputhash;
1312 }
1313
1314 sub complete_file_from_dsc ($$) {
1315     our ($dstdir, $fi) = @_;
1316     # Ensures that we have, in $dir, the file $fi, with the correct
1317     # contents.  (Downloading it from alongside $dscurl if necessary.)
1318
1319     my $f = $fi->{Filename};
1320     my $tf = "$dstdir/$f";
1321     my $downloaded = 0;
1322
1323     if (stat_exists $tf) {
1324         progress "using existing $f";
1325     } else {
1326         my $furl = $dscurl;
1327         $furl =~ s{/[^/]+$}{};
1328         $furl .= "/$f";
1329         die "$f ?" unless $f =~ m/^${package}_/;
1330         die "$f ?" if $f =~ m#/#;
1331         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1332         next if !act_local();
1333         $downloaded = 1;
1334     }
1335
1336     open F, "<", "$tf" or die "$tf: $!";
1337     $fi->{Digester}->reset();
1338     $fi->{Digester}->addfile(*F);
1339     F->error and die $!;
1340     my $got = $fi->{Digester}->hexdigest();
1341     $got eq $fi->{Hash} or
1342         fail "file $f has hash $got but .dsc".
1343             " demands hash $fi->{Hash} ".
1344             ($downloaded ? "(got wrong file from archive!)"
1345              : "(perhaps you should delete this file?)");
1346 }
1347
1348 sub ensure_we_have_orig () {
1349     foreach my $fi (dsc_files_info()) {
1350         my $f = $fi->{Filename};
1351         next unless is_orig_file($f);
1352         complete_file_from_dsc('..', $fi);
1353     }
1354 }
1355
1356 sub rev_parse ($) {
1357     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1358 }
1359
1360 sub is_fast_fwd ($$) {
1361     my ($ancestor,$child) = @_;
1362     my @cmd = (@git, qw(merge-base), $ancestor, $child);
1363     my $mb = cmdoutput_errok @cmd;
1364     if (defined $mb) {
1365         return rev_parse($mb) eq rev_parse($ancestor);
1366     } else {
1367         $?==256 or failedcmd @cmd;
1368         return 0;
1369     }
1370 }
1371
1372 sub git_fetch_us () {
1373     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1374 }
1375
1376 sub fetch_from_archive () {
1377     # ensures that lrref() is what is actually in the archive,
1378     #  one way or another
1379     get_archive_dsc();
1380
1381     if ($dsc) {
1382         foreach my $field (@ourdscfield) {
1383             $dsc_hash = $dsc->{$field};
1384             last if defined $dsc_hash;
1385         }
1386         if (defined $dsc_hash) {
1387             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1388             $dsc_hash = $&;
1389             progress "last upload to archive specified git hash";
1390         } else {
1391             progress "last upload to archive has NO git hash";
1392         }
1393     } else {
1394         progress "no version available from the archive";
1395     }
1396
1397     $lastpush_hash = git_get_ref(lrref());
1398     printdebug "previous reference hash=$lastpush_hash\n";
1399     my $hash;
1400     if (defined $dsc_hash) {
1401         fail "missing remote git history even though dsc has hash -".
1402             " could not find ref ".lrref().
1403             " (should have been fetched from ".access_giturl()."#".rrref().")"
1404             unless $lastpush_hash;
1405         $hash = $dsc_hash;
1406         ensure_we_have_orig();
1407         if ($dsc_hash eq $lastpush_hash) {
1408         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1409             print STDERR <<END or die $!;
1410
1411 Git commit in archive is behind the last version allegedly pushed/uploaded.
1412 Commit referred to by archive:  $dsc_hash
1413 Last allegedly pushed/uploaded: $lastpush_hash
1414 $later_warning_msg
1415 END
1416             $hash = $lastpush_hash;
1417         } else {
1418             fail "git head (".lrref()."=$lastpush_hash) is not a ".
1419                 "descendant of archive's .dsc hash ($dsc_hash)";
1420         }
1421     } elsif ($dsc) {
1422         $hash = generate_commit_from_dsc();
1423     } elsif ($lastpush_hash) {
1424         # only in git, not in the archive yet
1425         $hash = $lastpush_hash;
1426         print STDERR <<END or die $!;
1427
1428 Package not found in the archive, but has allegedly been pushed using dgit.
1429 $later_warning_msg
1430 END
1431     } else {
1432         printdebug "nothing found!\n";
1433         if (defined $skew_warning_vsn) {
1434             print STDERR <<END or die $!;
1435
1436 Warning: relevant archive skew detected.
1437 Archive allegedly contains $skew_warning_vsn
1438 But we were not able to obtain any version from the archive or git.
1439
1440 END
1441         }
1442         return 0;
1443     }
1444     printdebug "current hash=$hash\n";
1445     if ($lastpush_hash) {
1446         fail "not fast forward on last upload branch!".
1447             " (archive's version left in DGIT_ARCHIVE)"
1448             unless is_fast_fwd($lastpush_hash, $hash);
1449     }
1450     if (defined $skew_warning_vsn) {
1451         mkpath '.git/dgit';
1452         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1453         my $clogf = ".git/dgit/changelog.tmp";
1454         runcmd shell_cmd "exec >$clogf",
1455             @git, qw(cat-file blob), "$hash:debian/changelog";
1456         my $gotclogp = parsechangelog("-l$clogf");
1457         my $got_vsn = getfield $gotclogp, 'Version';
1458         printdebug "SKEW CHECK GOT $got_vsn\n";
1459         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1460             print STDERR <<END or die $!;
1461
1462 Warning: archive skew detected.  Using the available version:
1463 Archive allegedly contains    $skew_warning_vsn
1464 We were able to obtain only   $got_vsn
1465
1466 END
1467         }
1468     }
1469     if ($lastpush_hash ne $hash) {
1470         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1471         if (act_local()) {
1472             cmdoutput @upd_cmd;
1473         } else {
1474             dryrun_report @upd_cmd;
1475         }
1476     }
1477     return 1;
1478 }
1479
1480 sub clone ($) {
1481     my ($dstdir) = @_;
1482     canonicalise_suite();
1483     badusage "dry run makes no sense with clone" unless act_local();
1484     my $hasgit = check_for_git();
1485     mkdir $dstdir or die "$dstdir $!";
1486     changedir $dstdir;
1487     runcmd @git, qw(init -q);
1488     my $giturl = access_giturl(1);
1489     if (defined $giturl) {
1490         runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1491         open H, "> .git/HEAD" or die $!;
1492         print H "ref: ".lref()."\n" or die $!;
1493         close H or die $!;
1494         runcmd @git, qw(remote add), 'origin', $giturl;
1495     }
1496     if ($hasgit) {
1497         progress "fetching existing git history";
1498         git_fetch_us();
1499         runcmd_ordryrun_local @git, qw(fetch origin);
1500     } else {
1501         progress "starting new git history";
1502     }
1503     fetch_from_archive() or no_such_package;
1504     my $vcsgiturl = $dsc->{'Vcs-Git'};
1505     $vcsgiturl =~ s/\s+-b\s+\S+//g;
1506     if (length $vcsgiturl) {
1507         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1508     }
1509     runcmd @git, qw(reset --hard), lrref();
1510     printdone "ready for work in $dstdir";
1511 }
1512
1513 sub fetch () {
1514     if (check_for_git()) {
1515         git_fetch_us();
1516     }
1517     fetch_from_archive() or no_such_package();
1518     printdone "fetched into ".lrref();
1519 }
1520
1521 sub pull () {
1522     fetch();
1523     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1524         lrref();
1525     printdone "fetched to ".lrref()." and merged into HEAD";
1526 }
1527
1528 sub check_not_dirty () {
1529     return if $ignoredirty;
1530     my @cmd = (@git, qw(diff --quiet HEAD));
1531     printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1532     $!=0; $?=0; system @cmd;
1533     return if !$! && !$?;
1534     if (!$! && $?==256) {
1535         fail "working tree is dirty (does not match HEAD)";
1536     } else {
1537         failedcmd @cmd;
1538     }
1539 }
1540
1541 sub commit_admin ($) {
1542     my ($m) = @_;
1543     progress "$m";
1544     runcmd_ordryrun_local @git, qw(commit -m), $m;
1545 }
1546
1547 sub commit_quilty_patch () {
1548     my $output = cmdoutput @git, qw(status --porcelain);
1549     my %adds;
1550     foreach my $l (split /\n/, $output) {
1551         next unless $l =~ m/\S/;
1552         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1553             $adds{$1}++;
1554         }
1555     }
1556     delete $adds{'.pc'}; # if there wasn't one before, don't add it
1557     if (!%adds) {
1558         progress "nothing quilty to commit, ok.";
1559         return;
1560     }
1561     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1562     commit_admin "Commit Debian 3.0 (quilt) metadata";
1563 }
1564
1565 sub get_source_format () {
1566     if (!open F, "debian/source/format") {
1567         die $! unless $!==&ENOENT;
1568         return '';
1569     }
1570     $_ = <F>;
1571     F->error and die $!;
1572     chomp;
1573     return $_;
1574 }
1575
1576 sub madformat ($) {
1577     my ($format) = @_;
1578     return 0 unless $format eq '3.0 (quilt)';
1579     if ($quilt_mode eq 'nocheck') {
1580         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1581         return 0;
1582     }
1583     progress "Format \`$format', checking/updating patch stack";
1584     return 1;
1585 }
1586
1587 sub push_parse_changelog ($) {
1588     my ($clogpfn) = @_;
1589
1590     my $clogp = Dpkg::Control::Hash->new();
1591     $clogp->load($clogpfn) or die;
1592
1593     $package = getfield $clogp, 'Source';
1594     my $cversion = getfield $clogp, 'Version';
1595     my $tag = debiantag($cversion);
1596     runcmd @git, qw(check-ref-format), $tag;
1597
1598     my $dscfn = dscfn($cversion);
1599
1600     return ($clogp, $cversion, $tag, $dscfn);
1601 }
1602
1603 sub push_parse_dsc ($$$) {
1604     my ($dscfn,$dscfnwhat, $cversion) = @_;
1605     $dsc = parsecontrol($dscfn,$dscfnwhat);
1606     my $dversion = getfield $dsc, 'Version';
1607     my $dscpackage = getfield $dsc, 'Source';
1608     ($dscpackage eq $package && $dversion eq $cversion) or
1609         fail "$dscfn is for $dscpackage $dversion".
1610             " but debian/changelog is for $package $cversion";
1611 }
1612
1613 sub push_mktag ($$$$$$$) {
1614     my ($head,$clogp,$tag,
1615         $dscfn,
1616         $changesfile,$changesfilewhat,
1617         $tfn) = @_;
1618
1619     $dsc->{$ourdscfield[0]} = $head;
1620     $dsc->save("$dscfn.tmp") or die $!;
1621
1622     my $changes = parsecontrol($changesfile,$changesfilewhat);
1623     foreach my $field (qw(Source Distribution Version)) {
1624         $changes->{$field} eq $clogp->{$field} or
1625             fail "changes field $field \`$changes->{$field}'".
1626                 " does not match changelog \`$clogp->{$field}'";
1627     }
1628
1629     my $cversion = getfield $clogp, 'Version';
1630     my $clogsuite = getfield $clogp, 'Distribution';
1631
1632     # We make the git tag by hand because (a) that makes it easier
1633     # to control the "tagger" (b) we can do remote signing
1634     my $authline = clogp_authline $clogp;
1635     my $delibs = join(" ", "",@deliberatelies);
1636     my $declaredistro = access_basedistro();
1637     open TO, '>', $tfn->('.tmp') or die $!;
1638     print TO <<END or die $!;
1639 object $head
1640 type commit
1641 tag $tag
1642 tagger $authline
1643
1644 $package release $cversion for $clogsuite ($csuite) [dgit]
1645 [dgit distro=$declaredistro$delibs]
1646 END
1647     foreach my $ref (sort keys %supersedes) {
1648                     print TO <<END or die $!;
1649 [dgit supersede:$ref=$supersedes{$ref}]
1650 END
1651     }
1652
1653     close TO or die $!;
1654
1655     my $tagobjfn = $tfn->('.tmp');
1656     if ($sign) {
1657         if (!defined $keyid) {
1658             $keyid = access_cfg('keyid','RETURN-UNDEF');
1659         }
1660         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1661         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1662         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1663         push @sign_cmd, $tfn->('.tmp');
1664         runcmd_ordryrun @sign_cmd;
1665         if (act_scary()) {
1666             $tagobjfn = $tfn->('.signed.tmp');
1667             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1668                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1669         }
1670     }
1671
1672     return ($tagobjfn);
1673 }
1674
1675 sub sign_changes ($) {
1676     my ($changesfile) = @_;
1677     if ($sign) {
1678         my @debsign_cmd = @debsign;
1679         push @debsign_cmd, "-k$keyid" if defined $keyid;
1680         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1681         push @debsign_cmd, $changesfile;
1682         runcmd_ordryrun @debsign_cmd;
1683     }
1684 }
1685
1686 sub dopush () {
1687     printdebug "actually entering push\n";
1688     prep_ud();
1689
1690     access_giturl(); # check that success is vaguely likely
1691
1692     my $clogpfn = ".git/dgit/changelog.822.tmp";
1693     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1694
1695     responder_send_file('parsed-changelog', $clogpfn);
1696
1697     my ($clogp, $cversion, $tag, $dscfn) =
1698         push_parse_changelog("$clogpfn");
1699
1700     my $dscpath = "$buildproductsdir/$dscfn";
1701     stat_exists $dscpath or
1702         fail "looked for .dsc $dscfn, but $!;".
1703             " maybe you forgot to build";
1704
1705     responder_send_file('dsc', $dscpath);
1706
1707     push_parse_dsc($dscpath, $dscfn, $cversion);
1708
1709     my $format = getfield $dsc, 'Format';
1710     printdebug "format $format\n";
1711     if (madformat($format)) {
1712         commit_quilty_patch();
1713     }
1714     check_not_dirty();
1715     changedir $ud;
1716     progress "checking that $dscfn corresponds to HEAD";
1717     runcmd qw(dpkg-source -x --),
1718         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1719     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1720     changedir '../../../..';
1721     my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1722     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1723     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1724     $!=0; $?=0;
1725     my $r = system @diffcmd;
1726     if ($r) {
1727         if ($r==256) {
1728             fail "$dscfn specifies a different tree to your HEAD commit;".
1729                 " perhaps you forgot to build".
1730                 ($diffopt eq '--exit-code' ? "" :
1731                  " (run with -D to see full diff output)");
1732         } else {
1733             failedcmd @diffcmd;
1734         }
1735     }
1736 #fetch from alioth
1737 #do fast forward check and maybe fake merge
1738 #    if (!is_fast_fwd(mainbranch
1739 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1740 #        map { lref($_).":".rref($_) }
1741 #        (uploadbranch());
1742     my $head = rev_parse('HEAD');
1743     if (!$changesfile) {
1744         my $multi = "$buildproductsdir/".
1745             "${package}_".(stripepoch $cversion)."_multi.changes";
1746         if (stat_exists "$multi") {
1747             $changesfile = $multi;
1748         } else {
1749             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1750             my @cs = glob "$buildproductsdir/$pat";
1751             fail "failed to find unique changes file".
1752                 " (looked for $pat in $buildproductsdir, or $multi);".
1753                 " perhaps you need to use dgit -C"
1754                 unless @cs==1;
1755             ($changesfile) = @cs;
1756         }
1757     } else {
1758         $changesfile = "$buildproductsdir/$changesfile";
1759     }
1760
1761     responder_send_file('changes',$changesfile);
1762     responder_send_command("param head $head");
1763     responder_send_command("param csuite $csuite");
1764
1765     my $forceflag = deliberately('not-fast-forward') ? '+' : '';
1766     if ($forceflag && defined $lastpush_hash) {
1767         git_for_each_tag_referring($lastpush_hash, sub {
1768             my ($objid,$fullrefname,$tagname) = @_;
1769             responder_send_command("supersedes $fullrefname=$objid");
1770             $supersedes{$fullrefname} = $objid;
1771         });
1772     }
1773
1774     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1775     my $tagobjfn;
1776
1777     if ($we_are_responder) {
1778         $tagobjfn = $tfn->('.signed.tmp');
1779         responder_receive_files('signed-tag', $tagobjfn);
1780     } else {
1781         $tagobjfn =
1782             push_mktag($head,$clogp,$tag,
1783                        $dscpath,
1784                        $changesfile,$changesfile,
1785                        $tfn);
1786     }
1787
1788     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1789     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1790     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1791     runcmd_ordryrun @git, qw(tag -v --), $tag;
1792
1793     if (!check_for_git()) {
1794         create_remote_git_repo();
1795     }
1796     runcmd_ordryrun @git, qw(push),access_giturl(),
1797         $forceflag."HEAD:".rrref(), "refs/tags/$tag";
1798     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1799
1800     if ($we_are_responder) {
1801         my $dryrunsuffix = act_local() ? "" : ".tmp";
1802         responder_receive_files('signed-dsc-changes',
1803                                 "$dscpath$dryrunsuffix",
1804                                 "$changesfile$dryrunsuffix");
1805     } else {
1806         if (act_local()) {
1807             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1808         } else {
1809             progress "[new .dsc left in $dscpath.tmp]";
1810         }
1811         sign_changes $changesfile;
1812     }
1813
1814     my $host = access_cfg('upload-host','RETURN-UNDEF');
1815     my @hostarg = defined($host) ? ($host,) : ();
1816     runcmd_ordryrun @dput, @hostarg, $changesfile;
1817     printdone "pushed and uploaded $cversion";
1818
1819     responder_send_command("complete");
1820 }
1821
1822 sub cmd_clone {
1823     parseopts();
1824     my $dstdir;
1825     badusage "-p is not allowed with clone; specify as argument instead"
1826         if defined $package;
1827     if (@ARGV==1) {
1828         ($package) = @ARGV;
1829     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1830         ($package,$isuite) = @ARGV;
1831     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1832         ($package,$dstdir) = @ARGV;
1833     } elsif (@ARGV==3) {
1834         ($package,$isuite,$dstdir) = @ARGV;
1835     } else {
1836         badusage "incorrect arguments to dgit clone";
1837     }
1838     $dstdir ||= "$package";
1839
1840     if (stat_exists $dstdir) {
1841         fail "$dstdir already exists";
1842     }
1843
1844     my $cwd_remove;
1845     if ($rmonerror && !$dryrun_level) {
1846         $cwd_remove= getcwd();
1847         unshift @end, sub { 
1848             return unless defined $cwd_remove;
1849             if (!chdir "$cwd_remove") {
1850                 return if $!==&ENOENT;
1851                 die "chdir $cwd_remove: $!";
1852             }
1853             rmtree($dstdir) or die "remove $dstdir: $!\n";
1854         };
1855     }
1856
1857     clone($dstdir);
1858     $cwd_remove = undef;
1859 }
1860
1861 sub branchsuite () {
1862     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1863     if ($branch =~ m#$lbranch_re#o) {
1864         return $1;
1865     } else {
1866         return undef;
1867     }
1868 }
1869
1870 sub fetchpullargs () {
1871     if (!defined $package) {
1872         my $sourcep = parsecontrol('debian/control','debian/control');
1873         $package = getfield $sourcep, 'Source';
1874     }
1875     if (@ARGV==0) {
1876 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1877         if (!$isuite) {
1878             my $clogp = parsechangelog();
1879             $isuite = getfield $clogp, 'Distribution';
1880         }
1881         canonicalise_suite();
1882         progress "fetching from suite $csuite";
1883     } elsif (@ARGV==1) {
1884         ($isuite) = @ARGV;
1885         canonicalise_suite();
1886     } else {
1887         badusage "incorrect arguments to dgit fetch or dgit pull";
1888     }
1889 }
1890
1891 sub cmd_fetch {
1892     parseopts();
1893     fetchpullargs();
1894     fetch();
1895 }
1896
1897 sub cmd_pull {
1898     parseopts();
1899     fetchpullargs();
1900     pull();
1901 }
1902
1903 sub cmd_push {
1904     parseopts();
1905     badusage "-p is not allowed with dgit push" if defined $package;
1906     check_not_dirty();
1907     my $clogp = parsechangelog();
1908     $package = getfield $clogp, 'Source';
1909     my $specsuite;
1910     if (@ARGV==0) {
1911     } elsif (@ARGV==1) {
1912         ($specsuite) = (@ARGV);
1913     } else {
1914         badusage "incorrect arguments to dgit push";
1915     }
1916     $isuite = getfield $clogp, 'Distribution';
1917     if ($new_package) {
1918         local ($package) = $existing_package; # this is a hack
1919         canonicalise_suite();
1920     }
1921     if (defined $specsuite && $specsuite ne $isuite) {
1922         canonicalise_suite();
1923         $csuite eq $specsuite or
1924             fail "dgit push: changelog specifies $isuite ($csuite)".
1925                 " but command line specifies $specsuite";
1926     }
1927     if (check_for_git()) {
1928         git_fetch_us();
1929     }
1930     if (fetch_from_archive()) {
1931         is_fast_fwd(lrref(), 'HEAD') or
1932             fail "dgit push: HEAD is not a descendant".
1933                 " of the archive's version.\n".
1934                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1935     } else {
1936         $new_package or
1937             fail "package appears to be new in this suite;".
1938                 " if this is intentional, use --new";
1939     }
1940     dopush();
1941 }
1942
1943 #---------- remote commands' implementation ----------
1944
1945 sub cmd_remote_push_build_host {
1946     my ($nrargs) = shift @ARGV;
1947     my (@rargs) = @ARGV[0..$nrargs-1];
1948     @ARGV = @ARGV[$nrargs..$#ARGV];
1949     die unless @rargs;
1950     my ($dir,$vsnwant) = @rargs;
1951     # vsnwant is a comma-separated list; we report which we have
1952     # chosen in our ready response (so other end can tell if they
1953     # offered several)
1954     $debugprefix = ' ';
1955     $we_are_responder = 1;
1956
1957     open PI, "<&STDIN" or die $!;
1958     open STDIN, "/dev/null" or die $!;
1959     open PO, ">&STDOUT" or die $!;
1960     autoflush PO 1;
1961     open STDOUT, ">&STDERR" or die $!;
1962     autoflush STDOUT 1;
1963
1964     $vsnwant //= 1;
1965     fail "build host has dgit rpush protocol version".
1966         " $rpushprotovsn but invocation host has $vsnwant"
1967         unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1968
1969     responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1970
1971     changedir $dir;
1972     &cmd_push;
1973 }
1974
1975 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1976 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1977 #     a good error message)
1978
1979 our $i_tmp;
1980
1981 sub i_cleanup {
1982     local ($@, $?);
1983     my $report = i_child_report();
1984     if (defined $report) {
1985         printdebug "($report)\n";
1986     } elsif ($i_child_pid) {
1987         printdebug "(killing build host child $i_child_pid)\n";
1988         kill 15, $i_child_pid;
1989     }
1990     if (defined $i_tmp && !defined $initiator_tempdir) {
1991         changedir "/";
1992         eval { rmtree $i_tmp; };
1993     }
1994 }
1995
1996 END { i_cleanup(); }
1997
1998 sub i_method {
1999     my ($base,$selector,@args) = @_;
2000     $selector =~ s/\-/_/g;
2001     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2002 }
2003
2004 sub cmd_rpush {
2005     my $host = nextarg;
2006     my $dir;
2007     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2008         $host = $1;
2009         $dir = $'; #';
2010     } else {
2011         $dir = nextarg;
2012     }
2013     $dir =~ s{^-}{./-};
2014     my @rargs = ($dir,$rpushprotovsn);
2015     my @rdgit;
2016     push @rdgit, @dgit;
2017     push @rdgit, @ropts;
2018     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2019     push @rdgit, @ARGV;
2020     my @cmd = (@ssh, $host, shellquote @rdgit);
2021     printcmd \*DEBUG,$debugprefix."+",@cmd;
2022
2023     if (defined $initiator_tempdir) {
2024         rmtree $initiator_tempdir;
2025         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2026         $i_tmp = $initiator_tempdir;
2027     } else {
2028         $i_tmp = tempdir();
2029     }
2030     $i_child_pid = open2(\*RO, \*RI, @cmd);
2031     changedir $i_tmp;
2032     initiator_expect { m/^dgit-remote-push-ready/ };
2033     for (;;) {
2034         my ($icmd,$iargs) = initiator_expect {
2035             m/^(\S+)(?: (.*))?$/;
2036             ($1,$2);
2037         };
2038         i_method "i_resp", $icmd, $iargs;
2039     }
2040 }
2041
2042 sub i_resp_progress ($) {
2043     my ($rhs) = @_;
2044     my $msg = protocol_read_bytes \*RO, $rhs;
2045     progress $msg;
2046 }
2047
2048 sub i_resp_complete {
2049     my $pid = $i_child_pid;
2050     $i_child_pid = undef; # prevents killing some other process with same pid
2051     printdebug "waiting for build host child $pid...\n";
2052     my $got = waitpid $pid, 0;
2053     die $! unless $got == $pid;
2054     die "build host child failed $?" if $?;
2055
2056     i_cleanup();
2057     printdebug "all done\n";
2058     exit 0;
2059 }
2060
2061 sub i_resp_file ($) {
2062     my ($keyword) = @_;
2063     my $localname = i_method "i_localname", $keyword;
2064     my $localpath = "$i_tmp/$localname";
2065     stat_exists $localpath and
2066         badproto \*RO, "file $keyword ($localpath) twice";
2067     protocol_receive_file \*RO, $localpath;
2068     i_method "i_file", $keyword;
2069 }
2070
2071 our %i_param;
2072
2073 sub i_resp_param ($) {
2074     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2075     $i_param{$1} = $2;
2076 }
2077
2078 sub i_resp_supersedes ($) {
2079     $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2080         or badproto \*RO, "bad supersedes spec";
2081     my $r = system qw(git check-ref-format), $1;
2082     die "bad supersedes ref spec ($r)" if $r;
2083     $supersedes{$1} = $2;
2084 }
2085
2086 our %i_wanted;
2087
2088 sub i_resp_want ($) {
2089     my ($keyword) = @_;
2090     die "$keyword ?" if $i_wanted{$keyword}++;
2091     my @localpaths = i_method "i_want", $keyword;
2092     printdebug "[[  $keyword @localpaths\n";
2093     foreach my $localpath (@localpaths) {
2094         protocol_send_file \*RI, $localpath;
2095     }
2096     print RI "files-end\n" or die $!;
2097 }
2098
2099 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
2100
2101 sub i_localname_parsed_changelog {
2102     return "remote-changelog.822";
2103 }
2104 sub i_file_parsed_changelog {
2105     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
2106         push_parse_changelog "$i_tmp/remote-changelog.822";
2107     die if $i_dscfn =~ m#/|^\W#;
2108 }
2109
2110 sub i_localname_dsc {
2111     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2112     return $i_dscfn;
2113 }
2114 sub i_file_dsc { }
2115
2116 sub i_localname_changes {
2117     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2118     $i_changesfn = $i_dscfn;
2119     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2120     return $i_changesfn;
2121 }
2122 sub i_file_changes { }
2123
2124 sub i_want_signed_tag {
2125     printdebug Dumper(\%i_param, $i_dscfn);
2126     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2127         && defined $i_param{'csuite'}
2128         or badproto \*RO, "premature desire for signed-tag";
2129     my $head = $i_param{'head'};
2130     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2131
2132     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2133     $csuite = $&;
2134     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2135
2136     my $tagobjfn =
2137         push_mktag $head, $i_clogp, $i_tag,
2138             $i_dscfn,
2139             $i_changesfn, 'remote changes',
2140             sub { "tag$_[0]"; };
2141
2142     return $tagobjfn;
2143 }
2144
2145 sub i_want_signed_dsc_changes {
2146     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2147     sign_changes $i_changesfn;
2148     return ($i_dscfn, $i_changesfn);
2149 }
2150
2151 #---------- building etc. ----------
2152
2153 our $version;
2154 our $sourcechanges;
2155 our $dscfn;
2156
2157 #----- `3.0 (quilt)' handling -----
2158
2159 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2160
2161 sub quiltify_dpkg_commit ($$$;$) {
2162     my ($patchname,$author,$msg, $xinfo) = @_;
2163     $xinfo //= '';
2164
2165     mkpath '.git/dgit';
2166     my $descfn = ".git/dgit/quilt-description.tmp";
2167     open O, '>', $descfn or die "$descfn: $!";
2168     $msg =~ s/\s+$//g;
2169     $msg =~ s/\n/\n /g;
2170     $msg =~ s/^\s+$/ ./mg;
2171     print O <<END or die $!;
2172 Description: $msg
2173 Author: $author
2174 $xinfo
2175 ---
2176
2177 END
2178     close O or die $!;
2179
2180     {
2181         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2182         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2183         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2184         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2185     }
2186 }
2187
2188 sub quiltify_trees_differ ($$) {
2189     my ($x,$y) = @_;
2190     # returns 1 iff the two tree objects differ other than in debian/
2191     local $/=undef;
2192     my @cmd = (@git, qw(diff-tree --name-only -z), $x, $y);
2193     my $diffs= cmdoutput @cmd;
2194     foreach my $f (split /\0/, $diffs) {
2195         next if $f eq 'debian';
2196         return 1;
2197     }
2198     return 0;
2199 }
2200
2201 sub quiltify_tree_sentinelfiles ($) {
2202     # lists the `sentinel' files present in the tree
2203     my ($x) = @_;
2204     my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2205         qw(-- debian/rules debian/control);
2206     $r =~ s/\n/,/g;
2207     return $r;
2208 }
2209
2210 sub quiltify ($$) {
2211     my ($clogp,$target) = @_;
2212
2213     # Quilt patchification algorithm
2214     #
2215     # We search backwards through the history of the main tree's HEAD
2216     # (T) looking for a start commit S whose tree object is identical
2217     # to to the patch tip tree (ie the tree corresponding to the
2218     # current dpkg-committed patch series).  For these purposes
2219     # `identical' disregards anything in debian/ - this wrinkle is
2220     # necessary because dpkg-source treates debian/ specially.
2221     #
2222     # We can only traverse edges where at most one of the ancestors'
2223     # trees differs (in changes outside in debian/).  And we cannot
2224     # handle edges which change .pc/ or debian/patches.  To avoid
2225     # going down a rathole we avoid traversing edges which introduce
2226     # debian/rules or debian/control.  And we set a limit on the
2227     # number of edges we are willing to look at.
2228     #
2229     # If we succeed, we walk forwards again.  For each traversed edge
2230     # PC (with P parent, C child) (starting with P=S and ending with
2231     # C=T) to we do this:
2232     #  - git checkout C
2233     #  - dpkg-source --commit with a patch name and message derived from C
2234     # After traversing PT, we git commit the changes which
2235     # should be contained within debian/patches.
2236
2237     changedir '../fake';
2238     mktree_in_ud_here();
2239     rmtree '.pc';
2240     runcmd @git, 'add', '.';
2241     my $oldtiptree=git_write_tree();
2242     changedir '../work';
2243
2244     # The search for the path S..T is breadth-first.  We maintain a
2245     # todo list containing search nodes.  A search node identifies a
2246     # commit, and looks something like this:
2247     #  $p = {
2248     #      Commit => $git_commit_id,
2249     #      Child => $c,                          # or undef if P=T
2250     #      Whynot => $reason_edge_PC_unsuitable, # in @nots only
2251     #      Nontrivial => true iff $p..$c has relevant changes
2252     #  };
2253
2254     my @todo;
2255     my @nots;
2256     my $sref_S;
2257     my $max_work=100;
2258     my %considered; # saves being exponential on some weird graphs
2259
2260     my $t_sentinels = quiltify_tree_sentinelfiles $target;
2261
2262     my $not = sub {
2263         my ($search,$whynot) = @_;
2264         printdebug " search NOT $search->{Commit} $whynot\n";
2265         $search->{Whynot} = $whynot;
2266         push @nots, $search;
2267         no warnings qw(exiting);
2268         next;
2269     };
2270
2271     push @todo, {
2272         Commit => $target,
2273     };
2274
2275     while (@todo) {
2276         my $c = shift @todo;
2277         next if $considered{$c->{Commit}}++;
2278
2279         $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2280
2281         printdebug "quiltify investigate $c->{Commit}\n";
2282
2283         # are we done?
2284         if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2285             printdebug " search finished hooray!\n";
2286             $sref_S = $c;
2287             last;
2288         }
2289
2290         if ($quilt_mode eq 'nofix') {
2291             fail "quilt fixup required but quilt mode is \`nofix'\n".
2292                 "HEAD commit $c->{Commit} differs from tree implied by ".
2293                 " debian/patches (tree object $oldtiptree)";
2294         }
2295         if ($quilt_mode eq 'smash') {
2296             printdebug " search quitting smash\n";
2297             last;
2298         }
2299
2300         my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2301         $not->($c, "has $c_sentinels not $t_sentinels")
2302             if $c_sentinels ne $t_sentinels;
2303
2304         my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2305         $commitdata =~ m/\n\n/;
2306         $commitdata =~ $`;
2307         my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2308         @parents = map { { Commit => $_, Child => $c } } @parents;
2309
2310         $not->($c, "root commit") if !@parents;
2311
2312         foreach my $p (@parents) {
2313             $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2314         }
2315         my $ndiffers = grep { $_->{Nontrivial} } @parents;
2316         $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2317
2318         foreach my $p (@parents) {
2319             printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2320
2321             my @cmd= (@git, qw(diff-tree -r --name-only),
2322                       $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2323             my $patchstackchange = cmdoutput @cmd;
2324             if (length $patchstackchange) {
2325                 $patchstackchange =~ s/\n/,/g;
2326                 $not->($p, "changed $patchstackchange");
2327             }
2328
2329             printdebug " search queue P=$p->{Commit} ",
2330                 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2331             push @todo, $p;
2332         }
2333     }
2334
2335     if (!$sref_S) {
2336         printdebug "quiltify want to smash\n";
2337
2338         my $abbrev = sub {
2339             my $x = $_[0]{Commit};
2340             $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2341             return $;
2342         };
2343         my $reportnot = sub {
2344             my ($notp) = @_;
2345             my $s = $abbrev->($notp);
2346             my $c = $notp->{Child};
2347             $s .= "..".$abbrev->($c) if $c;
2348             $s .= ": ".$c->{Whynot};
2349             return $s;
2350         };
2351         if ($quilt_mode eq 'linear') {
2352             print STDERR "$us: quilt fixup cannot be linear.  Stopped at:\n";
2353             foreach my $notp (@nots) {
2354                 print STDERR "$us:  ", $reportnot->($notp), "\n";
2355             }
2356             fail "quilt fixup naive history linearisation failed.\n".
2357  "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2358         } elsif ($quilt_mode eq 'smash') {
2359         } elsif ($quilt_mode eq 'auto') {
2360             progress "quilt fixup cannot be linear, smashing...";
2361         } else {
2362             die "$quilt_mode ?";
2363         }
2364
2365         my $time = time;
2366         my $ncommits = 3;
2367         my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2368
2369         quiltify_dpkg_commit "auto-$version-$target-$time",
2370             (getfield $clogp, 'Maintainer'),
2371             "Automatically generated patch ($clogp->{Version})\n".
2372             "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2373         return;
2374     }
2375
2376     progress "quiltify linearisation planning successful, executing...";
2377
2378     for (my $p = $sref_S;
2379          my $c = $p->{Child};
2380          $p = $p->{Child}) {
2381         printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2382         next unless $p->{Nontrivial};
2383
2384         my $cc = $c->{Commit};
2385
2386         my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2387         $commitdata =~ m/\n\n/ or die "$c ?";
2388         $commitdata = $`;
2389         my $msg = $'; #';
2390         $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2391         my $author = $1;
2392
2393         $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2394
2395         my $title = $1;
2396         my $patchname = $title;
2397         $patchname =~ s/[.:]$//;
2398         $patchname =~ y/ A-Z/-a-z/;
2399         $patchname =~ y/-a-z0-9_.+=~//cd;
2400         $patchname =~ s/^\W/x-$&/;
2401         $patchname = substr($patchname,0,40);
2402         my $index;
2403         for ($index='';
2404              stat "debian/patches/$patchname$index";
2405              $index++) { }
2406         $!==ENOENT or die "$patchname$index $!";
2407
2408         runcmd @git, qw(checkout -q), $cc;
2409
2410         # We use the tip's changelog so that dpkg-source doesn't
2411         # produce complaining messages from dpkg-parsechangelog.  None
2412         # of the information dpkg-source gets from the changelog is
2413         # actually relevant - it gets put into the original message
2414         # which dpkg-source provides our stunt editor, and then
2415         # overwritten.
2416         runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2417
2418         quiltify_dpkg_commit "$patchname$index", $author, $msg,
2419             "X-Dgit-Generated: $clogp->{Version} $cc\n";
2420
2421         runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
2422     }
2423
2424     runcmd @git, qw(checkout -q master);
2425 }
2426
2427 sub build_maybe_quilt_fixup () {
2428     my $format=get_source_format;
2429     return unless madformat $format;
2430     # sigh
2431
2432     # Our objective is:
2433     #  - honour any existing .pc in case it has any strangeness
2434     #  - determine the git commit corresponding to the tip of
2435     #    the patch stack (if there is one)
2436     #  - if there is such a git commit, convert each subsequent
2437     #    git commit into a quilt patch with dpkg-source --commit
2438     #  - otherwise convert all the differences in the tree into
2439     #    a single git commit
2440     #
2441     # To do this we:
2442
2443     # Our git tree doesn't necessarily contain .pc.  (Some versions of
2444     # dgit would include the .pc in the git tree.)  If there isn't
2445     # one, we need to generate one by unpacking the patches that we
2446     # have.
2447     #
2448     # We first look for a .pc in the git tree.  If there is one, we
2449     # will use it.  (This is not the normal case.)
2450     #
2451     # Otherwise need to regenerate .pc so that dpkg-source --commit
2452     # can work.  We do this as follows:
2453     #     1. Collect all relevant .orig from parent directory
2454     #     2. Generate a debian.tar.gz out of
2455     #         debian/{patches,rules,source/format}
2456     #     3. Generate a fake .dsc containing just these fields:
2457     #          Format Source Version Files
2458     #     4. Extract the fake .dsc
2459     #        Now the fake .dsc has a .pc directory.
2460     # (In fact we do this in every case, because in future we will
2461     # want to search for a good base commit for generating patches.)
2462     #
2463     # Then we can actually do the dpkg-source --commit
2464     #     1. Make a new working tree with the same object
2465     #        store as our main tree and check out the main
2466     #        tree's HEAD.
2467     #     2. Copy .pc from the fake's extraction, if necessary
2468     #     3. Run dpkg-source --commit
2469     #     4. If the result has changes to debian/, then
2470     #          - git-add them them
2471     #          - git-add .pc if we had a .pc in-tree
2472     #          - git-commit
2473     #     5. If we had a .pc in-tree, delete it, and git-commit
2474     #     6. Back in the main tree, fast forward to the new HEAD
2475
2476     my $clogp = parsechangelog();
2477     my $headref = rev_parse('HEAD');
2478
2479     prep_ud();
2480     changedir $ud;
2481
2482     my $upstreamversion=$version;
2483     $upstreamversion =~ s/-[^-]*$//;
2484
2485     my $fakeversion="$upstreamversion-~~DGITFAKE";
2486
2487     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2488     print $fakedsc <<END or die $!;
2489 Format: 3.0 (quilt)
2490 Source: $package
2491 Version: $fakeversion
2492 Files:
2493 END
2494
2495     my $dscaddfile=sub {
2496         my ($b) = @_;
2497         
2498         my $md = new Digest::MD5;
2499
2500         my $fh = new IO::File $b, '<' or die "$b $!";
2501         stat $fh or die $!;
2502         my $size = -s _;
2503
2504         $md->addfile($fh);
2505         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2506     };
2507
2508     foreach my $f (<../../../../*>) { #/){
2509         my $b=$f; $b =~ s{.*/}{};
2510         next unless is_orig_file $b, srcfn $upstreamversion,'';
2511         link $f, $b or die "$b $!";
2512         $dscaddfile->($b);
2513     }
2514
2515     my @files=qw(debian/source/format debian/rules);
2516     if (stat_exists '../../../debian/patches') {
2517         push @files, 'debian/patches';
2518     }
2519
2520     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2521     runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2522
2523     $dscaddfile->($debtar);
2524     close $fakedsc or die $!;
2525
2526     runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2527
2528     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2529     rename $fakexdir, "fake" or die "$fakexdir $!";
2530
2531     mkdir "work" or die $!;
2532     changedir "work";
2533     mktree_in_ud_here();
2534     runcmd @git, qw(reset --hard), $headref;
2535
2536     my $mustdeletepc=0;
2537     if (stat_exists ".pc") {
2538         -d _ or die;
2539         progress "Tree already contains .pc - will use it then delete it.";
2540         $mustdeletepc=1;
2541     } else {
2542         rename '../fake/.pc','.pc' or die $!;
2543     }
2544
2545     quiltify($clogp,$headref);
2546
2547     if (!open P, '>>', ".pc/applied-patches") {
2548         $!==&ENOENT or die $!;
2549     } else {
2550         close P;
2551     }
2552
2553     commit_quilty_patch();
2554
2555     if ($mustdeletepc) {
2556         runcmd @git, qw(rm -rq .pc);
2557         commit_admin "Commit removal of .pc (quilt series tracking data)";
2558     }
2559
2560     changedir '../../../..';
2561     runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2562 }
2563
2564 sub quilt_fixup_editor () {
2565     my $descfn = $ENV{$fakeeditorenv};
2566     my $editing = $ARGV[$#ARGV];
2567     open I1, '<', $descfn or die "$descfn: $!";
2568     open I2, '<', $editing or die "$editing: $!";
2569     unlink $editing or die "$editing: $!";
2570     open O, '>', $editing or die "$editing: $!";
2571     while (<I1>) { print O or die $!; } I1->error and die $!;
2572     my $copying = 0;
2573     while (<I2>) {
2574         $copying ||= m/^\-\-\- /;
2575         next unless $copying;
2576         print O or die $!;
2577     }
2578     I2->error and die $!;
2579     close O or die $1;
2580     exit 0;
2581 }
2582
2583 #----- other building -----
2584
2585 sub clean_tree () {
2586     if ($cleanmode eq 'dpkg-source') {
2587         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2588     } elsif ($cleanmode eq 'git') {
2589         runcmd_ordryrun_local @git, qw(clean -xdf);
2590     } elsif ($cleanmode eq 'none') {
2591     } else {
2592         die "$cleanmode ?";
2593     }
2594 }
2595
2596 sub cmd_clean () {
2597     badusage "clean takes no additional arguments" if @ARGV;
2598     clean_tree();
2599 }
2600
2601 sub build_prep () {
2602     badusage "-p is not allowed when building" if defined $package;
2603     check_not_dirty();
2604     clean_tree();
2605     my $clogp = parsechangelog();
2606     $isuite = getfield $clogp, 'Distribution';
2607     $package = getfield $clogp, 'Source';
2608     $version = getfield $clogp, 'Version';
2609     build_maybe_quilt_fixup();
2610 }
2611
2612 sub changesopts () {
2613     my @opts =@changesopts[1..$#changesopts];
2614     if (!defined $changes_since_version) {
2615         my @vsns = archive_query('archive_query');
2616         my @quirk = access_quirk();
2617         if ($quirk[0] eq 'backports') {
2618             local $isuite = $quirk[2];
2619             local $csuite;
2620             canonicalise_suite();
2621             push @vsns, archive_query('archive_query');
2622         }
2623         if (@vsns) {
2624             @vsns = map { $_->[0] } @vsns;
2625             @vsns = sort { -version_compare($a, $b) } @vsns;
2626             $changes_since_version = $vsns[0];
2627             progress "changelog will contain changes since $vsns[0]";
2628         } else {
2629             $changes_since_version = '_';
2630             progress "package seems new, not specifying -v<version>";
2631         }
2632     }
2633     if ($changes_since_version ne '_') {
2634         unshift @opts, "-v$changes_since_version";
2635     }
2636     return @opts;
2637 }
2638
2639 sub cmd_build {
2640     build_prep();
2641     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2642     printdone "build successful\n";
2643 }
2644
2645 sub cmd_git_build {
2646     build_prep();
2647     my @cmd =
2648         (qw(git-buildpackage -us -uc --git-no-sign-tags),
2649          "--git-builder=@dpkgbuildpackage");
2650     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2651         canonicalise_suite();
2652         push @cmd, "--git-debian-branch=".lbranch();
2653     }
2654     push @cmd, changesopts();
2655     runcmd_ordryrun_local @cmd, @ARGV;
2656     printdone "build successful\n";
2657 }
2658
2659 sub build_source {
2660     build_prep();
2661     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2662     $dscfn = dscfn($version);
2663     if ($cleanmode eq 'dpkg-source') {
2664         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2665             changesopts();
2666     } else {
2667         my $pwd = must_getcwd();
2668         my $leafdir = basename $pwd;
2669         changedir "..";
2670         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2671         changedir $pwd;
2672         runcmd_ordryrun_local qw(sh -ec),
2673             'exec >$1; shift; exec "$@"','x',
2674             "../$sourcechanges",
2675             @dpkggenchanges, qw(-S), changesopts();
2676     }
2677 }
2678
2679 sub cmd_build_source {
2680     badusage "build-source takes no additional arguments" if @ARGV;
2681     build_source();
2682     printdone "source built, results in $dscfn and $sourcechanges";
2683 }
2684
2685 sub cmd_sbuild {
2686     build_source();
2687     changedir "..";
2688     my $pat = "${package}_".(stripepoch $version)."_*.changes";
2689     if (act_local()) {
2690         stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2691         stat_exists $sourcechanges
2692             or fail "$sourcechanges (in parent directory): $!";
2693         foreach my $cf (glob $pat) {
2694             next if $cf eq $sourcechanges;
2695             unlink $cf or fail "remove $cf: $!";
2696         }
2697     }
2698     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2699     my @changesfiles = glob $pat;
2700     @changesfiles = sort {
2701         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2702             or $a cmp $b
2703     } @changesfiles;
2704     fail "wrong number of different changes files (@changesfiles)"
2705         unless @changesfiles;
2706     runcmd_ordryrun_local @mergechanges, @changesfiles;
2707     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2708     if (act_local()) {
2709         stat_exists $multichanges or fail "$multichanges: $!";
2710     }
2711     printdone "build successful, results in $multichanges\n" or die $!;
2712 }    
2713
2714 sub cmd_quilt_fixup {
2715     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2716     my $clogp = parsechangelog();
2717     $version = getfield $clogp, 'Version';
2718     $package = getfield $clogp, 'Source';
2719     build_maybe_quilt_fixup();
2720 }
2721
2722 sub cmd_archive_api_query {
2723     badusage "need only 1 subpath argument" unless @ARGV==1;
2724     my ($subpath) = @ARGV;
2725     my @cmd = archive_api_query_cmd($subpath);
2726     exec @cmd or fail "exec curl: $!\n";
2727 }
2728
2729 #---------- argument parsing and main program ----------
2730
2731 sub cmd_version {
2732     print "dgit version $our_version\n" or die $!;
2733     exit 0;
2734 }
2735
2736 sub parseopts () {
2737     my $om;
2738
2739     if (defined $ENV{'DGIT_SSH'}) {
2740         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2741     } elsif (defined $ENV{'GIT_SSH'}) {
2742         @ssh = ($ENV{'GIT_SSH'});
2743     }
2744
2745     while (@ARGV) {
2746         last unless $ARGV[0] =~ m/^-/;
2747         $_ = shift @ARGV;
2748         last if m/^--?$/;
2749         if (m/^--/) {
2750             if (m/^--dry-run$/) {
2751                 push @ropts, $_;
2752                 $dryrun_level=2;
2753             } elsif (m/^--damp-run$/) {
2754                 push @ropts, $_;
2755                 $dryrun_level=1;
2756             } elsif (m/^--no-sign$/) {
2757                 push @ropts, $_;
2758                 $sign=0;
2759             } elsif (m/^--help$/) {
2760                 cmd_help();
2761             } elsif (m/^--version$/) {
2762                 cmd_version();
2763             } elsif (m/^--new$/) {
2764                 push @ropts, $_;
2765                 $new_package=1;
2766             } elsif (m/^--since-version=([^_]+|_)$/) {
2767                 push @ropts, $_;
2768                 $changes_since_version = $1;
2769             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2770                      ($om = $opts_opt_map{$1}) &&
2771                      length $om->[0]) {
2772                 push @ropts, $_;
2773                 $om->[0] = $2;
2774             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2775                      !$opts_opt_cmdonly{$1} &&
2776                      ($om = $opts_opt_map{$1})) {
2777                 push @ropts, $_;
2778                 push @$om, $2;
2779             } elsif (m/^--existing-package=(.*)/s) {
2780                 push @ropts, $_;
2781                 $existing_package = $1;
2782             } elsif (m/^--initiator-tempdir=(.*)/s) {
2783                 $initiator_tempdir = $1;
2784                 $initiator_tempdir =~ m#^/# or
2785                     badusage "--initiator-tempdir must be used specify an".
2786                         " absolute, not relative, directory."
2787             } elsif (m/^--distro=(.*)/s) {
2788                 push @ropts, $_;
2789                 $idistro = $1;
2790             } elsif (m/^--build-products-dir=(.*)/s) {
2791                 push @ropts, $_;
2792                 $buildproductsdir = $1;
2793             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2794                 push @ropts, $_;
2795                 $cleanmode = $1;
2796             } elsif (m/^--clean=(.*)$/s) {
2797                 badusage "unknown cleaning mode \`$1'";
2798             } elsif (m/^--quilt=($quilt_modes_re)$/s) {
2799                 push @ropts, $_;
2800                 $quilt_mode = $1;
2801             } elsif (m/^--quilt=(.*)$/s) {
2802                 badusage "unknown quilt fixup mode \`$1'";
2803             } elsif (m/^--ignore-dirty$/s) {
2804                 push @ropts, $_;
2805                 $ignoredirty = 1;
2806             } elsif (m/^--no-quilt-fixup$/s) {
2807                 push @ropts, $_;
2808                 $quilt_mode = 'nocheck';
2809             } elsif (m/^--no-rm-on-error$/s) {
2810                 push @ropts, $_;
2811                 $rmonerror = 0;
2812             } elsif (m/^--deliberately-($suite_re)$/s) {
2813                 push @ropts, $_;
2814                 push @deliberatelies, $&;
2815             } else {
2816                 badusage "unknown long option \`$_'";
2817             }
2818         } else {
2819             while (m/^-./s) {
2820                 if (s/^-n/-/) {
2821                     push @ropts, $&;
2822                     $dryrun_level=2;
2823                 } elsif (s/^-L/-/) {
2824                     push @ropts, $&;
2825                     $dryrun_level=1;
2826                 } elsif (s/^-h/-/) {
2827                     cmd_help();
2828                 } elsif (s/^-D/-/) {
2829                     push @ropts, $&;
2830                     open DEBUG, ">&STDERR" or die $!;
2831                     autoflush DEBUG 1;
2832                     $debug++;
2833                 } elsif (s/^-N/-/) {
2834                     push @ropts, $&;
2835                     $new_package=1;
2836                 } elsif (s/^-v([^_]+|_)$//s) {
2837                     push @ropts, $&;
2838                     $changes_since_version = $1;
2839                 } elsif (m/^-m/) {
2840                     push @ropts, $&;
2841                     push @changesopts, $_;
2842                     $_ = '';
2843                 } elsif (s/^-c(.*=.*)//s) {
2844                     push @ropts, $&;
2845                     push @git, '-c', $1;
2846                 } elsif (s/^-d(.+)//s) {
2847                     push @ropts, $&;
2848                     $idistro = $1;
2849                 } elsif (s/^-C(.+)//s) {
2850                     push @ropts, $&;
2851                     $changesfile = $1;
2852                     if ($changesfile =~ s#^(.*)/##) {
2853                         $buildproductsdir = $1;
2854                     }
2855                 } elsif (s/^-k(.+)//s) {
2856                     $keyid=$1;
2857                 } elsif (m/^-[vdCk]$/) {
2858                     badusage
2859  "option \`$_' requires an argument (and no space before the argument)";
2860                 } elsif (s/^-wn$//s) {
2861                     push @ropts, $&;
2862                     $cleanmode = 'none';
2863                 } elsif (s/^-wg$//s) {
2864                     push @ropts, $&;
2865                     $cleanmode = 'git';
2866                 } elsif (s/^-wd$//s) {
2867                     push @ropts, $&;
2868                     $cleanmode = 'dpkg-source';
2869                 } else {
2870                     badusage "unknown short option \`$_'";
2871                 }
2872             }
2873         }
2874     }
2875 }
2876
2877 if ($ENV{$fakeeditorenv}) {
2878     quilt_fixup_editor();
2879 }
2880
2881 parseopts();
2882 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2883 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2884     if $dryrun_level == 1;
2885 if (!@ARGV) {
2886     print STDERR $helpmsg or die $!;
2887     exit 8;
2888 }
2889 my $cmd = shift @ARGV;
2890 $cmd =~ y/-/_/;
2891
2892 if (!defined $quilt_mode) {
2893     $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
2894         // access_cfg('quilt-mode', 'RETURN-UNDEF')
2895         // 'linear';
2896     $quilt_mode =~ m/^($quilt_modes_re)$/ 
2897         or badcfg "unknown quilt-mode \`$quilt_mode'";
2898     $quilt_mode = $1;
2899 }
2900
2901 my $fn = ${*::}{"cmd_$cmd"};
2902 $fn or badusage "unknown operation $cmd";
2903 $fn->();