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