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