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