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