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