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