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