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