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