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