chiark / gitweb /
Split tags: Preparation: Reorganise tagwants and mktags
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013-2015 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 Debian::Dgit;
23 setup_sigwarn();
24
25 use IO::Handle;
26 use Data::Dumper;
27 use LWP::UserAgent;
28 use Dpkg::Control::Hash;
29 use File::Path;
30 use File::Temp qw(tempdir);
31 use File::Basename;
32 use Dpkg::Version;
33 use POSIX;
34 use IPC::Open2;
35 use Digest::SHA;
36 use Digest::MD5;
37 use List::MoreUtils qw(pairwise);
38
39 use Debian::Dgit;
40
41 our $our_version = 'UNRELEASED'; ###substituted###
42
43 our @rpushprotovsn_support = qw(3 2); # 4 is new tag format
44 our $protovsn;
45
46 our $isuite = 'unstable';
47 our $idistro;
48 our $package;
49 our @ropts;
50
51 our $sign = 1;
52 our $dryrun_level = 0;
53 our $changesfile;
54 our $buildproductsdir = '..';
55 our $new_package = 0;
56 our $ignoredirty = 0;
57 our $rmonerror = 1;
58 our @deliberatelies;
59 our %previously;
60 our $existing_package = 'dpkg';
61 our $cleanmode;
62 our $changes_since_version;
63 our $rmchanges;
64 our $quilt_mode;
65 our $quilt_modes_re = 'linear|smash|auto|nofix|nocheck|gbp|unapplied';
66 our $we_are_responder;
67 our $initiator_tempdir;
68 our $patches_applied_dirtily = 00;
69 our $tagformat_want;
70 our $tagformat;
71 our $tagformatfn;
72
73 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
74
75 our $suite_re = '[-+.0-9a-z]+';
76 our $cleanmode_re = 'dpkg-source(?:-d)?|git|git-ff|check|none';
77
78 our $git_authline_re = '^([^<>]+) \<(\S+)\> (\d+ [-+]\d+)$';
79 our $splitbraincache = 'dgit-intern/quilt-cache';
80
81 our (@git) = qw(git);
82 our (@dget) = qw(dget);
83 our (@curl) = qw(curl -f);
84 our (@dput) = qw(dput);
85 our (@debsign) = qw(debsign);
86 our (@gpg) = qw(gpg);
87 our (@sbuild) = qw(sbuild);
88 our (@ssh) = 'ssh';
89 our (@dgit) = qw(dgit);
90 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
91 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
92 our (@dpkggenchanges) = qw(dpkg-genchanges);
93 our (@mergechanges) = qw(mergechanges -f);
94 our (@gbp) = qw(gbp);
95 our (@changesopts) = ('');
96
97 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
98                      'curl' => \@curl,
99                      'dput' => \@dput,
100                      'debsign' => \@debsign,
101                      'gpg' => \@gpg,
102                      'sbuild' => \@sbuild,
103                      'ssh' => \@ssh,
104                      'dgit' => \@dgit,
105                      'git' => \@git,
106                      'dpkg-source' => \@dpkgsource,
107                      'dpkg-buildpackage' => \@dpkgbuildpackage,
108                      'dpkg-genchanges' => \@dpkggenchanges,
109                      'gbp' => \@gbp,
110                      'ch' => \@changesopts,
111                      'mergechanges' => \@mergechanges);
112
113 our %opts_opt_cmdonly = ('gpg' => 1, 'git' => 1);
114 our %opts_cfg_insertpos = map {
115     $_,
116     scalar @{ $opts_opt_map{$_} }
117 } keys %opts_opt_map;
118
119 sub finalise_opts_opts();
120
121 our $keyid;
122
123 autoflush STDOUT 1;
124
125 our $supplementary_message = '';
126 our $need_split_build_invocation = 0;
127 our $split_brain = 0;
128
129 END {
130     local ($@, $?);
131     print STDERR "! $_\n" foreach $supplementary_message =~ m/^.+$/mg;
132 }
133
134 our $remotename = 'dgit';
135 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
136 our $csuite;
137 our $instead_distro;
138
139 sub debiantag ($$) {
140     my ($v,$distro) = @_;
141     return $tagformatfn->($v, $distro);
142 }
143
144 sub lbranch () { return "$branchprefix/$csuite"; }
145 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
146 sub lref () { return "refs/heads/".lbranch(); }
147 sub lrref () { return "refs/remotes/$remotename/".server_branch($csuite); }
148 sub rrref () { return server_ref($csuite); }
149
150 sub lrfetchrefs () { return "refs/dgit-fetch/$csuite"; }
151
152 sub stripepoch ($) {
153     my ($vsn) = @_;
154     $vsn =~ s/^\d+\://;
155     return $vsn;
156 }
157
158 sub srcfn ($$) {
159     my ($vsn,$sfx) = @_;
160     return "${package}_".(stripepoch $vsn).$sfx
161 }
162
163 sub dscfn ($) {
164     my ($vsn) = @_;
165     return srcfn($vsn,".dsc");
166 }
167
168 sub changespat ($;$) {
169     my ($vsn, $arch) = @_;
170     return "${package}_".(stripepoch $vsn)."_".($arch//'*').".changes";
171 }
172
173 our $us = 'dgit';
174 initdebug('');
175
176 our @end;
177 END { 
178     local ($?);
179     foreach my $f (@end) {
180         eval { $f->(); };
181         print STDERR "$us: cleanup: $@" if length $@;
182     }
183 };
184
185 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
186
187 sub no_such_package () {
188     print STDERR "$us: package $package does not exist in suite $isuite\n";
189     exit 4;
190 }
191
192 sub fetchspec () {
193     local $csuite = '*';
194     return  "+".rrref().":".lrref();
195 }
196
197 sub changedir ($) {
198     my ($newdir) = @_;
199     printdebug "CD $newdir\n";
200     chdir $newdir or die "chdir: $newdir: $!";
201 }
202
203 sub deliberately ($) {
204     my ($enquiry) = @_;
205     return !!grep { $_ eq "--deliberately-$enquiry" } @deliberatelies;
206 }
207
208 sub deliberately_not_fast_forward () {
209     foreach (qw(not-fast-forward fresh-repo)) {
210         return 1 if deliberately($_) || deliberately("TEST-dgit-only-$_");
211     }
212 }
213
214 sub quiltmode_splitbrain () {
215     $quilt_mode =~ m/gbp|dpm|unapplied/;
216 }
217
218 #---------- remote protocol support, common ----------
219
220 # remote push initiator/responder protocol:
221 #  $ dgit remote-push-build-host <n-rargs> <rargs>... <push-args>...
222 #  where <rargs> is <push-host-dir> <supported-proto-vsn>,... ...
223 #  < dgit-remote-push-ready <actual-proto-vsn>
224 #
225 # occasionally:
226 #
227 #  > progress NBYTES
228 #  [NBYTES message]
229 #
230 #  > supplementary-message NBYTES          # $protovsn >= 3
231 #  [NBYTES message]
232 #
233 # main sequence:
234 #
235 #  > file parsed-changelog
236 #  [indicates that output of dpkg-parsechangelog follows]
237 #  > data-block NBYTES
238 #  > [NBYTES bytes of data (no newline)]
239 #  [maybe some more blocks]
240 #  > data-end
241 #
242 #  > file dsc
243 #  [etc]
244 #
245 #  > file changes
246 #  [etc]
247 #
248 #  > param head HEAD
249 #  > param csuite SUITE
250 #  > param tagformat old|new
251 #
252 #  > previously REFNAME=OBJNAME       # if --deliberately-not-fast-forward
253 #                                     # goes into tag, for replay prevention
254 #
255 #  > want signed-tag
256 #  [indicates that signed tag is wanted]
257 #  < data-block NBYTES
258 #  < [NBYTES bytes of data (no newline)]
259 #  [maybe some more blocks]
260 #  < data-end
261 #  < files-end
262 #
263 #  > want signed-dsc-changes
264 #  < data-block NBYTES    [transfer of signed dsc]
265 #  [etc]
266 #  < data-block NBYTES    [transfer of signed changes]
267 #  [etc]
268 #  < files-end
269 #
270 #  > complete
271
272 our $i_child_pid;
273
274 sub i_child_report () {
275     # Sees if our child has died, and reap it if so.  Returns a string
276     # describing how it died if it failed, or undef otherwise.
277     return undef unless $i_child_pid;
278     my $got = waitpid $i_child_pid, WNOHANG;
279     return undef if $got <= 0;
280     die unless $got == $i_child_pid;
281     $i_child_pid = undef;
282     return undef unless $?;
283     return "build host child ".waitstatusmsg();
284 }
285
286 sub badproto ($$) {
287     my ($fh, $m) = @_;
288     fail "connection lost: $!" if $fh->error;
289     fail "protocol violation; $m not expected";
290 }
291
292 sub badproto_badread ($$) {
293     my ($fh, $wh) = @_;
294     fail "connection lost: $!" if $!;
295     my $report = i_child_report();
296     fail $report if defined $report;
297     badproto $fh, "eof (reading $wh)";
298 }
299
300 sub protocol_expect (&$) {
301     my ($match, $fh) = @_;
302     local $_;
303     $_ = <$fh>;
304     defined && chomp or badproto_badread $fh, "protocol message";
305     if (wantarray) {
306         my @r = &$match;
307         return @r if @r;
308     } else {
309         my $r = &$match;
310         return $r if $r;
311     }
312     badproto $fh, "\`$_'";
313 }
314
315 sub protocol_send_file ($$) {
316     my ($fh, $ourfn) = @_;
317     open PF, "<", $ourfn or die "$ourfn: $!";
318     for (;;) {
319         my $d;
320         my $got = read PF, $d, 65536;
321         die "$ourfn: $!" unless defined $got;
322         last if !$got;
323         print $fh "data-block ".length($d)."\n" or die $!;
324         print $fh $d or die $!;
325     }
326     PF->error and die "$ourfn $!";
327     print $fh "data-end\n" or die $!;
328     close PF;
329 }
330
331 sub protocol_read_bytes ($$) {
332     my ($fh, $nbytes) = @_;
333     $nbytes =~ m/^[1-9]\d{0,5}$|^0$/ or badproto \*RO, "bad byte count";
334     my $d;
335     my $got = read $fh, $d, $nbytes;
336     $got==$nbytes or badproto_badread $fh, "data block";
337     return $d;
338 }
339
340 sub protocol_receive_file ($$) {
341     my ($fh, $ourfn) = @_;
342     printdebug "() $ourfn\n";
343     open PF, ">", $ourfn or die "$ourfn: $!";
344     for (;;) {
345         my ($y,$l) = protocol_expect {
346             m/^data-block (.*)$/ ? (1,$1) :
347             m/^data-end$/ ? (0,) :
348             ();
349         } $fh;
350         last unless $y;
351         my $d = protocol_read_bytes $fh, $l;
352         print PF $d or die $!;
353     }
354     close PF or die $!;
355 }
356
357 #---------- remote protocol support, responder ----------
358
359 sub responder_send_command ($) {
360     my ($command) = @_;
361     return unless $we_are_responder;
362     # called even without $we_are_responder
363     printdebug ">> $command\n";
364     print PO $command, "\n" or die $!;
365 }    
366
367 sub responder_send_file ($$) {
368     my ($keyword, $ourfn) = @_;
369     return unless $we_are_responder;
370     printdebug "]] $keyword $ourfn\n";
371     responder_send_command "file $keyword";
372     protocol_send_file \*PO, $ourfn;
373 }
374
375 sub responder_receive_files ($@) {
376     my ($keyword, @ourfns) = @_;
377     die unless $we_are_responder;
378     printdebug "[[ $keyword @ourfns\n";
379     responder_send_command "want $keyword";
380     foreach my $fn (@ourfns) {
381         protocol_receive_file \*PI, $fn;
382     }
383     printdebug "[[\$\n";
384     protocol_expect { m/^files-end$/ } \*PI;
385 }
386
387 #---------- remote protocol support, initiator ----------
388
389 sub initiator_expect (&) {
390     my ($match) = @_;
391     protocol_expect { &$match } \*RO;
392 }
393
394 #---------- end remote code ----------
395
396 sub progress {
397     if ($we_are_responder) {
398         my $m = join '', @_;
399         responder_send_command "progress ".length($m) or die $!;
400         print PO $m or die $!;
401     } else {
402         print @_, "\n";
403     }
404 }
405
406 our $ua;
407
408 sub url_get {
409     if (!$ua) {
410         $ua = LWP::UserAgent->new();
411         $ua->env_proxy;
412     }
413     my $what = $_[$#_];
414     progress "downloading $what...";
415     my $r = $ua->get(@_) or die $!;
416     return undef if $r->code == 404;
417     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
418     return $r->decoded_content(charset => 'none');
419 }
420
421 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
422
423 sub runcmd {
424     debugcmd "+",@_;
425     $!=0; $?=-1;
426     failedcmd @_ if system @_;
427 }
428
429 sub act_local () { return $dryrun_level <= 1; }
430 sub act_scary () { return !$dryrun_level; }
431
432 sub printdone {
433     if (!$dryrun_level) {
434         progress "dgit ok: @_";
435     } else {
436         progress "would be ok: @_ (but dry run only)";
437     }
438 }
439
440 sub dryrun_report {
441     printcmd(\*STDERR,$debugprefix."#",@_);
442 }
443
444 sub runcmd_ordryrun {
445     if (act_scary()) {
446         runcmd @_;
447     } else {
448         dryrun_report @_;
449     }
450 }
451
452 sub runcmd_ordryrun_local {
453     if (act_local()) {
454         runcmd @_;
455     } else {
456         dryrun_report @_;
457     }
458 }
459
460 sub shell_cmd {
461     my ($first_shell, @cmd) = @_;
462     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
463 }
464
465 our $helpmsg = <<END;
466 main usages:
467   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
468   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
469   dgit [dgit-opts] build [dpkg-buildpackage-opts]
470   dgit [dgit-opts] sbuild [sbuild-opts]
471   dgit [dgit-opts] push [dgit-opts] [suite]
472   dgit [dgit-opts] rpush build-host:build-dir ...
473 important dgit options:
474   -k<keyid>           sign tag and package with <keyid> instead of default
475   --dry-run -n        do not change anything, but go through the motions
476   --damp-run -L       like --dry-run but make local changes, without signing
477   --new -N            allow introducing a new package
478   --debug -D          increase debug level
479   -c<name>=<value>    set git config option (used directly by dgit too)
480 END
481
482 our $later_warning_msg = <<END;
483 Perhaps the upload is stuck in incoming.  Using the version from git.
484 END
485
486 sub badusage {
487     print STDERR "$us: @_\n", $helpmsg or die $!;
488     exit 8;
489 }
490
491 sub nextarg {
492     @ARGV or badusage "too few arguments";
493     return scalar shift @ARGV;
494 }
495
496 sub cmd_help () {
497     print $helpmsg or die $!;
498     exit 0;
499 }
500
501 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
502
503 our %defcfg = ('dgit.default.distro' => 'debian',
504                'dgit.default.username' => '',
505                'dgit.default.archive-query-default-component' => 'main',
506                'dgit.default.ssh' => 'ssh',
507                'dgit.default.archive-query' => 'madison:',
508                'dgit.default.sshpsql-dbname' => 'service=projectb',
509                'dgit.default.dgit-tag-format' => 'old,new',
510                'dgit-distro.debian.archive-query' => 'ftpmasterapi:',
511                'dgit-distro.debian.git-check' => 'url',
512                'dgit-distro.debian.git-check-suffix' => '/info/refs',
513                'dgit-distro.debian.new-private-pushers' => 't',
514                'dgit-distro.debian.dgit-tag-format' => 'old',
515                'dgit-distro.debian/push.git-url' => '',
516                'dgit-distro.debian/push.git-host' => 'push.dgit.debian.org',
517                'dgit-distro.debian/push.git-user-force' => 'dgit',
518                'dgit-distro.debian/push.git-proto' => 'git+ssh://',
519                'dgit-distro.debian/push.git-path' => '/dgit/debian/repos',
520                'dgit-distro.debian/push.git-create' => 'true',
521                'dgit-distro.debian/push.git-check' => 'ssh-cmd',
522  'dgit-distro.debian.archive-query-url', 'https://api.ftp-master.debian.org/',
523 # 'dgit-distro.debian.archive-query-tls-key',
524 #    '/etc/ssl/certs/%HOST%.pem:/etc/dgit/%HOST%.pem',
525 # ^ this does not work because curl is broken nowadays
526 # Fixing #790093 properly will involve providing providing the key
527 # in some pacagke and maybe updating these paths.
528 #
529 # 'dgit-distro.debian.archive-query-tls-curl-args',
530 #   '--ca-path=/etc/ssl/ca-debian',
531 # ^ this is a workaround but works (only) on DSA-administered machines
532                'dgit-distro.debian.git-url' => 'https://git.dgit.debian.org',
533                'dgit-distro.debian.git-url-suffix' => '',
534                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
535                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
536  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
537  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
538                'dgit-distro.ubuntu.git-check' => 'false',
539  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
540                'dgit-distro.test-dummy.ssh' => "$td/ssh",
541                'dgit-distro.test-dummy.username' => "alice",
542                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
543                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
544                'dgit-distro.test-dummy.git-url' => "$td/git",
545                'dgit-distro.test-dummy.git-host' => "git",
546                'dgit-distro.test-dummy.git-path' => "$td/git",
547                'dgit-distro.test-dummy.archive-query' => "ftpmasterapi:",
548                'dgit-distro.test-dummy.archive-query-url' => "file://$td/aq/",
549                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
550                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
551                );
552
553 our %gitcfg;
554
555 sub git_slurp_config () {
556     local ($debuglevel) = $debuglevel-2;
557     local $/="\0";
558
559     my @cmd = (@git, qw(config -z --get-regexp .*));
560     debugcmd "|",@cmd;
561
562     open GITS, "-|", @cmd or die $!;
563     while (<GITS>) {
564         chomp or die;
565         printdebug "=> ", (messagequote $_), "\n";
566         m/\n/ or die "$_ ?";
567         push @{ $gitcfg{$`} }, $'; #';
568     }
569     $!=0; $?=0;
570     close GITS
571         or ($!==0 && $?==256)
572         or failedcmd @cmd;
573 }
574
575 sub git_get_config ($) {
576     my ($c) = @_;
577     my $l = $gitcfg{$c};
578     printdebug"C $c ".(defined $l ? messagequote "'$l'" : "undef")."\n"
579         if $debuglevel >= 4;
580     $l or return undef;
581     @$l==1 or badcfg "multiple values for $c" if @$l > 1;
582     return $l->[0];
583 }
584
585 sub cfg {
586     foreach my $c (@_) {
587         return undef if $c =~ /RETURN-UNDEF/;
588         my $v = git_get_config($c);
589         return $v if defined $v;
590         my $dv = $defcfg{$c};
591         return $dv if defined $dv;
592     }
593     badcfg "need value for one of: @_\n".
594         "$us: distro or suite appears not to be (properly) supported";
595 }
596
597 sub access_basedistro () {
598     if (defined $idistro) {
599         return $idistro;
600     } else {    
601         return cfg("dgit-suite.$isuite.distro",
602                    "dgit.default.distro");
603     }
604 }
605
606 sub access_quirk () {
607     # returns (quirk name, distro to use instead or undef, quirk-specific info)
608     my $basedistro = access_basedistro();
609     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
610                               'RETURN-UNDEF');
611     if (defined $backports_quirk) {
612         my $re = $backports_quirk;
613         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
614         $re =~ s/\*/.*/g;
615         $re =~ s/\%/([-0-9a-z_]+)/
616             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
617         if ($isuite =~ m/^$re$/) {
618             return ('backports',"$basedistro-backports",$1);
619         }
620     }
621     return ('none',undef);
622 }
623
624 our $access_forpush;
625
626 sub parse_cfg_bool ($$$) {
627     my ($what,$def,$v) = @_;
628     $v //= $def;
629     return
630         $v =~ m/^[ty1]/ ? 1 :
631         $v =~ m/^[fn0]/ ? 0 :
632         badcfg "$what needs t (true, y, 1) or f (false, n, 0) not \`$v'";
633 }       
634
635 sub access_forpush_config () {
636     my $d = access_basedistro();
637
638     return 1 if
639         $new_package &&
640         parse_cfg_bool('new-private-pushers', 0,
641                        cfg("dgit-distro.$d.new-private-pushers",
642                            'RETURN-UNDEF'));
643
644     my $v = cfg("dgit-distro.$d.readonly", 'RETURN-UNDEF');
645     $v //= 'a';
646     return
647         $v =~ m/^[ty1]/ ? 0 : # force readonly,    forpush = 0
648         $v =~ m/^[fn0]/ ? 1 : # force nonreadonly, forpush = 1
649         $v =~ m/^[a]/  ? '' : # auto,              forpush = ''
650         badcfg "readonly needs t (true, y, 1) or f (false, n, 0) or a (auto)";
651 }
652
653 sub access_forpush () {
654     $access_forpush //= access_forpush_config();
655     return $access_forpush;
656 }
657
658 sub pushing () {
659     die "$access_forpush ?" if ($access_forpush // 1) ne 1;
660     badcfg "pushing but distro is configured readonly"
661         if access_forpush_config() eq '0';
662     $access_forpush = 1;
663     $supplementary_message = <<'END' unless $we_are_responder;
664 Push failed, before we got started.
665 You can retry the push, after fixing the problem, if you like.
666 END
667     finalise_opts_opts();
668 }
669
670 sub notpushing () {
671     finalise_opts_opts();
672 }
673
674 sub supplementary_message ($) {
675     my ($msg) = @_;
676     if (!$we_are_responder) {
677         $supplementary_message = $msg;
678         return;
679     } elsif ($protovsn >= 3) {
680         responder_send_command "supplementary-message ".length($msg)
681             or die $!;
682         print PO $msg or die $!;
683     }
684 }
685
686 sub access_distros () {
687     # Returns list of distros to try, in order
688     #
689     # We want to try:
690     #    0. `instead of' distro name(s) we have been pointed to
691     #    1. the access_quirk distro, if any
692     #    2a. the user's specified distro, or failing that  } basedistro
693     #    2b. the distro calculated from the suite          }
694     my @l = access_basedistro();
695
696     my (undef,$quirkdistro) = access_quirk();
697     unshift @l, $quirkdistro;
698     unshift @l, $instead_distro;
699     @l = grep { defined } @l;
700
701     if (access_forpush()) {
702         @l = map { ("$_/push", $_) } @l;
703     }
704     @l;
705 }
706
707 sub access_cfg_cfgs (@) {
708     my (@keys) = @_;
709     my @cfgs;
710     # The nesting of these loops determines the search order.  We put
711     # the key loop on the outside so that we search all the distros
712     # for each key, before going on to the next key.  That means that
713     # if access_cfg is called with a more specific, and then a less
714     # specific, key, an earlier distro can override the less specific
715     # without necessarily overriding any more specific keys.  (If the
716     # distro wants to override the more specific keys it can simply do
717     # so; whereas if we did the loop the other way around, it would be
718     # impossible to for an earlier distro to override a less specific
719     # key but not the more specific ones without restating the unknown
720     # values of the more specific keys.
721     my @realkeys;
722     my @rundef;
723     # We have to deal with RETURN-UNDEF specially, so that we don't
724     # terminate the search prematurely.
725     foreach (@keys) {
726         if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
727         push @realkeys, $_
728     }
729     foreach my $d (access_distros()) {
730         push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
731     }
732     push @cfgs, map { "dgit.default.$_" } @realkeys;
733     push @cfgs, @rundef;
734     return @cfgs;
735 }
736
737 sub access_cfg (@) {
738     my (@keys) = @_;
739     my (@cfgs) = access_cfg_cfgs(@keys);
740     my $value = cfg(@cfgs);
741     return $value;
742 }
743
744 sub access_cfg_bool ($$) {
745     my ($def, @keys) = @_;
746     parse_cfg_bool($keys[0], $def, access_cfg(@keys, 'RETURN-UNDEF'));
747 }
748
749 sub string_to_ssh ($) {
750     my ($spec) = @_;
751     if ($spec =~ m/\s/) {
752         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
753     } else {
754         return ($spec);
755     }
756 }
757
758 sub access_cfg_ssh () {
759     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
760     if (!defined $gitssh) {
761         return @ssh;
762     } else {
763         return string_to_ssh $gitssh;
764     }
765 }
766
767 sub access_runeinfo ($) {
768     my ($info) = @_;
769     return ": dgit ".access_basedistro()." $info ;";
770 }
771
772 sub access_someuserhost ($) {
773     my ($some) = @_;
774     my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
775     defined($user) && length($user) or
776         $user = access_cfg("$some-user",'username');
777     my $host = access_cfg("$some-host");
778     return length($user) ? "$user\@$host" : $host;
779 }
780
781 sub access_gituserhost () {
782     return access_someuserhost('git');
783 }
784
785 sub access_giturl (;$) {
786     my ($optional) = @_;
787     my $url = access_cfg('git-url','RETURN-UNDEF');
788     my $suffix;
789     if (!length $url) {
790         my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
791         return undef unless defined $proto;
792         $url =
793             $proto.
794             access_gituserhost().
795             access_cfg('git-path');
796     } else {
797         $suffix = access_cfg('git-url-suffix','RETURN-UNDEF');
798     }
799     $suffix //= '.git';
800     return "$url/$package$suffix";
801 }              
802
803 sub parsecontrolfh ($$;$) {
804     my ($fh, $desc, $allowsigned) = @_;
805     our $dpkgcontrolhash_noissigned;
806     my $c;
807     for (;;) {
808         my %opts = ('name' => $desc);
809         $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
810         $c = Dpkg::Control::Hash->new(%opts);
811         $c->parse($fh,$desc) or die "parsing of $desc failed";
812         last if $allowsigned;
813         last if $dpkgcontrolhash_noissigned;
814         my $issigned= $c->get_option('is_pgp_signed');
815         if (!defined $issigned) {
816             $dpkgcontrolhash_noissigned= 1;
817             seek $fh, 0,0 or die "seek $desc: $!";
818         } elsif ($issigned) {
819             fail "control file $desc is (already) PGP-signed. ".
820                 " Note that dgit push needs to modify the .dsc and then".
821                 " do the signature itself";
822         } else {
823             last;
824         }
825     }
826     return $c;
827 }
828
829 sub parsecontrol {
830     my ($file, $desc) = @_;
831     my $fh = new IO::Handle;
832     open $fh, '<', $file or die "$file: $!";
833     my $c = parsecontrolfh($fh,$desc);
834     $fh->error and die $!;
835     close $fh;
836     return $c;
837 }
838
839 sub getfield ($$) {
840     my ($dctrl,$field) = @_;
841     my $v = $dctrl->{$field};
842     return $v if defined $v;
843     fail "missing field $field in ".$v->get_option('name');
844 }
845
846 sub parsechangelog {
847     my $c = Dpkg::Control::Hash->new();
848     my $p = new IO::Handle;
849     my @cmd = (qw(dpkg-parsechangelog), @_);
850     open $p, '-|', @cmd or die $!;
851     $c->parse($p);
852     $?=0; $!=0; close $p or failedcmd @cmd;
853     return $c;
854 }
855
856 sub must_getcwd () {
857     my $d = getcwd();
858     defined $d or fail "getcwd failed: $!";
859     return $d;
860 }
861
862 our %rmad;
863
864 sub archive_query ($) {
865     my ($method) = @_;
866     my $query = access_cfg('archive-query','RETURN-UNDEF');
867     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
868     my $proto = $1;
869     my $data = $'; #';
870     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
871 }
872
873 sub pool_dsc_subpath ($$) {
874     my ($vsn,$component) = @_; # $package is implict arg
875     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
876     return "/pool/$component/$prefix/$package/".dscfn($vsn);
877 }
878
879 #---------- `ftpmasterapi' archive query method (nascent) ----------
880
881 sub archive_api_query_cmd ($) {
882     my ($subpath) = @_;
883     my @cmd = qw(curl -sS);
884     my $url = access_cfg('archive-query-url');
885     if ($url =~ m#^https://([-.0-9a-z]+)/#) {
886         my $host = $1;
887         my $keys = access_cfg('archive-query-tls-key','RETURN-UNDEF') //'';
888         foreach my $key (split /\:/, $keys) {
889             $key =~ s/\%HOST\%/$host/g;
890             if (!stat $key) {
891                 fail "for $url: stat $key: $!" unless $!==ENOENT;
892                 next;
893             }
894             fail "config requested specific TLS key but do not know".
895                 " how to get curl to use exactly that EE key ($key)";
896 #           push @cmd, "--cacert", $key, "--capath", "/dev/enoent";
897 #           # Sadly the above line does not work because of changes
898 #           # to gnutls.   The real fix for #790093 may involve
899 #           # new curl options.
900             last;
901         }
902         # Fixing #790093 properly will involve providing a value
903         # for this on clients.
904         my $kargs = access_cfg('archive-query-tls-curl-ca-args','RETURN-UNDEF');
905         push @cmd, split / /, $kargs if defined $kargs;
906     }
907     push @cmd, $url.$subpath;
908     return @cmd;
909 }
910
911 sub api_query ($$) {
912     use JSON;
913     my ($data, $subpath) = @_;
914     badcfg "ftpmasterapi archive query method takes no data part"
915         if length $data;
916     my @cmd = archive_api_query_cmd($subpath);
917     my $json = cmdoutput @cmd;
918     return decode_json($json);
919 }
920
921 sub canonicalise_suite_ftpmasterapi () {
922     my ($proto,$data) = @_;
923     my $suites = api_query($data, 'suites');
924     my @matched;
925     foreach my $entry (@$suites) {
926         next unless grep { 
927             my $v = $entry->{$_};
928             defined $v && $v eq $isuite;
929         } qw(codename name);
930         push @matched, $entry;
931     }
932     fail "unknown suite $isuite" unless @matched;
933     my $cn;
934     eval {
935         @matched==1 or die "multiple matches for suite $isuite\n";
936         $cn = "$matched[0]{codename}";
937         defined $cn or die "suite $isuite info has no codename\n";
938         $cn =~ m/^$suite_re$/ or die "suite $isuite maps to bad codename\n";
939     };
940     die "bad ftpmaster api response: $@\n".Dumper(\@matched)
941         if length $@;
942     return $cn;
943 }
944
945 sub archive_query_ftpmasterapi () {
946     my ($proto,$data) = @_;
947     my $info = api_query($data, "dsc_in_suite/$isuite/$package");
948     my @rows;
949     my $digester = Digest::SHA->new(256);
950     foreach my $entry (@$info) {
951         eval {
952             my $vsn = "$entry->{version}";
953             my ($ok,$msg) = version_check $vsn;
954             die "bad version: $msg\n" unless $ok;
955             my $component = "$entry->{component}";
956             $component =~ m/^$component_re$/ or die "bad component";
957             my $filename = "$entry->{filename}";
958             $filename && $filename !~ m#[^-+:._~0-9a-zA-Z/]|^[/.]|/[/.]#
959                 or die "bad filename";
960             my $sha256sum = "$entry->{sha256sum}";
961             $sha256sum =~ m/^[0-9a-f]+$/ or die "bad sha256sum";
962             push @rows, [ $vsn, "/pool/$component/$filename",
963                           $digester, $sha256sum ];
964         };
965         die "bad ftpmaster api response: $@\n".Dumper($entry)
966             if length $@;
967     }
968     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
969     return @rows;
970 }
971
972 #---------- `madison' archive query method ----------
973
974 sub archive_query_madison {
975     return map { [ @$_[0..1] ] } madison_get_parse(@_);
976 }
977
978 sub madison_get_parse {
979     my ($proto,$data) = @_;
980     die unless $proto eq 'madison';
981     if (!length $data) {
982         $data= access_cfg('madison-distro','RETURN-UNDEF');
983         $data //= access_basedistro();
984     }
985     $rmad{$proto,$data,$package} ||= cmdoutput
986         qw(rmadison -asource),"-s$isuite","-u$data",$package;
987     my $rmad = $rmad{$proto,$data,$package};
988
989     my @out;
990     foreach my $l (split /\n/, $rmad) {
991         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
992                   \s*( [^ \t|]+ )\s* \|
993                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
994                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
995         $1 eq $package or die "$rmad $package ?";
996         my $vsn = $2;
997         my $newsuite = $3;
998         my $component;
999         if (defined $4) {
1000             $component = $4;
1001         } else {
1002             $component = access_cfg('archive-query-default-component');
1003         }
1004         $5 eq 'source' or die "$rmad ?";
1005         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
1006     }
1007     return sort { -version_compare($a->[0],$b->[0]); } @out;
1008 }
1009
1010 sub canonicalise_suite_madison {
1011     # madison canonicalises for us
1012     my @r = madison_get_parse(@_);
1013     @r or fail
1014         "unable to canonicalise suite using package $package".
1015         " which does not appear to exist in suite $isuite;".
1016         " --existing-package may help";
1017     return $r[0][2];
1018 }
1019
1020 #---------- `sshpsql' archive query method ----------
1021
1022 sub sshpsql ($$$) {
1023     my ($data,$runeinfo,$sql) = @_;
1024     if (!length $data) {
1025         $data= access_someuserhost('sshpsql').':'.
1026             access_cfg('sshpsql-dbname');
1027     }
1028     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
1029     my ($userhost,$dbname) = ($`,$'); #';
1030     my @rows;
1031     my @cmd = (access_cfg_ssh, $userhost,
1032                access_runeinfo("ssh-psql $runeinfo").
1033                " export LC_MESSAGES=C; export LC_CTYPE=C;".
1034                " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
1035     debugcmd "|",@cmd;
1036     open P, "-|", @cmd or die $!;
1037     while (<P>) {
1038         chomp or die;
1039         printdebug(">|$_|\n");
1040         push @rows, $_;
1041     }
1042     $!=0; $?=0; close P or failedcmd @cmd;
1043     @rows or die;
1044     my $nrows = pop @rows;
1045     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
1046     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
1047     @rows = map { [ split /\|/, $_ ] } @rows;
1048     my $ncols = scalar @{ shift @rows };
1049     die if grep { scalar @$_ != $ncols } @rows;
1050     return @rows;
1051 }
1052
1053 sub sql_injection_check {
1054     foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
1055 }
1056
1057 sub archive_query_sshpsql ($$) {
1058     my ($proto,$data) = @_;
1059     sql_injection_check $isuite, $package;
1060     my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
1061         SELECT source.version, component.name, files.filename, files.sha256sum
1062           FROM source
1063           JOIN src_associations ON source.id = src_associations.source
1064           JOIN suite ON suite.id = src_associations.suite
1065           JOIN dsc_files ON dsc_files.source = source.id
1066           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
1067           JOIN component ON component.id = files_archive_map.component_id
1068           JOIN files ON files.id = dsc_files.file
1069          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
1070            AND source.source='$package'
1071            AND files.filename LIKE '%.dsc';
1072 END
1073     @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
1074     my $digester = Digest::SHA->new(256);
1075     @rows = map {
1076         my ($vsn,$component,$filename,$sha256sum) = @$_;
1077         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
1078     } @rows;
1079     return @rows;
1080 }
1081
1082 sub canonicalise_suite_sshpsql ($$) {
1083     my ($proto,$data) = @_;
1084     sql_injection_check $isuite;
1085     my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
1086         SELECT suite.codename
1087           FROM suite where suite_name='$isuite' or codename='$isuite';
1088 END
1089     @rows = map { $_->[0] } @rows;
1090     fail "unknown suite $isuite" unless @rows;
1091     die "ambiguous $isuite: @rows ?" if @rows>1;
1092     return $rows[0];
1093 }
1094
1095 #---------- `dummycat' archive query method ----------
1096
1097 sub canonicalise_suite_dummycat ($$) {
1098     my ($proto,$data) = @_;
1099     my $dpath = "$data/suite.$isuite";
1100     if (!open C, "<", $dpath) {
1101         $!==ENOENT or die "$dpath: $!";
1102         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
1103         return $isuite;
1104     }
1105     $!=0; $_ = <C>;
1106     chomp or die "$dpath: $!";
1107     close C;
1108     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
1109     return $_;
1110 }
1111
1112 sub archive_query_dummycat ($$) {
1113     my ($proto,$data) = @_;
1114     canonicalise_suite();
1115     my $dpath = "$data/package.$csuite.$package";
1116     if (!open C, "<", $dpath) {
1117         $!==ENOENT or die "$dpath: $!";
1118         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
1119         return ();
1120     }
1121     my @rows;
1122     while (<C>) {
1123         next if m/^\#/;
1124         next unless m/\S/;
1125         die unless chomp;
1126         printdebug "dummycat query $csuite $package $dpath | $_\n";
1127         my @row = split /\s+/, $_;
1128         @row==2 or die "$dpath: $_ ?";
1129         push @rows, \@row;
1130     }
1131     C->error and die "$dpath: $!";
1132     close C;
1133     return sort { -version_compare($a->[0],$b->[0]); } @rows;
1134 }
1135
1136 #---------- tag format handling ----------
1137
1138 sub access_cfg_tagformats () {
1139     split /\,/, access_cfg('dgit-tag-format');
1140 }
1141
1142 sub need_tagformat ($$) {
1143     my ($fmt, $why) = @_;
1144     fail "need to use tag format $fmt ($why) but also need".
1145         " to use tag format $tagformat_want->[0] ($tagformat_want->[1])".
1146         " - no way to proceed"
1147         if $tagformat_want && $tagformat_want->[0] ne $fmt;
1148     $tagformat_want = [$fmt, $why, $tagformat_want->[2] // 0];
1149 }
1150
1151 sub select_tagformat () {
1152     # sets $tagformatfn
1153     return if $tagformatfn && !$tagformat_want;
1154     die 'bug' if $tagformatfn && $tagformat_want;
1155     # ... $tagformat_want assigned after previous select_tagformat
1156
1157     my (@supported) = access_cfg_tagformats();
1158     printdebug "select_tagformat supported @supported\n";
1159
1160     $tagformat_want //= [ $supported[0], "distro access configuration", 0 ];
1161     printdebug "select_tagformat specified @$tagformat_want\n";
1162
1163     my ($fmt,$why,$override) = @$tagformat_want;
1164
1165     fail "target distro supports tag formats @supported".
1166         " but have to use $fmt ($why)"
1167         unless $override
1168             or grep { $_ eq $fmt } @supported;
1169
1170     $tagformat_want = undef;
1171     $tagformat = $fmt;
1172     $tagformatfn = ${*::}{"debiantag_$fmt"};
1173
1174     fail "trying to use unknown tag format \`$fmt' ($why) !"
1175         unless $tagformatfn;
1176 }
1177
1178 #---------- archive query entrypoints and rest of program ----------
1179
1180 sub canonicalise_suite () {
1181     return if defined $csuite;
1182     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
1183     $csuite = archive_query('canonicalise_suite');
1184     if ($isuite ne $csuite) {
1185         progress "canonical suite name for $isuite is $csuite";
1186     }
1187 }
1188
1189 sub get_archive_dsc () {
1190     canonicalise_suite();
1191     my @vsns = archive_query('archive_query');
1192     foreach my $vinfo (@vsns) {
1193         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
1194         $dscurl = access_cfg('mirror').$subpath;
1195         $dscdata = url_get($dscurl);
1196         if (!$dscdata) {
1197             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
1198             next;
1199         }
1200         if ($digester) {
1201             $digester->reset();
1202             $digester->add($dscdata);
1203             my $got = $digester->hexdigest();
1204             $got eq $digest or
1205                 fail "$dscurl has hash $got but".
1206                     " archive told us to expect $digest";
1207         }
1208         my $dscfh = new IO::File \$dscdata, '<' or die $!;
1209         printdebug Dumper($dscdata) if $debuglevel>1;
1210         $dsc = parsecontrolfh($dscfh,$dscurl,1);
1211         printdebug Dumper($dsc) if $debuglevel>1;
1212         my $fmt = getfield $dsc, 'Format';
1213         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
1214         $dsc_checked = !!$digester;
1215         return;
1216     }
1217     $dsc = undef;
1218 }
1219
1220 sub check_for_git ();
1221 sub check_for_git () {
1222     # returns 0 or 1
1223     my $how = access_cfg('git-check');
1224     if ($how eq 'ssh-cmd') {
1225         my @cmd =
1226             (access_cfg_ssh, access_gituserhost(),
1227              access_runeinfo("git-check $package").
1228              " set -e; cd ".access_cfg('git-path').";".
1229              " if test -d $package.git; then echo 1; else echo 0; fi");
1230         my $r= cmdoutput @cmd;
1231         if (defined $r and $r =~ m/^divert (\w+)$/) {
1232             my $divert=$1;
1233             my ($usedistro,) = access_distros();
1234             # NB that if we are pushing, $usedistro will be $distro/push
1235             $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1236             $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1237             progress "diverting to $divert (using config for $instead_distro)";
1238             return check_for_git();
1239         }
1240         failedcmd @cmd unless defined $r and $r =~ m/^[01]$/;
1241         return $r+0;
1242     } elsif ($how eq 'url') {
1243         my $prefix = access_cfg('git-check-url','git-url');
1244         my $suffix = access_cfg('git-check-suffix','git-suffix',
1245                                 'RETURN-UNDEF') // '.git';
1246         my $url = "$prefix/$package$suffix";
1247         my @cmd = (qw(curl -sS -I), $url);
1248         my $result = cmdoutput @cmd;
1249         $result =~ s/^\S+ 200 .*\n\r?\n//;
1250         # curl -sS -I with https_proxy prints
1251         # HTTP/1.0 200 Connection established
1252         $result =~ m/^\S+ (404|200) /s or
1253             fail "unexpected results from git check query - ".
1254                 Dumper($prefix, $result);
1255         my $code = $1;
1256         if ($code eq '404') {
1257             return 0;
1258         } elsif ($code eq '200') {
1259             return 1;
1260         } else {
1261             die;
1262         }
1263     } elsif ($how eq 'true') {
1264         return 1;
1265     } elsif ($how eq 'false') {
1266         return 0;
1267     } else {
1268         badcfg "unknown git-check \`$how'";
1269     }
1270 }
1271
1272 sub create_remote_git_repo () {
1273     my $how = access_cfg('git-create');
1274     if ($how eq 'ssh-cmd') {
1275         runcmd_ordryrun
1276             (access_cfg_ssh, access_gituserhost(),
1277              access_runeinfo("git-create $package").
1278              "set -e; cd ".access_cfg('git-path').";".
1279              " cp -a _template $package.git");
1280     } elsif ($how eq 'true') {
1281         # nothing to do
1282     } else {
1283         badcfg "unknown git-create \`$how'";
1284     }
1285 }
1286
1287 our ($dsc_hash,$lastpush_hash);
1288
1289 our $ud = '.git/dgit/unpack';
1290
1291 sub prep_ud (;$) {
1292     my ($d) = @_;
1293     $d //= $ud;
1294     rmtree($d);
1295     mkpath '.git/dgit';
1296     mkdir $d or die $!;
1297 }
1298
1299 sub mktree_in_ud_here () {
1300     runcmd qw(git init -q);
1301     rmtree('.git/objects');
1302     symlink '../../../../objects','.git/objects' or die $!;
1303 }
1304
1305 sub git_write_tree () {
1306     my $tree = cmdoutput @git, qw(write-tree);
1307     $tree =~ m/^\w+$/ or die "$tree ?";
1308     return $tree;
1309 }
1310
1311 sub remove_stray_gits () {
1312     my @gitscmd = qw(find -name .git -prune -print0);
1313     debugcmd "|",@gitscmd;
1314     open GITS, "-|", @gitscmd or die $!;
1315     {
1316         local $/="\0";
1317         while (<GITS>) {
1318             chomp or die;
1319             print STDERR "$us: warning: removing from source package: ",
1320                 (messagequote $_), "\n";
1321             rmtree $_;
1322         }
1323     }
1324     $!=0; $?=0; close GITS or failedcmd @gitscmd;
1325 }
1326
1327 sub mktree_in_ud_from_only_subdir () {
1328     # changes into the subdir
1329     my (@dirs) = <*/.>;
1330     die "@dirs ?" unless @dirs==1;
1331     $dirs[0] =~ m#^([^/]+)/\.$# or die;
1332     my $dir = $1;
1333     changedir $dir;
1334
1335     remove_stray_gits();
1336     mktree_in_ud_here();
1337     my ($format, $fopts) = get_source_format();
1338     if (madformat($format)) {
1339         rmtree '.pc';
1340     }
1341     runcmd @git, qw(add -Af);
1342     my $tree=git_write_tree();
1343     return ($tree,$dir);
1344 }
1345
1346 sub dsc_files_info () {
1347     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1348                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
1349                        ['Files',           'Digest::MD5', 'new()']) {
1350         my ($fname, $module, $method) = @$csumi;
1351         my $field = $dsc->{$fname};
1352         next unless defined $field;
1353         eval "use $module; 1;" or die $@;
1354         my @out;
1355         foreach (split /\n/, $field) {
1356             next unless m/\S/;
1357             m/^(\w+) (\d+) (\S+)$/ or
1358                 fail "could not parse .dsc $fname line \`$_'";
1359             my $digester = eval "$module"."->$method;" or die $@;
1360             push @out, {
1361                 Hash => $1,
1362                 Bytes => $2,
1363                 Filename => $3,
1364                 Digester => $digester,
1365             };
1366         }
1367         return @out;
1368     }
1369     fail "missing any supported Checksums-* or Files field in ".
1370         $dsc->get_option('name');
1371 }
1372
1373 sub dsc_files () {
1374     map { $_->{Filename} } dsc_files_info();
1375 }
1376
1377 sub is_orig_file ($;$) {
1378     local ($_) = $_[0];
1379     my $base = $_[1];
1380     m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1381     defined $base or return 1;
1382     return $` eq $base;
1383 }
1384
1385 sub make_commit ($) {
1386     my ($file) = @_;
1387     return cmdoutput @git, qw(hash-object -w -t commit), $file;
1388 }
1389
1390 sub clogp_authline ($) {
1391     my ($clogp) = @_;
1392     my $author = getfield $clogp, 'Maintainer';
1393     $author =~ s#,.*##ms;
1394     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1395     my $authline = "$author $date";
1396     $authline =~ m/$git_authline_re/o or
1397         fail "unexpected commit author line format \`$authline'".
1398         " (was generated from changelog Maintainer field)";
1399     return ($1,$2,$3) if wantarray;
1400     return $authline;
1401 }
1402
1403 sub vendor_patches_distro ($$) {
1404     my ($checkdistro, $what) = @_;
1405     return unless defined $checkdistro;
1406
1407     my $series = "debian/patches/\L$checkdistro\E.series";
1408     printdebug "checking for vendor-specific $series ($what)\n";
1409
1410     if (!open SERIES, "<", $series) {
1411         die "$series $!" unless $!==ENOENT;
1412         return;
1413     }
1414     while (<SERIES>) {
1415         next unless m/\S/;
1416         next if m/^\s+\#/;
1417
1418         print STDERR <<END;
1419
1420 Unfortunately, this source package uses a feature of dpkg-source where
1421 the same source package unpacks to different source code on different
1422 distros.  dgit cannot safely operate on such packages on affected
1423 distros, because the meaning of source packages is not stable.
1424
1425 Please ask the distro/maintainer to remove the distro-specific series
1426 files and use a different technique (if necessary, uploading actually
1427 different packages, if different distros are supposed to have
1428 different code).
1429
1430 END
1431         fail "Found active distro-specific series file for".
1432             " $checkdistro ($what): $series, cannot continue";
1433     }
1434     die "$series $!" if SERIES->error;
1435     close SERIES;
1436 }
1437
1438 sub check_for_vendor_patches () {
1439     # This dpkg-source feature doesn't seem to be documented anywhere!
1440     # But it can be found in the changelog (reformatted):
1441
1442     #   commit  4fa01b70df1dc4458daee306cfa1f987b69da58c
1443     #   Author: Raphael Hertzog <hertzog@debian.org>
1444     #   Date: Sun  Oct  3  09:36:48  2010 +0200
1445
1446     #   dpkg-source: correctly create .pc/.quilt_series with alternate
1447     #   series files
1448     #   
1449     #   If you have debian/patches/ubuntu.series and you were
1450     #   unpacking the source package on ubuntu, quilt was still
1451     #   directed to debian/patches/series instead of
1452     #   debian/patches/ubuntu.series.
1453     #   
1454     #   debian/changelog                        |    3 +++
1455     #   scripts/Dpkg/Source/Package/V3/quilt.pm |    4 +++-
1456     #   2 files changed, 6 insertions(+), 1 deletion(-)
1457
1458     use Dpkg::Vendor;
1459     vendor_patches_distro($ENV{DEB_VENDOR}, "DEB_VENDOR");
1460     vendor_patches_distro(Dpkg::Vendor::get_current_vendor(),
1461                          "Dpkg::Vendor \`current vendor'");
1462     vendor_patches_distro(access_basedistro(),
1463                           "distro being accessed");
1464 }
1465
1466 sub generate_commit_from_dsc () {
1467     prep_ud();
1468     changedir $ud;
1469
1470     foreach my $fi (dsc_files_info()) {
1471         my $f = $fi->{Filename};
1472         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1473
1474         link_ltarget "../../../$f", $f
1475             or $!==&ENOENT
1476             or die "$f $!";
1477
1478         complete_file_from_dsc('.', $fi)
1479             or next;
1480
1481         if (is_orig_file($f)) {
1482             link $f, "../../../../$f"
1483                 or $!==&EEXIST
1484                 or die "$f $!";
1485         }
1486     }
1487
1488     my $dscfn = "$package.dsc";
1489
1490     open D, ">", $dscfn or die "$dscfn: $!";
1491     print D $dscdata or die "$dscfn: $!";
1492     close D or die "$dscfn: $!";
1493     my @cmd = qw(dpkg-source);
1494     push @cmd, '--no-check' if $dsc_checked;
1495     push @cmd, qw(-x --), $dscfn;
1496     runcmd @cmd;
1497
1498     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1499     check_for_vendor_patches() if madformat($dsc->{format});
1500     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1501     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1502     my $authline = clogp_authline $clogp;
1503     my $changes = getfield $clogp, 'Changes';
1504     open C, ">../commit.tmp" or die $!;
1505     print C <<END or die $!;
1506 tree $tree
1507 author $authline
1508 committer $authline
1509
1510 $changes
1511
1512 # imported from the archive
1513 END
1514     close C or die $!;
1515     my $outputhash = make_commit qw(../commit.tmp);
1516     my $cversion = getfield $clogp, 'Version';
1517     progress "synthesised git commit from .dsc $cversion";
1518     if ($lastpush_hash) {
1519         runcmd @git, qw(reset -q --hard), $lastpush_hash;
1520         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1521         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1522         my $oversion = getfield $oldclogp, 'Version';
1523         my $vcmp =
1524             version_compare($oversion, $cversion);
1525         if ($vcmp < 0) {
1526             # git upload/ is earlier vsn than archive, use archive
1527             open C, ">../commit2.tmp" or die $!;
1528             print C <<END or die $!;
1529 tree $tree
1530 parent $lastpush_hash
1531 parent $outputhash
1532 author $authline
1533 committer $authline
1534
1535 Record $package ($cversion) in archive suite $csuite
1536 END
1537             $outputhash = make_commit qw(../commit2.tmp);
1538         } elsif ($vcmp > 0) {
1539             print STDERR <<END or die $!;
1540
1541 Version actually in archive:    $cversion (older)
1542 Last allegedly pushed/uploaded: $oversion (newer or same)
1543 $later_warning_msg
1544 END
1545             $outputhash = $lastpush_hash;
1546         } else {
1547             $outputhash = $lastpush_hash;
1548         }
1549     }
1550     changedir '../../../..';
1551     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1552             'DGIT_ARCHIVE', $outputhash;
1553     cmdoutput @git, qw(log -n2), $outputhash;
1554     # ... gives git a chance to complain if our commit is malformed
1555     rmtree($ud);
1556     return $outputhash;
1557 }
1558
1559 sub complete_file_from_dsc ($$) {
1560     our ($dstdir, $fi) = @_;
1561     # Ensures that we have, in $dir, the file $fi, with the correct
1562     # contents.  (Downloading it from alongside $dscurl if necessary.)
1563
1564     my $f = $fi->{Filename};
1565     my $tf = "$dstdir/$f";
1566     my $downloaded = 0;
1567
1568     if (stat_exists $tf) {
1569         progress "using existing $f";
1570     } else {
1571         my $furl = $dscurl;
1572         $furl =~ s{/[^/]+$}{};
1573         $furl .= "/$f";
1574         die "$f ?" unless $f =~ m/^\Q${package}\E_/;
1575         die "$f ?" if $f =~ m#/#;
1576         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1577         return 0 if !act_local();
1578         $downloaded = 1;
1579     }
1580
1581     open F, "<", "$tf" or die "$tf: $!";
1582     $fi->{Digester}->reset();
1583     $fi->{Digester}->addfile(*F);
1584     F->error and die $!;
1585     my $got = $fi->{Digester}->hexdigest();
1586     $got eq $fi->{Hash} or
1587         fail "file $f has hash $got but .dsc".
1588             " demands hash $fi->{Hash} ".
1589             ($downloaded ? "(got wrong file from archive!)"
1590              : "(perhaps you should delete this file?)");
1591
1592     return 1;
1593 }
1594
1595 sub ensure_we_have_orig () {
1596     foreach my $fi (dsc_files_info()) {
1597         my $f = $fi->{Filename};
1598         next unless is_orig_file($f);
1599         complete_file_from_dsc('..', $fi)
1600             or next;
1601     }
1602 }
1603
1604 sub git_fetch_us () {
1605     my @specs = (fetchspec());
1606     push @specs,
1607         map { "+refs/$_/*:".lrfetchrefs."/$_/*" }
1608         qw(tags heads);
1609     runcmd_ordryrun_local @git, qw(fetch -p -n -q), access_giturl(), @specs;
1610
1611     my %here;
1612     my @tagpats = debiantags('*',access_basedistro);
1613
1614     git_for_each_ref([map { "refs/tags/$_" } @tagpats], sub {
1615         my ($objid,$objtype,$fullrefname,$reftail) = @_;
1616         printdebug "currently $fullrefname=$objid\n";
1617         $here{$fullrefname} = $objid;
1618     });
1619     git_for_each_ref([map { lrfetchrefs."/tags/".$_ } @tagpats], sub {
1620         my ($objid,$objtype,$fullrefname,$reftail) = @_;
1621         my $lref = "refs".substr($fullrefname, length lrfetchrefs);
1622         printdebug "offered $lref=$objid\n";
1623         if (!defined $here{$lref}) {
1624             my @upd = (@git, qw(update-ref), $lref, $objid, '');
1625             runcmd_ordryrun_local @upd;
1626         } elsif ($here{$lref} eq $objid) {
1627         } else {
1628             print STDERR \
1629                 "Not updateting $lref from $here{$lref} to $objid.\n";
1630         }
1631     });
1632 }
1633
1634 sub fetch_from_archive () {
1635     # ensures that lrref() is what is actually in the archive,
1636     #  one way or another
1637     get_archive_dsc();
1638
1639     if ($dsc) {
1640         foreach my $field (@ourdscfield) {
1641             $dsc_hash = $dsc->{$field};
1642             last if defined $dsc_hash;
1643         }
1644         if (defined $dsc_hash) {
1645             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1646             $dsc_hash = $&;
1647             progress "last upload to archive specified git hash";
1648         } else {
1649             progress "last upload to archive has NO git hash";
1650         }
1651     } else {
1652         progress "no version available from the archive";
1653     }
1654
1655     $lastpush_hash = git_get_ref(lrref());
1656     printdebug "previous reference hash=$lastpush_hash\n";
1657     my $hash;
1658     if (defined $dsc_hash) {
1659         fail "missing remote git history even though dsc has hash -".
1660             " could not find ref ".lrref().
1661             " (should have been fetched from ".access_giturl()."#".rrref().")"
1662             unless $lastpush_hash;
1663         $hash = $dsc_hash;
1664         ensure_we_have_orig();
1665         if ($dsc_hash eq $lastpush_hash) {
1666         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1667             print STDERR <<END or die $!;
1668
1669 Git commit in archive is behind the last version allegedly pushed/uploaded.
1670 Commit referred to by archive:  $dsc_hash
1671 Last allegedly pushed/uploaded: $lastpush_hash
1672 $later_warning_msg
1673 END
1674             $hash = $lastpush_hash;
1675         } else {
1676             fail "git head (".lrref()."=$lastpush_hash) is not a ".
1677                 "descendant of archive's .dsc hash ($dsc_hash)";
1678         }
1679     } elsif ($dsc) {
1680         $hash = generate_commit_from_dsc();
1681     } elsif ($lastpush_hash) {
1682         # only in git, not in the archive yet
1683         $hash = $lastpush_hash;
1684         print STDERR <<END or die $!;
1685
1686 Package not found in the archive, but has allegedly been pushed using dgit.
1687 $later_warning_msg
1688 END
1689     } else {
1690         printdebug "nothing found!\n";
1691         if (defined $skew_warning_vsn) {
1692             print STDERR <<END or die $!;
1693
1694 Warning: relevant archive skew detected.
1695 Archive allegedly contains $skew_warning_vsn
1696 But we were not able to obtain any version from the archive or git.
1697
1698 END
1699         }
1700         return 0;
1701     }
1702     printdebug "current hash=$hash\n";
1703     if ($lastpush_hash) {
1704         fail "not fast forward on last upload branch!".
1705             " (archive's version left in DGIT_ARCHIVE)"
1706             unless is_fast_fwd($lastpush_hash, $hash);
1707     }
1708     if (defined $skew_warning_vsn) {
1709         mkpath '.git/dgit';
1710         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1711         my $clogf = ".git/dgit/changelog.tmp";
1712         runcmd shell_cmd "exec >$clogf",
1713             @git, qw(cat-file blob), "$hash:debian/changelog";
1714         my $gotclogp = parsechangelog("-l$clogf");
1715         my $got_vsn = getfield $gotclogp, 'Version';
1716         printdebug "SKEW CHECK GOT $got_vsn\n";
1717         if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1718             print STDERR <<END or die $!;
1719
1720 Warning: archive skew detected.  Using the available version:
1721 Archive allegedly contains    $skew_warning_vsn
1722 We were able to obtain only   $got_vsn
1723
1724 END
1725         }
1726     }
1727     if ($lastpush_hash ne $hash) {
1728         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1729         if (act_local()) {
1730             cmdoutput @upd_cmd;
1731         } else {
1732             dryrun_report @upd_cmd;
1733         }
1734     }
1735     return 1;
1736 }
1737
1738 sub set_local_git_config ($$) {
1739     my ($k, $v) = @_;
1740     runcmd @git, qw(config), $k, $v;
1741 }
1742
1743 sub setup_mergechangelogs (;$) {
1744     my ($always) = @_;
1745     return unless $always || access_cfg_bool(1, 'setup-mergechangelogs');
1746
1747     my $driver = 'dpkg-mergechangelogs';
1748     my $cb = "merge.$driver";
1749     my $attrs = '.git/info/attributes';
1750     ensuredir '.git/info';
1751
1752     open NATTRS, ">", "$attrs.new" or die "$attrs.new $!";
1753     if (!open ATTRS, "<", $attrs) {
1754         $!==ENOENT or die "$attrs: $!";
1755     } else {
1756         while (<ATTRS>) {
1757             chomp;
1758             next if m{^debian/changelog\s};
1759             print NATTRS $_, "\n" or die $!;
1760         }
1761         ATTRS->error and die $!;
1762         close ATTRS;
1763     }
1764     print NATTRS "debian/changelog merge=$driver\n" or die $!;
1765     close NATTRS;
1766
1767     set_local_git_config "$cb.name", 'debian/changelog merge driver';
1768     set_local_git_config "$cb.driver", 'dpkg-mergechangelogs -m %O %A %B %A';
1769
1770     rename "$attrs.new", "$attrs" or die "$attrs: $!";
1771 }
1772
1773 sub setup_useremail (;$) {
1774     my ($always) = @_;
1775     return unless $always || access_cfg_bool(1, 'setup-useremail');
1776
1777     my $setup = sub {
1778         my ($k, $envvar) = @_;
1779         my $v = access_cfg("user-$k", 'RETURN-UNDEF') // $ENV{$envvar};
1780         return unless defined $v;
1781         set_local_git_config "user.$k", $v;
1782     };
1783
1784     $setup->('email', 'DEBEMAIL');
1785     $setup->('name', 'DEBFULLNAME');
1786 }
1787
1788 sub setup_new_tree () {
1789     setup_mergechangelogs();
1790     setup_useremail();
1791 }
1792
1793 sub clone ($) {
1794     my ($dstdir) = @_;
1795     canonicalise_suite();
1796     badusage "dry run makes no sense with clone" unless act_local();
1797     my $hasgit = check_for_git();
1798     mkdir $dstdir or fail "create \`$dstdir': $!";
1799     changedir $dstdir;
1800     runcmd @git, qw(init -q);
1801     my $giturl = access_giturl(1);
1802     if (defined $giturl) {
1803         set_local_git_config "remote.$remotename.fetch", fetchspec();
1804         open H, "> .git/HEAD" or die $!;
1805         print H "ref: ".lref()."\n" or die $!;
1806         close H or die $!;
1807         runcmd @git, qw(remote add), 'origin', $giturl;
1808     }
1809     if ($hasgit) {
1810         progress "fetching existing git history";
1811         git_fetch_us();
1812         runcmd_ordryrun_local @git, qw(fetch origin);
1813     } else {
1814         progress "starting new git history";
1815     }
1816     fetch_from_archive() or no_such_package;
1817     my $vcsgiturl = $dsc->{'Vcs-Git'};
1818     if (length $vcsgiturl) {
1819         $vcsgiturl =~ s/\s+-b\s+\S+//g;
1820         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1821     }
1822     setup_new_tree();
1823     runcmd @git, qw(reset --hard), lrref();
1824     printdone "ready for work in $dstdir";
1825 }
1826
1827 sub fetch () {
1828     if (check_for_git()) {
1829         git_fetch_us();
1830     }
1831     fetch_from_archive() or no_such_package();
1832     printdone "fetched into ".lrref();
1833 }
1834
1835 sub pull () {
1836     fetch();
1837     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1838         lrref();
1839     printdone "fetched to ".lrref()." and merged into HEAD";
1840 }
1841
1842 sub check_not_dirty () {
1843     foreach my $f (qw(local-options local-patch-header)) {
1844         if (stat_exists "debian/source/$f") {
1845             fail "git tree contains debian/source/$f";
1846         }
1847     }
1848
1849     return if $ignoredirty;
1850
1851     my @cmd = (@git, qw(diff --quiet HEAD));
1852     debugcmd "+",@cmd;
1853     $!=0; $?=-1; system @cmd;
1854     return if !$?;
1855     if ($?==256) {
1856         fail "working tree is dirty (does not match HEAD)";
1857     } else {
1858         failedcmd @cmd;
1859     }
1860 }
1861
1862 sub commit_admin ($) {
1863     my ($m) = @_;
1864     progress "$m";
1865     runcmd_ordryrun_local @git, qw(commit -m), $m;
1866 }
1867
1868 sub commit_quilty_patch () {
1869     my $output = cmdoutput @git, qw(status --porcelain);
1870     my %adds;
1871     foreach my $l (split /\n/, $output) {
1872         next unless $l =~ m/\S/;
1873         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1874             $adds{$1}++;
1875         }
1876     }
1877     delete $adds{'.pc'}; # if there wasn't one before, don't add it
1878     if (!%adds) {
1879         progress "nothing quilty to commit, ok.";
1880         return;
1881     }
1882     my @adds = map { s/[][*?\\]/\\$&/g; $_; } sort keys %adds;
1883     runcmd_ordryrun_local @git, qw(add -f), @adds;
1884     commit_admin "Commit Debian 3.0 (quilt) metadata";
1885 }
1886
1887 sub get_source_format () {
1888     my %options;
1889     if (open F, "debian/source/options") {
1890         while (<F>) {
1891             next if m/^\s*\#/;
1892             next unless m/\S/;
1893             s/\s+$//; # ignore missing final newline
1894             if (m/\s*\#\s*/) {
1895                 my ($k, $v) = ($`, $'); #');
1896                 $v =~ s/^"(.*)"$/$1/;
1897                 $options{$k} = $v;
1898             } else {
1899                 $options{$_} = 1;
1900             }
1901         }
1902         F->error and die $!;
1903         close F;
1904     } else {
1905         die $! unless $!==&ENOENT;
1906     }
1907
1908     if (!open F, "debian/source/format") {
1909         die $! unless $!==&ENOENT;
1910         return '';
1911     }
1912     $_ = <F>;
1913     F->error and die $!;
1914     chomp;
1915     return ($_, \%options);
1916 }
1917
1918 sub madformat ($) {
1919     my ($format) = @_;
1920     return 0 unless $format eq '3.0 (quilt)';
1921     our $quilt_mode_warned;
1922     if ($quilt_mode eq 'nocheck') {
1923         progress "Not doing any fixup of \`$format' due to".
1924             " ----no-quilt-fixup or --quilt=nocheck"
1925             unless $quilt_mode_warned++;
1926         return 0;
1927     }
1928     progress "Format \`$format', need to check/update patch stack"
1929         unless $quilt_mode_warned++;
1930     return 1;
1931 }
1932
1933 sub push_parse_changelog ($) {
1934     my ($clogpfn) = @_;
1935
1936     my $clogp = Dpkg::Control::Hash->new();
1937     $clogp->load($clogpfn) or die;
1938
1939     $package = getfield $clogp, 'Source';
1940     my $cversion = getfield $clogp, 'Version';
1941     my $tag = debiantag($cversion, access_basedistro);
1942     runcmd @git, qw(check-ref-format), $tag;
1943
1944     my $dscfn = dscfn($cversion);
1945
1946     return ($clogp, $cversion, $dscfn);
1947 }
1948
1949 sub push_parse_dsc ($$$) {
1950     my ($dscfn,$dscfnwhat, $cversion) = @_;
1951     $dsc = parsecontrol($dscfn,$dscfnwhat);
1952     my $dversion = getfield $dsc, 'Version';
1953     my $dscpackage = getfield $dsc, 'Source';
1954     ($dscpackage eq $package && $dversion eq $cversion) or
1955         fail "$dscfn is for $dscpackage $dversion".
1956             " but debian/changelog is for $package $cversion";
1957 }
1958
1959 sub push_tagwants ($$$) {
1960     my ($cversion, $dgithead, $tfbase) = @_;
1961     my @tagwants;
1962     push @tagwants, {
1963         TagFn => \&debiantag,
1964         Objid => $dgithead,
1965         TfSuffix => '',
1966         View => 'dgit',
1967     };
1968     foreach my $tw (@tagwants) {
1969         $tw->{Tag} = $tw->{TagFn}($cversion, access_basedistro);
1970         $tw->{Tfn} = sub { $tfbase.$tw->{TfSuffix}.$_[0]; };
1971     }
1972     return @tagwants;
1973 }
1974
1975 sub push_mktags ($$ $$ $) {
1976     my ($clogp,$dscfn,
1977         $changesfile,$changesfilewhat,
1978         $tagwants) = @_;
1979
1980     die unless $tagwants->[0]{View} eq 'dgit';
1981
1982     $dsc->{$ourdscfield[0]} = $tagwants->[0]{Objid};
1983     $dsc->save("$dscfn.tmp") or die $!;
1984
1985     my $changes = parsecontrol($changesfile,$changesfilewhat);
1986     foreach my $field (qw(Source Distribution Version)) {
1987         $changes->{$field} eq $clogp->{$field} or
1988             fail "changes field $field \`$changes->{$field}'".
1989                 " does not match changelog \`$clogp->{$field}'";
1990     }
1991
1992     my $cversion = getfield $clogp, 'Version';
1993     my $clogsuite = getfield $clogp, 'Distribution';
1994
1995     # We make the git tag by hand because (a) that makes it easier
1996     # to control the "tagger" (b) we can do remote signing
1997     my $authline = clogp_authline $clogp;
1998     my $delibs = join(" ", "",@deliberatelies);
1999     my $declaredistro = access_basedistro();
2000
2001     my $mktag = sub {
2002         my ($tw) = @_;
2003         my $tfn = $tw->{Tfn};
2004         my $head = $tw->{Objid};
2005         my $tag = $tw->{Tag};
2006
2007         open TO, '>', $tfn->('.tmp') or die $!;
2008         print TO <<END or die $!;
2009 object $head
2010 type commit
2011 tag $tag
2012 tagger $authline
2013
2014 $package release $cversion for $clogsuite ($csuite) [dgit]
2015 [dgit distro=$declaredistro$delibs]
2016 END
2017         foreach my $ref (sort keys %previously) {
2018             print TO <<END or die $!;
2019 [dgit previously:$ref=$previously{$ref}]
2020 END
2021         }
2022
2023         close TO or die $!;
2024
2025         my $tagobjfn = $tfn->('.tmp');
2026         if ($sign) {
2027             if (!defined $keyid) {
2028                 $keyid = access_cfg('keyid','RETURN-UNDEF');
2029             }
2030             if (!defined $keyid) {
2031                 $keyid = getfield $clogp, 'Maintainer';
2032             }
2033             unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
2034             my @sign_cmd = (@gpg, qw(--detach-sign --armor));
2035             push @sign_cmd, qw(-u),$keyid if defined $keyid;
2036             push @sign_cmd, $tfn->('.tmp');
2037             runcmd_ordryrun @sign_cmd;
2038             if (act_scary()) {
2039                 $tagobjfn = $tfn->('.signed.tmp');
2040                 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
2041                     $tfn->('.tmp'), $tfn->('.tmp.asc');
2042             }
2043         }
2044         return $tagobjfn;
2045     };
2046
2047     my @r = map { $mktag->($_); } @$tagwants;
2048     return @r;
2049 }
2050
2051 sub sign_changes ($) {
2052     my ($changesfile) = @_;
2053     if ($sign) {
2054         my @debsign_cmd = @debsign;
2055         push @debsign_cmd, "-k$keyid" if defined $keyid;
2056         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
2057         push @debsign_cmd, $changesfile;
2058         runcmd_ordryrun @debsign_cmd;
2059     }
2060 }
2061
2062 sub dopush ($) {
2063     my ($forceflag) = @_;
2064     printdebug "actually entering push\n";
2065     supplementary_message(<<'END');
2066 Push failed, while preparing your push.
2067 You can retry the push, after fixing the problem, if you like.
2068 END
2069     prep_ud();
2070
2071     access_giturl(); # check that success is vaguely likely
2072     select_tagformat();
2073
2074     my $clogpfn = ".git/dgit/changelog.822.tmp";
2075     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
2076
2077     responder_send_file('parsed-changelog', $clogpfn);
2078
2079     my ($clogp, $cversion, $dscfn) =
2080         push_parse_changelog("$clogpfn");
2081
2082     my $dscpath = "$buildproductsdir/$dscfn";
2083     stat_exists $dscpath or
2084         fail "looked for .dsc $dscfn, but $!;".
2085             " maybe you forgot to build";
2086
2087     responder_send_file('dsc', $dscpath);
2088
2089     push_parse_dsc($dscpath, $dscfn, $cversion);
2090
2091     my $format = getfield $dsc, 'Format';
2092     printdebug "format $format\n";
2093
2094     my $head = git_rev_parse('HEAD');
2095
2096     if (madformat($format)) {
2097         # user might have not used dgit build, so maybe do this now:
2098         if (quiltmode_splitbrain()) {
2099             my $upstreamversion = $clogp->{Version};
2100             $upstreamversion =~ s/-[^-]*$//;
2101             changedir $ud;
2102             quilt_make_fake_dsc($upstreamversion);
2103             my ($dgitview, $cachekey) =
2104                 quilt_check_splitbrain_cache($head, $upstreamversion);
2105             $dgitview or fail
2106  "--quilt=$quilt_mode but no cached dgit view:
2107  perhaps tree changed since dgit build[-source] ?";
2108             $split_brain = 1;
2109             changedir '../../../..';
2110             prep_ud(); # so _only_subdir() works, below
2111         } else {
2112             commit_quilty_patch();
2113         }
2114     }
2115
2116     die 'xxx fast forward (should not depend on quilt mode, but will always be needed if we did $split_brain)' if $split_brain;
2117
2118     check_not_dirty();
2119     changedir $ud;
2120     progress "checking that $dscfn corresponds to HEAD";
2121     runcmd qw(dpkg-source -x --),
2122         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
2123     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
2124     check_for_vendor_patches() if madformat($dsc->{format});
2125     changedir '../../../..';
2126     my $diffopt = $debuglevel>0 ? '--exit-code' : '--quiet';
2127     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
2128     debugcmd "+",@diffcmd;
2129     $!=0; $?=-1;
2130     my $r = system @diffcmd;
2131     if ($r) {
2132         if ($r==256) {
2133             fail "$dscfn specifies a different tree to your HEAD commit;".
2134                 " perhaps you forgot to build".
2135                 ($diffopt eq '--exit-code' ? "" :
2136                  " (run with -D to see full diff output)");
2137         } else {
2138             failedcmd @diffcmd;
2139         }
2140     }
2141     if (!$changesfile) {
2142         my $pat = changespat $cversion;
2143         my @cs = glob "$buildproductsdir/$pat";
2144         fail "failed to find unique changes file".
2145             " (looked for $pat in $buildproductsdir);".
2146             " perhaps you need to use dgit -C"
2147             unless @cs==1;
2148         ($changesfile) = @cs;
2149     } else {
2150         $changesfile = "$buildproductsdir/$changesfile";
2151     }
2152
2153     responder_send_file('changes',$changesfile);
2154     responder_send_command("param head $head");
2155     responder_send_command("param csuite $csuite");
2156     responder_send_command("param tagformat $tagformat");
2157
2158     if (deliberately_not_fast_forward) {
2159         git_for_each_ref(lrfetchrefs, sub {
2160             my ($objid,$objtype,$lrfetchrefname,$reftail) = @_;
2161             my $rrefname= substr($lrfetchrefname, length(lrfetchrefs) + 1);
2162             responder_send_command("previously $rrefname=$objid");
2163             $previously{$rrefname} = $objid;
2164         });
2165     }
2166
2167     my @tagwants = push_tagwants($cversion, $head,
2168                                  ".git/dgit/tag");
2169     my @tagobjfns;
2170
2171     supplementary_message(<<'END');
2172 Push failed, while signing the tag.
2173 You can retry the push, after fixing the problem, if you like.
2174 END
2175     # If we manage to sign but fail to record it anywhere, it's fine.
2176     if ($we_are_responder) {
2177         @tagobjfns = map { $_->{Tfn}('.signed-tmp') } @tagwants;
2178         responder_receive_files('signed-tag', @tagobjfns);
2179     } else {
2180         @tagobjfns = push_mktags($clogp,$dscpath,
2181                               $changesfile,$changesfile,
2182                               \@tagwants);
2183     }
2184     supplementary_message(<<'END');
2185 Push failed, *after* signing the tag.
2186 If you want to try again, you should use a new version number.
2187 END
2188
2189     pairwise { $a->{TagObjFn} = $b } @tagwants, @tagobjfns;
2190
2191     foreach my $tw (@tagwants) {
2192         my $tag = $tw->{Tag};
2193         my $tagobjfn = $tw->{TagObjFn};
2194         my $tag_obj_hash =
2195             cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
2196         runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
2197         runcmd_ordryrun_local
2198             @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
2199     }
2200
2201     supplementary_message(<<'END');
2202 Push failed, while updating the remote git repository - see messages above.
2203 If you want to try again, you should use a new version number.
2204 END
2205     if (!check_for_git()) {
2206         create_remote_git_repo();
2207     }
2208
2209     my @pushrefs = $forceflag."HEAD:".rrref();
2210     foreach my $tw (@tagwants) {
2211         push @pushrefs, $forceflag."refs/tags/$tw->{Tag}";
2212     }
2213
2214     runcmd_ordryrun @git, qw(push),access_giturl(), @pushrefs;
2215     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
2216
2217     supplementary_message(<<'END');
2218 Push failed, after updating the remote git repository.
2219 If you want to try again, you must use a new version number.
2220 END
2221     if ($we_are_responder) {
2222         my $dryrunsuffix = act_local() ? "" : ".tmp";
2223         responder_receive_files('signed-dsc-changes',
2224                                 "$dscpath$dryrunsuffix",
2225                                 "$changesfile$dryrunsuffix");
2226     } else {
2227         if (act_local()) {
2228             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
2229         } else {
2230             progress "[new .dsc left in $dscpath.tmp]";
2231         }
2232         sign_changes $changesfile;
2233     }
2234
2235     supplementary_message(<<END);
2236 Push failed, while uploading package(s) to the archive server.
2237 You can retry the upload of exactly these same files with dput of:
2238   $changesfile
2239 If that .changes file is broken, you will need to use a new version
2240 number for your next attempt at the upload.
2241 END
2242     my $host = access_cfg('upload-host','RETURN-UNDEF');
2243     my @hostarg = defined($host) ? ($host,) : ();
2244     runcmd_ordryrun @dput, @hostarg, $changesfile;
2245     printdone "pushed and uploaded $cversion";
2246
2247     supplementary_message('');
2248     responder_send_command("complete");
2249 }
2250
2251 sub cmd_clone {
2252     parseopts();
2253     notpushing();
2254     my $dstdir;
2255     badusage "-p is not allowed with clone; specify as argument instead"
2256         if defined $package;
2257     if (@ARGV==1) {
2258         ($package) = @ARGV;
2259     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
2260         ($package,$isuite) = @ARGV;
2261     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
2262         ($package,$dstdir) = @ARGV;
2263     } elsif (@ARGV==3) {
2264         ($package,$isuite,$dstdir) = @ARGV;
2265     } else {
2266         badusage "incorrect arguments to dgit clone";
2267     }
2268     $dstdir ||= "$package";
2269
2270     if (stat_exists $dstdir) {
2271         fail "$dstdir already exists";
2272     }
2273
2274     my $cwd_remove;
2275     if ($rmonerror && !$dryrun_level) {
2276         $cwd_remove= getcwd();
2277         unshift @end, sub { 
2278             return unless defined $cwd_remove;
2279             if (!chdir "$cwd_remove") {
2280                 return if $!==&ENOENT;
2281                 die "chdir $cwd_remove: $!";
2282             }
2283             if (stat $dstdir) {
2284                 rmtree($dstdir) or die "remove $dstdir: $!\n";
2285             } elsif (!grep { $! == $_ }
2286                      (ENOENT, ENOTDIR, EACCES, EPERM, ELOOP)) {
2287             } else {
2288                 print STDERR "check whether to remove $dstdir: $!\n";
2289             }
2290         };
2291     }
2292
2293     clone($dstdir);
2294     $cwd_remove = undef;
2295 }
2296
2297 sub branchsuite () {
2298     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
2299     if ($branch =~ m#$lbranch_re#o) {
2300         return $1;
2301     } else {
2302         return undef;
2303     }
2304 }
2305
2306 sub fetchpullargs () {
2307     notpushing();
2308     if (!defined $package) {
2309         my $sourcep = parsecontrol('debian/control','debian/control');
2310         $package = getfield $sourcep, 'Source';
2311     }
2312     if (@ARGV==0) {
2313 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
2314         if (!$isuite) {
2315             my $clogp = parsechangelog();
2316             $isuite = getfield $clogp, 'Distribution';
2317         }
2318         canonicalise_suite();
2319         progress "fetching from suite $csuite";
2320     } elsif (@ARGV==1) {
2321         ($isuite) = @ARGV;
2322         canonicalise_suite();
2323     } else {
2324         badusage "incorrect arguments to dgit fetch or dgit pull";
2325     }
2326 }
2327
2328 sub cmd_fetch {
2329     parseopts();
2330     fetchpullargs();
2331     fetch();
2332 }
2333
2334 sub cmd_pull {
2335     parseopts();
2336     fetchpullargs();
2337     pull();
2338 }
2339
2340 sub cmd_push {
2341     parseopts();
2342     pushing();
2343     badusage "-p is not allowed with dgit push" if defined $package;
2344     check_not_dirty();
2345     my $clogp = parsechangelog();
2346     $package = getfield $clogp, 'Source';
2347     my $specsuite;
2348     if (@ARGV==0) {
2349     } elsif (@ARGV==1) {
2350         ($specsuite) = (@ARGV);
2351     } else {
2352         badusage "incorrect arguments to dgit push";
2353     }
2354     $isuite = getfield $clogp, 'Distribution';
2355     if ($new_package) {
2356         local ($package) = $existing_package; # this is a hack
2357         canonicalise_suite();
2358     } else {
2359         canonicalise_suite();
2360     }
2361     if (defined $specsuite &&
2362         $specsuite ne $isuite &&
2363         $specsuite ne $csuite) {
2364             fail "dgit push: changelog specifies $isuite ($csuite)".
2365                 " but command line specifies $specsuite";
2366     }
2367     supplementary_message(<<'END');
2368 Push failed, while checking state of the archive.
2369 You can retry the push, after fixing the problem, if you like.
2370 END
2371     if (check_for_git()) {
2372         git_fetch_us();
2373     }
2374     my $forceflag = '';
2375     if (fetch_from_archive()) {
2376         if (is_fast_fwd(lrref(), 'HEAD')) {
2377             # ok
2378         } elsif (deliberately_not_fast_forward) {
2379             $forceflag = '+';
2380         } else {
2381             fail "dgit push: HEAD is not a descendant".
2382                 " of the archive's version.\n".
2383                 "dgit: To overwrite its contents,".
2384                 " use git merge -s ours ".lrref().".\n".
2385                 "dgit: To rewind history, if permitted by the archive,".
2386                 " use --deliberately-not-fast-forward";
2387         }
2388     } else {
2389         $new_package or
2390             fail "package appears to be new in this suite;".
2391                 " if this is intentional, use --new";
2392     }
2393     dopush($forceflag);
2394 }
2395
2396 #---------- remote commands' implementation ----------
2397
2398 sub cmd_remote_push_build_host {
2399     my ($nrargs) = shift @ARGV;
2400     my (@rargs) = @ARGV[0..$nrargs-1];
2401     @ARGV = @ARGV[$nrargs..$#ARGV];
2402     die unless @rargs;
2403     my ($dir,$vsnwant) = @rargs;
2404     # vsnwant is a comma-separated list; we report which we have
2405     # chosen in our ready response (so other end can tell if they
2406     # offered several)
2407     $debugprefix = ' ';
2408     $we_are_responder = 1;
2409     $us .= " (build host)";
2410
2411     pushing();
2412
2413     open PI, "<&STDIN" or die $!;
2414     open STDIN, "/dev/null" or die $!;
2415     open PO, ">&STDOUT" or die $!;
2416     autoflush PO 1;
2417     open STDOUT, ">&STDERR" or die $!;
2418     autoflush STDOUT 1;
2419
2420     $vsnwant //= 1;
2421     ($protovsn) = grep {
2422         $vsnwant =~ m{^(?:.*,)?$_(?:,.*)?$}
2423     } @rpushprotovsn_support;
2424
2425     fail "build host has dgit rpush protocol versions ".
2426         (join ",", @rpushprotovsn_support).
2427         " but invocation host has $vsnwant"
2428         unless defined $protovsn;
2429
2430     responder_send_command("dgit-remote-push-ready $protovsn");
2431     rpush_handle_protovsn_bothends();
2432     changedir $dir;
2433     &cmd_push;
2434 }
2435
2436 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
2437 # ... for compatibility with proto vsn.1 dgit (just so that user gets
2438 #     a good error message)
2439
2440 sub rpush_handle_protovsn_bothends () {
2441     if ($protovsn < 4) {
2442         need_tagformat 'old', "rpush negotiated protocol $protovsn";
2443     }
2444     select_tagformat();
2445 }
2446
2447 our $i_tmp;
2448
2449 sub i_cleanup {
2450     local ($@, $?);
2451     my $report = i_child_report();
2452     if (defined $report) {
2453         printdebug "($report)\n";
2454     } elsif ($i_child_pid) {
2455         printdebug "(killing build host child $i_child_pid)\n";
2456         kill 15, $i_child_pid;
2457     }
2458     if (defined $i_tmp && !defined $initiator_tempdir) {
2459         changedir "/";
2460         eval { rmtree $i_tmp; };
2461     }
2462 }
2463
2464 END { i_cleanup(); }
2465
2466 sub i_method {
2467     my ($base,$selector,@args) = @_;
2468     $selector =~ s/\-/_/g;
2469     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
2470 }
2471
2472 sub cmd_rpush {
2473     pushing();
2474     my $host = nextarg;
2475     my $dir;
2476     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
2477         $host = $1;
2478         $dir = $'; #';
2479     } else {
2480         $dir = nextarg;
2481     }
2482     $dir =~ s{^-}{./-};
2483     my @rargs = ($dir);
2484     push @rargs, join ",", @rpushprotovsn_support;
2485     my @rdgit;
2486     push @rdgit, @dgit;
2487     push @rdgit, @ropts;
2488     push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
2489     push @rdgit, @ARGV;
2490     my @cmd = (@ssh, $host, shellquote @rdgit);
2491     debugcmd "+",@cmd;
2492
2493     if (defined $initiator_tempdir) {
2494         rmtree $initiator_tempdir;
2495         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
2496         $i_tmp = $initiator_tempdir;
2497     } else {
2498         $i_tmp = tempdir();
2499     }
2500     $i_child_pid = open2(\*RO, \*RI, @cmd);
2501     changedir $i_tmp;
2502     ($protovsn) = initiator_expect { m/^dgit-remote-push-ready (\S+)/ };
2503     die "$protovsn ?" unless grep { $_ eq $protovsn } @rpushprotovsn_support;
2504     $supplementary_message = '' unless $protovsn >= 3;
2505     rpush_handle_protovsn_bothends();
2506     for (;;) {
2507         my ($icmd,$iargs) = initiator_expect {
2508             m/^(\S+)(?: (.*))?$/;
2509             ($1,$2);
2510         };
2511         i_method "i_resp", $icmd, $iargs;
2512     }
2513 }
2514
2515 sub i_resp_progress ($) {
2516     my ($rhs) = @_;
2517     my $msg = protocol_read_bytes \*RO, $rhs;
2518     progress $msg;
2519 }
2520
2521 sub i_resp_supplementary_message ($) {
2522     my ($rhs) = @_;
2523     $supplementary_message = protocol_read_bytes \*RO, $rhs;
2524 }
2525
2526 sub i_resp_complete {
2527     my $pid = $i_child_pid;
2528     $i_child_pid = undef; # prevents killing some other process with same pid
2529     printdebug "waiting for build host child $pid...\n";
2530     my $got = waitpid $pid, 0;
2531     die $! unless $got == $pid;
2532     die "build host child failed $?" if $?;
2533
2534     i_cleanup();
2535     printdebug "all done\n";
2536     exit 0;
2537 }
2538
2539 sub i_resp_file ($) {
2540     my ($keyword) = @_;
2541     my $localname = i_method "i_localname", $keyword;
2542     my $localpath = "$i_tmp/$localname";
2543     stat_exists $localpath and
2544         badproto \*RO, "file $keyword ($localpath) twice";
2545     protocol_receive_file \*RO, $localpath;
2546     i_method "i_file", $keyword;
2547 }
2548
2549 our %i_param;
2550
2551 sub i_resp_param ($) {
2552     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
2553     $i_param{$1} = $2;
2554 }
2555
2556 sub i_resp_previously ($) {
2557     $_[0] =~ m#^(refs/tags/\S+)=(\w+)$#
2558         or badproto \*RO, "bad previously spec";
2559     my $r = system qw(git check-ref-format), $1;
2560     die "bad previously ref spec ($r)" if $r;
2561     $previously{$1} = $2;
2562 }
2563
2564 our %i_wanted;
2565
2566 sub i_resp_want ($) {
2567     my ($keyword) = @_;
2568     die "$keyword ?" if $i_wanted{$keyword}++;
2569     my @localpaths = i_method "i_want", $keyword;
2570     printdebug "[[  $keyword @localpaths\n";
2571     foreach my $localpath (@localpaths) {
2572         protocol_send_file \*RI, $localpath;
2573     }
2574     print RI "files-end\n" or die $!;
2575 }
2576
2577 our ($i_clogp, $i_version, $i_dscfn, $i_changesfn);
2578
2579 sub i_localname_parsed_changelog {
2580     return "remote-changelog.822";
2581 }
2582 sub i_file_parsed_changelog {
2583     ($i_clogp, $i_version, $i_dscfn) =
2584         push_parse_changelog "$i_tmp/remote-changelog.822";
2585     die if $i_dscfn =~ m#/|^\W#;
2586 }
2587
2588 sub i_localname_dsc {
2589     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2590     return $i_dscfn;
2591 }
2592 sub i_file_dsc { }
2593
2594 sub i_localname_changes {
2595     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2596     $i_changesfn = $i_dscfn;
2597     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2598     return $i_changesfn;
2599 }
2600 sub i_file_changes { }
2601
2602 sub i_want_signed_tag {
2603     printdebug Dumper(\%i_param, $i_dscfn);
2604     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2605         && defined $i_param{'csuite'}
2606         or badproto \*RO, "premature desire for signed-tag";
2607     my $head = $i_param{'head'};
2608     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2609
2610     select_tagformat();
2611     if ($protovsn >= 4) {
2612         my $p = $i_param{'tagformat'} // '<undef>';
2613         $p eq $tagformat
2614             or badproto \*RO, "tag format mismatch: $p vs. $tagformat";
2615     }
2616
2617     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2618     $csuite = $&;
2619     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2620
2621     my @tagwants = push_tagwants $i_version, $head, "tag";
2622
2623     return
2624         push_mktags $i_clogp, $i_dscfn,
2625             $i_changesfn, 'remote changes',
2626             \@tagwants;
2627 }
2628
2629 sub i_want_signed_dsc_changes {
2630     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2631     sign_changes $i_changesfn;
2632     return ($i_dscfn, $i_changesfn);
2633 }
2634
2635 #---------- building etc. ----------
2636
2637 our $version;
2638 our $sourcechanges;
2639 our $dscfn;
2640
2641 #----- `3.0 (quilt)' handling -----
2642
2643 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2644
2645 sub quiltify_dpkg_commit ($$$;$) {
2646     my ($patchname,$author,$msg, $xinfo) = @_;
2647     $xinfo //= '';
2648
2649     mkpath '.git/dgit';
2650     my $descfn = ".git/dgit/quilt-description.tmp";
2651     open O, '>', $descfn or die "$descfn: $!";
2652     $msg =~ s/\s+$//g;
2653     $msg =~ s/\n/\n /g;
2654     $msg =~ s/^\s+$/ ./mg;
2655     print O <<END or die $!;
2656 Description: $msg
2657 Author: $author
2658 $xinfo
2659 ---
2660
2661 END
2662     close O or die $!;
2663
2664     {
2665         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2666         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2667         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2668         runcmd @dpkgsource, qw(--commit .), $patchname;
2669     }
2670 }
2671
2672 sub quiltify_trees_differ ($$;$$) {
2673     my ($x,$y,$finegrained,$ignorenamesr) = @_;
2674     # returns true iff the two tree objects differ other than in debian/
2675     # with $finegrained,
2676     # returns bitmask 01 - differ in upstream files except .gitignore
2677     #                 02 - differ in .gitignore
2678     # if $ignorenamesr is defined, $ingorenamesr->{$fn}
2679     #  is set for each modified .gitignore filename $fn
2680     local $/=undef;
2681     my @cmd = (@git, qw(diff-tree --name-only -z));
2682     push @cmd, qw(-r) if $finegrained;
2683     push @cmd, $x, $y;
2684     my $diffs= cmdoutput @cmd;
2685     my $r = 0;
2686     foreach my $f (split /\0/, $diffs) {
2687         next if $f =~ m#^debian(?:/.*)?$#s;
2688         my $isignore = $f =~ m#^(?:.*/)?.gitignore$#s;
2689         $r |= $isignore ? 02 : 01;
2690         $ignorenamesr->{$f}=1 if $ignorenamesr && $isignore;
2691     }
2692     printdebug "quiltify_trees_differ $x $y => $r\n";
2693     return $r;
2694 }
2695
2696 sub quiltify_tree_sentinelfiles ($) {
2697     # lists the `sentinel' files present in the tree
2698     my ($x) = @_;
2699     my $r = cmdoutput @git, qw(ls-tree --name-only), $x,
2700         qw(-- debian/rules debian/control);
2701     $r =~ s/\n/,/g;
2702     return $r;
2703 }
2704
2705 sub quiltify_splitbrain_needed () {
2706     if (!$split_brain) {
2707         progress "dgit view: changes are required...";
2708         runcmd @git, qw(checkout -q -b dgit-view);
2709         $split_brain = 1;
2710     }
2711 }
2712
2713 sub quiltify_splitbrain ($$$$$$) {
2714     my ($clogp, $unapplied, $headref, $diffbits,
2715         $editedignores, $cachekey) = @_;
2716     if ($quilt_mode !~ m/gbp|dpm/) {
2717         # treat .gitignore just like any other upstream file
2718         $diffbits = { %$diffbits };
2719         $_ = !!$_ foreach values %$diffbits;
2720     }
2721     # We would like any commits we generate to be reproducible
2722     my @authline = clogp_authline($clogp);
2723     local $ENV{GIT_COMMITTER_NAME} =  $authline[0];
2724     local $ENV{GIT_COMMITTER_EMAIL} = $authline[1];
2725     local $ENV{GIT_COMMITTER_DATE} =  $authline[2];
2726         
2727     if ($quilt_mode =~ m/gbp|unapplied/ &&
2728         ($diffbits->{H2O} & 01)) {
2729         my $msg =
2730  "--quilt=$quilt_mode specified, implying patches-unapplied git tree\n".
2731  " but git tree differs from orig in upstream files.";
2732         if (!stat_exists "debian/patches") {
2733             $msg .=
2734  "\n ... debian/patches is missing; perhaps this is a patch queue branch?";
2735         }  
2736         fail $msg;
2737     }
2738     if ($quilt_mode =~ m/gbp|unapplied/ &&
2739         ($diffbits->{O2A} & 01)) { # some patches
2740         quiltify_splitbrain_needed();
2741         progress "dgit view: creating patches-applied version using gbp pq";
2742         runcmd shell_cmd 'exec >/dev/null', @gbp, qw(pq import);
2743         # gbp pq import creates a fresh branch; push back to dgit-view
2744         runcmd @git, qw(update-ref refs/heads/dgit-view HEAD);
2745         runcmd @git, qw(checkout -q dgit-view);
2746     }
2747     if (($diffbits->{H2O} & 02) && # user has modified .gitignore
2748         !($diffbits->{O2A} & 02)) { # patches do not change .gitignore
2749         quiltify_splitbrain_needed();
2750         progress "dgit view: creating patch to represent .gitignore changes";
2751         ensuredir "debian/patches";
2752         my $gipatch = "debian/patches/auto-gitignore";
2753         open GIPATCH, ">>", "$gipatch" or die "$gipatch: $!";
2754         stat GIPATCH or die "$gipatch: $!";
2755         fail "$gipatch already exists; but want to create it".
2756             " to record .gitignore changes" if (stat _)[7];
2757         print GIPATCH <<END or die "$gipatch: $!";
2758 Subject: Update .gitignore from Debian packaging branch
2759
2760 The Debian packaging git branch contains these updates to the upstream
2761 .gitignore file(s).  This patch is autogenerated, to provide these
2762 updates to users of the official Debian archive view of the package.
2763
2764 [dgit version $our_version]
2765 ---
2766 END
2767         close GIPATCH or die "$gipatch: $!";
2768         runcmd shell_cmd "exec >>$gipatch", @git, qw(diff),
2769             $unapplied, $headref, "--", sort keys %$editedignores;
2770         open SERIES, "+>>", "debian/patches/series" or die $!;
2771         defined seek SERIES, -1, 2 or $!==EINVAL or die $!;
2772         my $newline;
2773         defined read SERIES, $newline, 1 or die $!;
2774         print SERIES "\n" or die $! unless $newline eq "\n";
2775         print SERIES "auto-gitignore\n" or die $!;
2776         close SERIES or die  $!;
2777         runcmd @git, qw(add -- debian/patches/series), $gipatch;
2778         commit_admin "Commit patch to update .gitignore";
2779     }
2780
2781     my $dgitview = git_rev_parse 'refs/heads/dgit-view';
2782
2783     changedir '../../../..';
2784     ensuredir ".git/logs/refs/dgit-intern";
2785     my $makelogfh = new IO::File ".git/logs/refs/$splitbraincache", '>>'
2786       or die $!;
2787     runcmd @git, qw(update-ref -m), $cachekey, "refs/$splitbraincache",
2788         $dgitview;
2789
2790     progress "dgit view: created (commit id $dgitview)";
2791
2792     changedir '.git/dgit/unpack/work';
2793 }
2794
2795 sub quiltify ($$$$) {
2796     my ($clogp,$target,$oldtiptree,$failsuggestion) = @_;
2797
2798     # Quilt patchification algorithm
2799     #
2800     # We search backwards through the history of the main tree's HEAD
2801     # (T) looking for a start commit S whose tree object is identical
2802     # to to the patch tip tree (ie the tree corresponding to the
2803     # current dpkg-committed patch series).  For these purposes
2804     # `identical' disregards anything in debian/ - this wrinkle is
2805     # necessary because dpkg-source treates debian/ specially.
2806     #
2807     # We can only traverse edges where at most one of the ancestors'
2808     # trees differs (in changes outside in debian/).  And we cannot
2809     # handle edges which change .pc/ or debian/patches.  To avoid
2810     # going down a rathole we avoid traversing edges which introduce
2811     # debian/rules or debian/control.  And we set a limit on the
2812     # number of edges we are willing to look at.
2813     #
2814     # If we succeed, we walk forwards again.  For each traversed edge
2815     # PC (with P parent, C child) (starting with P=S and ending with
2816     # C=T) to we do this:
2817     #  - git checkout C
2818     #  - dpkg-source --commit with a patch name and message derived from C
2819     # After traversing PT, we git commit the changes which
2820     # should be contained within debian/patches.
2821
2822     # The search for the path S..T is breadth-first.  We maintain a
2823     # todo list containing search nodes.  A search node identifies a
2824     # commit, and looks something like this:
2825     #  $p = {
2826     #      Commit => $git_commit_id,
2827     #      Child => $c,                          # or undef if P=T
2828     #      Whynot => $reason_edge_PC_unsuitable, # in @nots only
2829     #      Nontrivial => true iff $p..$c has relevant changes
2830     #  };
2831
2832     my @todo;
2833     my @nots;
2834     my $sref_S;
2835     my $max_work=100;
2836     my %considered; # saves being exponential on some weird graphs
2837
2838     my $t_sentinels = quiltify_tree_sentinelfiles $target;
2839
2840     my $not = sub {
2841         my ($search,$whynot) = @_;
2842         printdebug " search NOT $search->{Commit} $whynot\n";
2843         $search->{Whynot} = $whynot;
2844         push @nots, $search;
2845         no warnings qw(exiting);
2846         next;
2847     };
2848
2849     push @todo, {
2850         Commit => $target,
2851     };
2852
2853     while (@todo) {
2854         my $c = shift @todo;
2855         next if $considered{$c->{Commit}}++;
2856
2857         $not->($c, "maximum search space exceeded") if --$max_work <= 0;
2858
2859         printdebug "quiltify investigate $c->{Commit}\n";
2860
2861         # are we done?
2862         if (!quiltify_trees_differ $c->{Commit}, $oldtiptree) {
2863             printdebug " search finished hooray!\n";
2864             $sref_S = $c;
2865             last;
2866         }
2867
2868         if ($quilt_mode eq 'nofix') {
2869             fail "quilt fixup required but quilt mode is \`nofix'\n".
2870                 "HEAD commit $c->{Commit} differs from tree implied by ".
2871                 " debian/patches (tree object $oldtiptree)";
2872         }
2873         if ($quilt_mode eq 'smash') {
2874             printdebug " search quitting smash\n";
2875             last;
2876         }
2877
2878         my $c_sentinels = quiltify_tree_sentinelfiles $c->{Commit};
2879         $not->($c, "has $c_sentinels not $t_sentinels")
2880             if $c_sentinels ne $t_sentinels;
2881
2882         my $commitdata = cmdoutput @git, qw(cat-file commit), $c->{Commit};
2883         $commitdata =~ m/\n\n/;
2884         $commitdata =~ $`;
2885         my @parents = ($commitdata =~ m/^parent (\w+)$/gm);
2886         @parents = map { { Commit => $_, Child => $c } } @parents;
2887
2888         $not->($c, "root commit") if !@parents;
2889
2890         foreach my $p (@parents) {
2891             $p->{Nontrivial}= quiltify_trees_differ $p->{Commit},$c->{Commit};
2892         }
2893         my $ndiffers = grep { $_->{Nontrivial} } @parents;
2894         $not->($c, "merge ($ndiffers nontrivial parents)") if $ndiffers > 1;
2895
2896         foreach my $p (@parents) {
2897             printdebug "considering C=$c->{Commit} P=$p->{Commit}\n";
2898
2899             my @cmd= (@git, qw(diff-tree -r --name-only),
2900                       $p->{Commit},$c->{Commit}, qw(-- debian/patches .pc));
2901             my $patchstackchange = cmdoutput @cmd;
2902             if (length $patchstackchange) {
2903                 $patchstackchange =~ s/\n/,/g;
2904                 $not->($p, "changed $patchstackchange");
2905             }
2906
2907             printdebug " search queue P=$p->{Commit} ",
2908                 ($p->{Nontrivial} ? "NT" : "triv"),"\n";
2909             push @todo, $p;
2910         }
2911     }
2912
2913     if (!$sref_S) {
2914         printdebug "quiltify want to smash\n";
2915
2916         my $abbrev = sub {
2917             my $x = $_[0]{Commit};
2918             $x =~ s/(.*?[0-9a-z]{8})[0-9a-z]*$/$1/;
2919             return $x;
2920         };
2921         my $reportnot = sub {
2922             my ($notp) = @_;
2923             my $s = $abbrev->($notp);
2924             my $c = $notp->{Child};
2925             $s .= "..".$abbrev->($c) if $c;
2926             $s .= ": ".$notp->{Whynot};
2927             return $s;
2928         };
2929         if ($quilt_mode eq 'linear') {
2930             print STDERR "$us: quilt fixup cannot be linear.  Stopped at:\n";
2931             foreach my $notp (@nots) {
2932                 print STDERR "$us:  ", $reportnot->($notp), "\n";
2933             }
2934             print STDERR "$us: $_\n" foreach @$failsuggestion;
2935             fail "quilt fixup naive history linearisation failed.\n".
2936  "Use dpkg-source --commit by hand; or, --quilt=smash for one ugly patch";
2937         } elsif ($quilt_mode eq 'smash') {
2938         } elsif ($quilt_mode eq 'auto') {
2939             progress "quilt fixup cannot be linear, smashing...";
2940         } else {
2941             die "$quilt_mode ?";
2942         }
2943
2944         my $time = $ENV{'GIT_COMMITTER_DATE'} || time;
2945         $time =~ s/\s.*//; # trim timezone from GIT_COMMITTER_DATE
2946         my $ncommits = 3;
2947         my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2948
2949         quiltify_dpkg_commit "auto-$version-$target-$time",
2950             (getfield $clogp, 'Maintainer'),
2951             "Automatically generated patch ($clogp->{Version})\n".
2952             "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2953         return;
2954     }
2955
2956     progress "quiltify linearisation planning successful, executing...";
2957
2958     for (my $p = $sref_S;
2959          my $c = $p->{Child};
2960          $p = $p->{Child}) {
2961         printdebug "quiltify traverse $p->{Commit}..$c->{Commit}\n";
2962         next unless $p->{Nontrivial};
2963
2964         my $cc = $c->{Commit};
2965
2966         my $commitdata = cmdoutput @git, qw(cat-file commit), $cc;
2967         $commitdata =~ m/\n\n/ or die "$c ?";
2968         $commitdata = $`;
2969         my $msg = $'; #';
2970         $commitdata =~ m/^author (.*) \d+ [-+0-9]+$/m or die "$cc ?";
2971         my $author = $1;
2972
2973         $msg =~ s/^(.*)\n*/$1\n/ or die "$cc $msg ?";
2974
2975         my $title = $1;
2976         my $patchname = $title;
2977         $patchname =~ s/[.:]$//;
2978         $patchname =~ y/ A-Z/-a-z/;
2979         $patchname =~ y/-a-z0-9_.+=~//cd;
2980         $patchname =~ s/^\W/x-$&/;
2981         $patchname = substr($patchname,0,40);
2982         my $index;
2983         for ($index='';
2984              stat "debian/patches/$patchname$index";
2985              $index++) { }
2986         $!==ENOENT or die "$patchname$index $!";
2987
2988         runcmd @git, qw(checkout -q), $cc;
2989
2990         # We use the tip's changelog so that dpkg-source doesn't
2991         # produce complaining messages from dpkg-parsechangelog.  None
2992         # of the information dpkg-source gets from the changelog is
2993         # actually relevant - it gets put into the original message
2994         # which dpkg-source provides our stunt editor, and then
2995         # overwritten.
2996         runcmd @git, qw(checkout -q), $target, qw(debian/changelog);
2997
2998         quiltify_dpkg_commit "$patchname$index", $author, $msg,
2999             "X-Dgit-Generated: $clogp->{Version} $cc\n";
3000
3001         runcmd @git, qw(checkout -q), $cc, qw(debian/changelog);
3002     }
3003
3004     runcmd @git, qw(checkout -q master);
3005 }
3006
3007 sub build_maybe_quilt_fixup () {
3008     my ($format,$fopts) = get_source_format;
3009     return unless madformat $format;
3010     # sigh
3011
3012     check_for_vendor_patches();
3013
3014     my $clogp = parsechangelog();
3015     my $headref = git_rev_parse('HEAD');
3016
3017     prep_ud();
3018     changedir $ud;
3019
3020     my $upstreamversion=$version;
3021     $upstreamversion =~ s/-[^-]*$//;
3022
3023     if ($fopts->{'single-debian-patch'}) {
3024         quilt_fixup_singlepatch($clogp, $headref, $upstreamversion);
3025     } else {
3026         quilt_fixup_multipatch($clogp, $headref, $upstreamversion);
3027     }
3028
3029     die 'bug' if $split_brain && !$need_split_build_invocation;
3030
3031     changedir '../../../..';
3032     runcmd_ordryrun_local
3033         @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
3034 }
3035
3036 sub quilt_fixup_mkwork ($) {
3037     my ($headref) = @_;
3038
3039     mkdir "work" or die $!;
3040     changedir "work";
3041     mktree_in_ud_here();
3042     runcmd @git, qw(reset -q --hard), $headref;
3043 }
3044
3045 sub quilt_fixup_linkorigs ($$) {
3046     my ($upstreamversion, $fn) = @_;
3047     # calls $fn->($leafname);
3048
3049     foreach my $f (<../../../../*>) { #/){
3050         my $b=$f; $b =~ s{.*/}{};
3051         {
3052             local ($debuglevel) = $debuglevel-1;
3053             printdebug "QF linkorigs $b, $f ?\n";
3054         }
3055         next unless is_orig_file $b, srcfn $upstreamversion,'';
3056         printdebug "QF linkorigs $b, $f Y\n";
3057         link_ltarget $f, $b or die "$b $!";
3058         $fn->($b);
3059     }
3060 }
3061
3062 sub quilt_fixup_delete_pc () {
3063     runcmd @git, qw(rm -rqf .pc);
3064     commit_admin "Commit removal of .pc (quilt series tracking data)";
3065 }
3066
3067 sub quilt_fixup_singlepatch ($$$) {
3068     my ($clogp, $headref, $upstreamversion) = @_;
3069
3070     progress "starting quiltify (single-debian-patch)";
3071
3072     # dpkg-source --commit generates new patches even if
3073     # single-debian-patch is in debian/source/options.  In order to
3074     # get it to generate debian/patches/debian-changes, it is
3075     # necessary to build the source package.
3076
3077     quilt_fixup_linkorigs($upstreamversion, sub { });
3078     quilt_fixup_mkwork($headref);
3079
3080     rmtree("debian/patches");
3081
3082     runcmd @dpkgsource, qw(-b .);
3083     chdir "..";
3084     runcmd @dpkgsource, qw(-x), (srcfn $version, ".dsc");
3085     rename srcfn("$upstreamversion", "/debian/patches"), 
3086            "work/debian/patches";
3087
3088     chdir "work";
3089     commit_quilty_patch();
3090 }
3091
3092 sub quilt_make_fake_dsc ($) {
3093     my ($upstreamversion) = @_;
3094
3095     my $fakeversion="$upstreamversion-~~DGITFAKE";
3096
3097     my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
3098     print $fakedsc <<END or die $!;
3099 Format: 3.0 (quilt)
3100 Source: $package
3101 Version: $fakeversion
3102 Files:
3103 END
3104
3105     my $dscaddfile=sub {
3106         my ($b) = @_;
3107         
3108         my $md = new Digest::MD5;
3109
3110         my $fh = new IO::File $b, '<' or die "$b $!";
3111         stat $fh or die $!;
3112         my $size = -s _;
3113
3114         $md->addfile($fh);
3115         print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
3116     };
3117
3118     quilt_fixup_linkorigs($upstreamversion, $dscaddfile);
3119
3120     my @files=qw(debian/source/format debian/rules
3121                  debian/control debian/changelog);
3122     foreach my $maybe (qw(debian/patches debian/source/options
3123                           debian/tests/control)) {
3124         next unless stat_exists "../../../$maybe";
3125         push @files, $maybe;
3126     }
3127
3128     my $debtar= srcfn $fakeversion,'.debian.tar.gz';
3129     runcmd qw(env GZIP=-1n tar -zcf), "./$debtar", qw(-C ../../..), @files;
3130
3131     $dscaddfile->($debtar);
3132     close $fakedsc or die $!;
3133 }
3134
3135 sub quilt_check_splitbrain_cache ($$) {
3136     my ($headref, $upstreamversion) = @_;
3137     # Called only if we are in (potentially) split brain mode.
3138     # Called in $ud.
3139     # Computes the cache key and looks in the cache.
3140     # Returns ($dgit_view_commitid, $cachekey) or (undef, $cachekey)
3141
3142     my $splitbrain_cachekey;
3143     
3144     progress
3145  "dgit: split brain (separate dgit view) may be needed (--quilt=$quilt_mode).";
3146     # we look in the reflog of dgit-intern/quilt-cache
3147     # we look for an entry whose message is the key for the cache lookup
3148     my @cachekey = (qw(dgit), $our_version);
3149     push @cachekey, $upstreamversion;
3150     push @cachekey, $quilt_mode;
3151     push @cachekey, $headref;
3152
3153     push @cachekey, hashfile('fake.dsc');
3154
3155     my $srcshash = Digest::SHA->new(256);
3156     my %sfs = ( %INC, '$0(dgit)' => $0 );
3157     foreach my $sfk (sort keys %sfs) {
3158         next unless m/^\$0\b/ || m{^Debian/Dgit\b};
3159         $srcshash->add($sfk,"  ");
3160         $srcshash->add(hashfile($sfs{$sfk}));
3161         $srcshash->add("\n");
3162     }
3163     push @cachekey, $srcshash->hexdigest();
3164     $splitbrain_cachekey = "@cachekey";
3165
3166     my @cmd = (@git, qw(reflog), '--pretty=format:%H %gs',
3167                $splitbraincache);
3168     printdebug "splitbrain cachekey $splitbrain_cachekey\n";
3169     debugcmd "|(probably)",@cmd;
3170     my $child = open GC, "-|";  defined $child or die $!;
3171     if (!$child) {
3172         chdir '../../..' or die $!;
3173         if (!stat ".git/logs/refs/$splitbraincache") {
3174             $! == ENOENT or die $!;
3175             printdebug ">(no reflog)\n";
3176             exit 0;
3177         }
3178         exec @cmd; die $!;
3179     }
3180     while (<GC>) {
3181         chomp;
3182         printdebug ">| ", $_, "\n" if $debuglevel > 1;
3183         next unless m/^(\w+) (\S.*\S)$/ && $2 eq $splitbrain_cachekey;
3184             
3185         my $cachehit = $1;
3186         quilt_fixup_mkwork($headref);
3187         if ($cachehit ne $headref) {
3188             progress "dgit view: found cached (commit id $cachehit)";
3189             runcmd @git, qw(checkout -q -b dgit-view), $cachehit;
3190             $split_brain = 1;
3191             return ($cachehit, $splitbrain_cachekey);
3192         }
3193         progress "dgit view: found cached, no changes required";
3194         return ($headref, $splitbrain_cachekey);
3195     }
3196     die $! if GC->error;
3197     failedcmd unless close GC;
3198
3199     printdebug "splitbrain cache miss\n";
3200     return (undef, $splitbrain_cachekey);
3201 }
3202
3203 sub quilt_fixup_multipatch ($$$) {
3204     my ($clogp, $headref, $upstreamversion) = @_;
3205
3206     progress "examining quilt state (multiple patches, $quilt_mode mode)";
3207
3208     # Our objective is:
3209     #  - honour any existing .pc in case it has any strangeness
3210     #  - determine the git commit corresponding to the tip of
3211     #    the patch stack (if there is one)
3212     #  - if there is such a git commit, convert each subsequent
3213     #    git commit into a quilt patch with dpkg-source --commit
3214     #  - otherwise convert all the differences in the tree into
3215     #    a single git commit
3216     #
3217     # To do this we:
3218
3219     # Our git tree doesn't necessarily contain .pc.  (Some versions of
3220     # dgit would include the .pc in the git tree.)  If there isn't
3221     # one, we need to generate one by unpacking the patches that we
3222     # have.
3223     #
3224     # We first look for a .pc in the git tree.  If there is one, we
3225     # will use it.  (This is not the normal case.)
3226     #
3227     # Otherwise need to regenerate .pc so that dpkg-source --commit
3228     # can work.  We do this as follows:
3229     #     1. Collect all relevant .orig from parent directory
3230     #     2. Generate a debian.tar.gz out of
3231     #         debian/{patches,rules,source/format,source/options}
3232     #     3. Generate a fake .dsc containing just these fields:
3233     #          Format Source Version Files
3234     #     4. Extract the fake .dsc
3235     #        Now the fake .dsc has a .pc directory.
3236     # (In fact we do this in every case, because in future we will
3237     # want to search for a good base commit for generating patches.)
3238     #
3239     # Then we can actually do the dpkg-source --commit
3240     #     1. Make a new working tree with the same object
3241     #        store as our main tree and check out the main
3242     #        tree's HEAD.
3243     #     2. Copy .pc from the fake's extraction, if necessary
3244     #     3. Run dpkg-source --commit
3245     #     4. If the result has changes to debian/, then
3246     #          - git-add them them
3247     #          - git-add .pc if we had a .pc in-tree
3248     #          - git-commit
3249     #     5. If we had a .pc in-tree, delete it, and git-commit
3250     #     6. Back in the main tree, fast forward to the new HEAD
3251
3252     # Another situation we may have to cope with is gbp-style
3253     # patches-unapplied trees.
3254     #
3255     # We would want to detect these, so we know to escape into
3256     # quilt_fixup_gbp.  However, this is in general not possible.
3257     # Consider a package with a one patch which the dgit user reverts
3258     # (with git-revert or the moral equivalent).
3259     #
3260     # That is indistinguishable in contents from a patches-unapplied
3261     # tree.  And looking at the history to distinguish them is not
3262     # useful because the user might have made a confusing-looking git
3263     # history structure (which ought to produce an error if dgit can't
3264     # cope, not a silent reintroduction of an unwanted patch).
3265     #
3266     # So gbp users will have to pass an option.  But we can usually
3267     # detect their failure to do so: if the tree is not a clean
3268     # patches-applied tree, quilt linearisation fails, but the tree
3269     # _is_ a clean patches-unapplied tree, we can suggest that maybe
3270     # they want --quilt=unapplied.
3271     #
3272     # To help detect this, when we are extracting the fake dsc, we
3273     # first extract it with --skip-patches, and then apply the patches
3274     # afterwards with dpkg-source --before-build.  That lets us save a
3275     # tree object corresponding to .origs.
3276
3277     my $splitbrain_cachekey;
3278
3279     quilt_make_fake_dsc($upstreamversion);
3280
3281     if (quiltmode_splitbrain()) {
3282         my $cachehit;
3283         ($cachehit, $splitbrain_cachekey) =
3284             quilt_check_splitbrain_cache($headref, $upstreamversion);
3285         return if $cachehit;
3286     }
3287
3288     runcmd qw(sh -ec),
3289         'exec dpkg-source --no-check --skip-patches -x fake.dsc >/dev/null';
3290
3291     my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
3292     rename $fakexdir, "fake" or die "$fakexdir $!";
3293
3294     changedir 'fake';
3295
3296     remove_stray_gits();
3297     mktree_in_ud_here();
3298
3299     rmtree '.pc';
3300
3301     runcmd @git, qw(add -Af .);
3302     my $unapplied=git_write_tree();
3303     printdebug "fake orig tree object $unapplied\n";
3304
3305     ensuredir '.pc';
3306
3307     runcmd qw(sh -ec),
3308         'exec dpkg-source --before-build . >/dev/null';
3309
3310     changedir '..';
3311
3312     quilt_fixup_mkwork($headref);
3313
3314     my $mustdeletepc=0;
3315     if (stat_exists ".pc") {
3316         -d _ or die;
3317         progress "Tree already contains .pc - will use it then delete it.";
3318         $mustdeletepc=1;
3319     } else {
3320         rename '../fake/.pc','.pc' or die $!;
3321     }
3322
3323     changedir '../fake';
3324     rmtree '.pc';
3325     runcmd @git, qw(add -Af .);
3326     my $oldtiptree=git_write_tree();
3327     printdebug "fake o+d/p tree object $unapplied\n";
3328     changedir '../work';
3329
3330
3331     # We calculate some guesswork now about what kind of tree this might
3332     # be.  This is mostly for error reporting.
3333
3334     my %editedignores;
3335     my $diffbits = {
3336         # H = user's HEAD
3337         # O = orig, without patches applied
3338         # A = "applied", ie orig with H's debian/patches applied
3339         H2O => quiltify_trees_differ($headref,  $unapplied, 1,\%editedignores),
3340         H2A => quiltify_trees_differ($headref,  $oldtiptree,1),
3341         O2A => quiltify_trees_differ($unapplied,$oldtiptree,1),
3342     };
3343
3344     my @dl;
3345     foreach my $b (qw(01 02)) {
3346         foreach my $v (qw(H2O O2A H2A)) {
3347             push @dl, ($diffbits->{$v} & $b) ? '##' : '==';
3348         }
3349     }
3350     printdebug "differences \@dl @dl.\n";
3351
3352     progress sprintf
3353 "$us: quilt differences: src:  %s orig %s     gitignores:  %s orig %s\n".
3354 "$us: quilt differences:      HEAD %s o+d/p               HEAD %s o+d/p",
3355                              $dl[0], $dl[1],              $dl[3], $dl[4],
3356                                  $dl[2],                     $dl[5];
3357
3358     my @failsuggestion;
3359     if (!($diffbits->{H2O} & $diffbits->{O2A})) {
3360         push @failsuggestion, "This might be a patches-unapplied branch.";
3361     }  elsif (!($diffbits->{H2A} & $diffbits->{O2A})) {
3362         push @failsuggestion, "This might be a patches-applied branch.";
3363     }
3364     push @failsuggestion, "Maybe you need to specify one of".
3365         " --quilt=gbp --quilt=dpm --quilt=unapplied ?";
3366
3367     if (quiltmode_splitbrain()) {
3368         quiltify_splitbrain($clogp, $unapplied, $headref,
3369                             $diffbits, \%editedignores,
3370                             $splitbrain_cachekey);
3371         return;
3372     }
3373
3374     progress "starting quiltify (multiple patches, $quilt_mode mode)";
3375     quiltify($clogp,$headref,$oldtiptree,\@failsuggestion);
3376
3377     if (!open P, '>>', ".pc/applied-patches") {
3378         $!==&ENOENT or die $!;
3379     } else {
3380         close P;
3381     }
3382
3383     commit_quilty_patch();
3384
3385     if ($mustdeletepc) {
3386         quilt_fixup_delete_pc();
3387     }
3388 }
3389
3390 sub quilt_fixup_editor () {
3391     my $descfn = $ENV{$fakeeditorenv};
3392     my $editing = $ARGV[$#ARGV];
3393     open I1, '<', $descfn or die "$descfn: $!";
3394     open I2, '<', $editing or die "$editing: $!";
3395     unlink $editing or die "$editing: $!";
3396     open O, '>', $editing or die "$editing: $!";
3397     while (<I1>) { print O or die $!; } I1->error and die $!;
3398     my $copying = 0;
3399     while (<I2>) {
3400         $copying ||= m/^\-\-\- /;
3401         next unless $copying;
3402         print O or die $!;
3403     }
3404     I2->error and die $!;
3405     close O or die $1;
3406     exit 0;
3407 }
3408
3409 sub maybe_apply_patches_dirtily () {
3410     return unless $quilt_mode =~ m/gbp|unapplied/;
3411     print STDERR <<END or die $!;
3412
3413 dgit: Building, or cleaning with rules target, in patches-unapplied tree.
3414 dgit: Have to apply the patches - making the tree dirty.
3415 dgit: (Consider specifying --clean=git and (or) using dgit sbuild.)
3416
3417 END
3418     $patches_applied_dirtily = 01;
3419     $patches_applied_dirtily |= 02 unless stat_exists '.pc';
3420     runcmd qw(dpkg-source --before-build .);
3421 }
3422
3423 sub maybe_unapply_patches_again () {
3424     progress "dgit: Unapplying patches again to tidy up the tree."
3425         if $patches_applied_dirtily;
3426     runcmd qw(dpkg-source --after-build .)
3427         if $patches_applied_dirtily & 01;
3428     rmtree '.pc'
3429         if $patches_applied_dirtily & 02;
3430 }
3431
3432 #----- other building -----
3433
3434 our $clean_using_builder;
3435 # ^ tree is to be cleaned by dpkg-source's builtin idea that it should
3436 #   clean the tree before building (perhaps invoked indirectly by
3437 #   whatever we are using to run the build), rather than separately
3438 #   and explicitly by us.
3439
3440 sub clean_tree () {
3441     return if $clean_using_builder;
3442     if ($cleanmode eq 'dpkg-source') {
3443         maybe_apply_patches_dirtily();
3444         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
3445     } elsif ($cleanmode eq 'dpkg-source-d') {
3446         maybe_apply_patches_dirtily();
3447         runcmd_ordryrun_local @dpkgbuildpackage, qw(-d -T clean);
3448     } elsif ($cleanmode eq 'git') {
3449         runcmd_ordryrun_local @git, qw(clean -xdf);
3450     } elsif ($cleanmode eq 'git-ff') {
3451         runcmd_ordryrun_local @git, qw(clean -xdff);
3452     } elsif ($cleanmode eq 'check') {
3453         my $leftovers = cmdoutput @git, qw(clean -xdn);
3454         if (length $leftovers) {
3455             print STDERR $leftovers, "\n" or die $!;
3456             fail "tree contains uncommitted files and --clean=check specified";
3457         }
3458     } elsif ($cleanmode eq 'none') {
3459     } else {
3460         die "$cleanmode ?";
3461     }
3462 }
3463
3464 sub cmd_clean () {
3465     badusage "clean takes no additional arguments" if @ARGV;
3466     notpushing();
3467     clean_tree();
3468     maybe_unapply_patches_again();
3469 }
3470
3471 sub build_prep () {
3472     notpushing();
3473     badusage "-p is not allowed when building" if defined $package;
3474     check_not_dirty();
3475     clean_tree();
3476     my $clogp = parsechangelog();
3477     $isuite = getfield $clogp, 'Distribution';
3478     $package = getfield $clogp, 'Source';
3479     $version = getfield $clogp, 'Version';
3480     build_maybe_quilt_fixup();
3481     if ($rmchanges) {
3482         my $pat = changespat $version;
3483         foreach my $f (glob "$buildproductsdir/$pat") {
3484             if (act_local()) {
3485                 unlink $f or fail "remove old changes file $f: $!";
3486             } else {
3487                 progress "would remove $f";
3488             }
3489         }
3490     }
3491 }
3492
3493 sub changesopts_initial () {
3494     my @opts =@changesopts[1..$#changesopts];
3495 }
3496
3497 sub changesopts_version () {
3498     if (!defined $changes_since_version) {
3499         my @vsns = archive_query('archive_query');
3500         my @quirk = access_quirk();
3501         if ($quirk[0] eq 'backports') {
3502             local $isuite = $quirk[2];
3503             local $csuite;
3504             canonicalise_suite();
3505             push @vsns, archive_query('archive_query');
3506         }
3507         if (@vsns) {
3508             @vsns = map { $_->[0] } @vsns;
3509             @vsns = sort { -version_compare($a, $b) } @vsns;
3510             $changes_since_version = $vsns[0];
3511             progress "changelog will contain changes since $vsns[0]";
3512         } else {
3513             $changes_since_version = '_';
3514             progress "package seems new, not specifying -v<version>";
3515         }
3516     }
3517     if ($changes_since_version ne '_') {
3518         return ("-v$changes_since_version");
3519     } else {
3520         return ();
3521     }
3522 }
3523
3524 sub changesopts () {
3525     return (changesopts_initial(), changesopts_version());
3526 }
3527
3528 sub massage_dbp_args ($;$) {
3529     my ($cmd,$xargs) = @_;
3530     # We need to:
3531     #
3532     #  - if we're going to split the source build out so we can
3533     #    do strange things to it, massage the arguments to dpkg-buildpackage
3534     #    so that the main build doessn't build source (or add an argument
3535     #    to stop it building source by default).
3536     #
3537     #  - add -nc to stop dpkg-source cleaning the source tree,
3538     #    unless we're not doing a split build and want dpkg-source
3539     #    as cleanmode, in which case we can do nothing
3540     #
3541     # return values:
3542     #    0 - source will NOT need to be built separately by caller
3543     #   +1 - source will need to be built separately by caller
3544     #   +2 - source will need to be built separately by caller AND
3545     #        dpkg-buildpackage should not in fact be run at all!
3546     debugcmd '#massaging#', @$cmd if $debuglevel>1;
3547 #print STDERR "MASS0 ",Dumper($cmd, $xargs, $need_split_build_invocation);
3548     if ($cleanmode eq 'dpkg-source' && !$need_split_build_invocation) {
3549         $clean_using_builder = 1;
3550         return 0;
3551     }
3552     # -nc has the side effect of specifying -b if nothing else specified
3553     # and some combinations of -S, -b, et al, are errors, rather than
3554     # later simply overriding earlie.  So we need to:
3555     #  - search the command line for these options
3556     #  - pick the last one
3557     #  - perhaps add our own as a default
3558     #  - perhaps adjust it to the corresponding non-source-building version
3559     my $dmode = '-F';
3560     foreach my $l ($cmd, $xargs) {
3561         next unless $l;
3562         @$l = grep { !(m/^-[SgGFABb]$/s and $dmode=$_) } @$l;
3563     }
3564     push @$cmd, '-nc';
3565 #print STDERR "MASS1 ",Dumper($cmd, $xargs, $dmode);
3566     my $r = 0;
3567     if ($need_split_build_invocation) {
3568         printdebug "massage split $dmode.\n";
3569         $r = $dmode =~ m/[S]/     ? +2 :
3570              $dmode =~ y/gGF/ABb/ ? +1 :
3571              $dmode =~ m/[ABb]/   ?  0 :
3572              die "$dmode ?";
3573     }
3574     printdebug "massage done $r $dmode.\n";
3575     push @$cmd, $dmode;
3576 #print STDERR "MASS2 ",Dumper($cmd, $xargs, $r);
3577     return $r;
3578 }
3579
3580 sub cmd_build {
3581     my @dbp = (@dpkgbuildpackage, qw(-us -uc), changesopts_initial(), @ARGV);
3582     my $wantsrc = massage_dbp_args \@dbp;
3583     if ($wantsrc > 0) {
3584         build_source();
3585     } else {
3586         build_prep();
3587     }
3588     if ($wantsrc < 2) {
3589         push @dbp, changesopts_version();
3590         maybe_apply_patches_dirtily();
3591         runcmd_ordryrun_local @dbp;
3592     }
3593     maybe_unapply_patches_again();
3594     printdone "build successful\n";
3595 }
3596
3597 sub cmd_gbp_build {
3598     my @dbp = @dpkgbuildpackage;
3599
3600     my $wantsrc = massage_dbp_args \@dbp, \@ARGV;
3601
3602     my @cmd;
3603     if (length executable_on_path('git-buildpackage')) {
3604         @cmd = qw(git-buildpackage);
3605     } else {
3606         @cmd = qw(gbp buildpackage);
3607     }
3608     push @cmd, (qw(-us -uc --git-no-sign-tags), "--git-builder=@dbp");
3609
3610     if ($wantsrc > 0) {
3611         build_source();
3612     } else {
3613         if (!$clean_using_builder) {
3614             push @cmd, '--git-cleaner=true';
3615         }
3616         build_prep();
3617     }
3618     if ($wantsrc < 2) {
3619         unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
3620             canonicalise_suite();
3621             push @cmd, "--git-debian-branch=".lbranch();
3622         }
3623         push @cmd, changesopts();
3624         maybe_apply_patches_dirtily();
3625         runcmd_ordryrun_local @cmd, @ARGV;
3626     }
3627     maybe_unapply_patches_again();
3628     printdone "build successful\n";
3629 }
3630 sub cmd_git_build { cmd_gbp_build(); } # compatibility with <= 1.0
3631
3632 sub build_source {
3633     my $our_cleanmode = $cleanmode;
3634     if ($need_split_build_invocation) {
3635         # Pretend that clean is being done some other way.  This
3636         # forces us not to try to use dpkg-buildpackage to clean and
3637         # build source all in one go; and instead we run dpkg-source
3638         # (and build_prep() will do the clean since $clean_using_builder
3639         # is false).
3640         $our_cleanmode = 'ELSEWHERE';
3641     }
3642     if ($our_cleanmode =~ m/^dpkg-source/) {
3643         # dpkg-source invocation (below) will clean, so build_prep shouldn't
3644         $clean_using_builder = 1;
3645     }
3646     build_prep();
3647     $sourcechanges = changespat $version,'source';
3648     if (act_local()) {
3649         unlink "../$sourcechanges" or $!==ENOENT
3650             or fail "remove $sourcechanges: $!";
3651     }
3652     $dscfn = dscfn($version);
3653     if ($our_cleanmode eq 'dpkg-source') {
3654         maybe_apply_patches_dirtily();
3655         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S),
3656             changesopts();
3657     } elsif ($our_cleanmode eq 'dpkg-source-d') {
3658         maybe_apply_patches_dirtily();
3659         runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc -S -d),
3660             changesopts();
3661     } else {
3662         my @cmd = (@dpkgsource, qw(-b --));
3663         if ($split_brain) {
3664             changedir $ud;
3665             runcmd_ordryrun_local @cmd, "work";
3666             my @udfiles = <${package}_*>;
3667             changedir "../../..";
3668             foreach my $f (@udfiles) {
3669                 printdebug "source copy, found $f\n";
3670                 next unless
3671                     $f eq $dscfn or
3672                     ($f =~ m/\.debian\.tar(?:\.\w+)$/ &&
3673                      $f eq srcfn($version, $&));
3674                 printdebug "source copy, found $f - renaming\n";
3675                 rename "$ud/$f", "../$f" or $!==ENOENT
3676                     or fail "put in place new source file ($f): $!";
3677             }
3678         } else {
3679             my $pwd = must_getcwd();
3680             my $leafdir = basename $pwd;
3681             changedir "..";
3682             runcmd_ordryrun_local @cmd, $leafdir;
3683             changedir $pwd;
3684         }
3685         runcmd_ordryrun_local qw(sh -ec),
3686             'exec >$1; shift; exec "$@"','x',
3687             "../$sourcechanges",
3688             @dpkggenchanges, qw(-S), changesopts();
3689     }
3690 }
3691
3692 sub cmd_build_source {
3693     badusage "build-source takes no additional arguments" if @ARGV;
3694     build_source();
3695     maybe_unapply_patches_again();
3696     printdone "source built, results in $dscfn and $sourcechanges";
3697 }
3698
3699 sub cmd_sbuild {
3700     build_source();
3701     my $pat = changespat $version;
3702     if (!$rmchanges) {
3703         my @unwanted = map { s#^\.\./##; $_; } glob "../$pat";
3704         @unwanted = grep { $_ ne changespat $version,'source' } @unwanted;
3705         fail "changes files other than source matching $pat".
3706             " already present (@unwanted);".
3707             " building would result in ambiguity about the intended results"
3708             if @unwanted;
3709     }
3710     changedir "..";
3711     if (act_local()) {
3712         stat_exists $dscfn or fail "$dscfn (in parent directory): $!";
3713         stat_exists $sourcechanges
3714             or fail "$sourcechanges (in parent directory): $!";
3715     }
3716     runcmd_ordryrun_local @sbuild, qw(-d), $isuite, @ARGV, $dscfn;
3717     my @changesfiles = glob $pat;
3718     @changesfiles = sort {
3719         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
3720             or $a cmp $b
3721     } @changesfiles;
3722     fail "wrong number of different changes files (@changesfiles)"
3723         unless @changesfiles==2;
3724     my $binchanges = parsecontrol($changesfiles[1], "binary changes file");
3725     foreach my $l (split /\n/, getfield $binchanges, 'Files') {
3726         fail "$l found in binaries changes file $binchanges"
3727             if $l =~ m/\.dsc$/;
3728     }
3729     runcmd_ordryrun_local @mergechanges, @changesfiles;
3730     my $multichanges = changespat $version,'multi';
3731     if (act_local()) {
3732         stat_exists $multichanges or fail "$multichanges: $!";
3733         foreach my $cf (glob $pat) {
3734             next if $cf eq $multichanges;
3735             rename "$cf", "$cf.inmulti" or fail "$cf\{,.inmulti}: $!";
3736         }
3737     }
3738     maybe_unapply_patches_again();
3739     printdone "build successful, results in $multichanges\n" or die $!;
3740 }    
3741
3742 sub cmd_quilt_fixup {
3743     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
3744     my $clogp = parsechangelog();
3745     $version = getfield $clogp, 'Version';
3746     $package = getfield $clogp, 'Source';
3747     check_not_dirty();
3748     clean_tree();
3749     build_maybe_quilt_fixup();
3750 }
3751
3752 sub cmd_archive_api_query {
3753     badusage "need only 1 subpath argument" unless @ARGV==1;
3754     my ($subpath) = @ARGV;
3755     my @cmd = archive_api_query_cmd($subpath);
3756     debugcmd ">",@cmd;
3757     exec @cmd or fail "exec curl: $!\n";
3758 }
3759
3760 sub cmd_clone_dgit_repos_server {
3761     badusage "need destination argument" unless @ARGV==1;
3762     my ($destdir) = @ARGV;
3763     $package = '_dgit-repos-server';
3764     my @cmd = (@git, qw(clone), access_giturl(), $destdir);
3765     debugcmd ">",@cmd;
3766     exec @cmd or fail "exec git clone: $!\n";
3767 }
3768
3769 sub cmd_setup_mergechangelogs {
3770     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3771     setup_mergechangelogs(1);
3772 }
3773
3774 sub cmd_setup_useremail {
3775     badusage "no arguments allowed to dgit setup-mergechangelogs" if @ARGV;
3776     setup_useremail(1);
3777 }
3778
3779 sub cmd_setup_new_tree {
3780     badusage "no arguments allowed to dgit setup-tree" if @ARGV;
3781     setup_new_tree();
3782 }
3783
3784 #---------- argument parsing and main program ----------
3785
3786 sub cmd_version {
3787     print "dgit version $our_version\n" or die $!;
3788     exit 0;
3789 }
3790
3791 our (%valopts_long, %valopts_short);
3792 our @rvalopts;
3793
3794 sub defvalopt ($$$$) {
3795     my ($long,$short,$val_re,$how) = @_;
3796     my $oi = { Long => $long, Short => $short, Re => $val_re, How => $how };
3797     $valopts_long{$long} = $oi;
3798     $valopts_short{$short} = $oi;
3799     # $how subref should:
3800     #   do whatever assignemnt or thing it likes with $_[0]
3801     #   if the option should not be passed on to remote, @rvalopts=()
3802     # or $how can be a scalar ref, meaning simply assign the value
3803 }
3804
3805 defvalopt '--since-version', '-v', '[^_]+|_', \$changes_since_version;
3806 defvalopt '--distro',        '-d', '.+',      \$idistro;
3807 defvalopt '',                '-k', '.+',      \$keyid;
3808 defvalopt '--existing-package','', '.*',      \$existing_package;
3809 defvalopt '--build-products-dir','','.*',     \$buildproductsdir;
3810 defvalopt '--clean',       '', $cleanmode_re, \$cleanmode;
3811 defvalopt '--quilt',     '', $quilt_modes_re, \$quilt_mode;
3812
3813 defvalopt '', '-c', '.*=.*', sub { push @git, '-c', @_; };
3814
3815 defvalopt '', '-C', '.+', sub {
3816     ($changesfile) = (@_);
3817     if ($changesfile =~ s#^(.*)/##) {
3818         $buildproductsdir = $1;
3819     }
3820 };
3821
3822 defvalopt '--initiator-tempdir','','.*', sub {
3823     ($initiator_tempdir) = (@_);
3824     $initiator_tempdir =~ m#^/# or
3825         badusage "--initiator-tempdir must be used specify an".
3826         " absolute, not relative, directory."
3827 };
3828
3829 sub parseopts () {
3830     my $om;
3831
3832     if (defined $ENV{'DGIT_SSH'}) {
3833         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
3834     } elsif (defined $ENV{'GIT_SSH'}) {
3835         @ssh = ($ENV{'GIT_SSH'});
3836     }
3837
3838     my $oi;
3839     my $val;
3840     my $valopt = sub {
3841         my ($what) = @_;
3842         @rvalopts = ($_);
3843         if (!defined $val) {
3844             badusage "$what needs a value" unless @ARGV;
3845             $val = shift @ARGV;
3846             push @rvalopts, $val;
3847         }
3848         badusage "bad value \`$val' for $what" unless
3849             $val =~ m/^$oi->{Re}$(?!\n)/s;
3850         my $how = $oi->{How};
3851         if (ref($how) eq 'SCALAR') {
3852             $$how = $val;
3853         } else {
3854             $how->($val);
3855         }
3856         push @ropts, @rvalopts;
3857     };
3858
3859     while (@ARGV) {
3860         last unless $ARGV[0] =~ m/^-/;
3861         $_ = shift @ARGV;
3862         last if m/^--?$/;
3863         if (m/^--/) {
3864             if (m/^--dry-run$/) {
3865                 push @ropts, $_;
3866                 $dryrun_level=2;
3867             } elsif (m/^--damp-run$/) {
3868                 push @ropts, $_;
3869                 $dryrun_level=1;
3870             } elsif (m/^--no-sign$/) {
3871                 push @ropts, $_;
3872                 $sign=0;
3873             } elsif (m/^--help$/) {
3874                 cmd_help();
3875             } elsif (m/^--version$/) {
3876                 cmd_version();
3877             } elsif (m/^--new$/) {
3878                 push @ropts, $_;
3879                 $new_package=1;
3880             } elsif (m/^--([-0-9a-z]+)=(.+)/s &&
3881                      ($om = $opts_opt_map{$1}) &&
3882                      length $om->[0]) {
3883                 push @ropts, $_;
3884                 $om->[0] = $2;
3885             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
3886                      !$opts_opt_cmdonly{$1} &&
3887                      ($om = $opts_opt_map{$1})) {
3888                 push @ropts, $_;
3889                 push @$om, $2;
3890             } elsif (m/^--ignore-dirty$/s) {
3891                 push @ropts, $_;
3892                 $ignoredirty = 1;
3893             } elsif (m/^--no-quilt-fixup$/s) {
3894                 push @ropts, $_;
3895                 $quilt_mode = 'nocheck';
3896             } elsif (m/^--no-rm-on-error$/s) {
3897                 push @ropts, $_;
3898                 $rmonerror = 0;
3899             } elsif (m/^--(no-)?rm-old-changes$/s) {
3900                 push @ropts, $_;
3901                 $rmchanges = !$1;
3902             } elsif (m/^--deliberately-($deliberately_re)$/s) {
3903                 push @ropts, $_;
3904                 push @deliberatelies, $&;
3905             } elsif (m/^--dgit-tag-format=(old|new)$/s) {
3906                 # undocumented, for testing
3907                 push @ropts, $_;
3908                 $tagformat_want = [ $1, 'command line', 1 ];
3909                 # 1 menas overrides distro configuration
3910             } elsif (m/^--always-split-source-build$/s) {
3911                 # undocumented, for testing
3912                 push @ropts, $_;
3913                 $need_split_build_invocation = 1;
3914             } elsif (m/^(--[-0-9a-z]+)(=|$)/ && ($oi = $valopts_long{$1})) {
3915                 $val = $2 ? $' : undef; #';
3916                 $valopt->($oi->{Long});
3917             } else {
3918                 badusage "unknown long option \`$_'";
3919             }
3920         } else {
3921             while (m/^-./s) {
3922                 if (s/^-n/-/) {
3923                     push @ropts, $&;
3924                     $dryrun_level=2;
3925                 } elsif (s/^-L/-/) {
3926                     push @ropts, $&;
3927                     $dryrun_level=1;
3928                 } elsif (s/^-h/-/) {
3929                     cmd_help();
3930                 } elsif (s/^-D/-/) {
3931                     push @ropts, $&;
3932                     $debuglevel++;
3933                     enabledebug();
3934                 } elsif (s/^-N/-/) {
3935                     push @ropts, $&;
3936                     $new_package=1;
3937                 } elsif (m/^-m/) {
3938                     push @ropts, $&;
3939                     push @changesopts, $_;
3940                     $_ = '';
3941                 } elsif (s/^-wn$//s) {
3942                     push @ropts, $&;
3943                     $cleanmode = 'none';
3944                 } elsif (s/^-wg$//s) {
3945                     push @ropts, $&;
3946                     $cleanmode = 'git';
3947                 } elsif (s/^-wgf$//s) {
3948                     push @ropts, $&;
3949                     $cleanmode = 'git-ff';
3950                 } elsif (s/^-wd$//s) {
3951                     push @ropts, $&;
3952                     $cleanmode = 'dpkg-source';
3953                 } elsif (s/^-wdd$//s) {
3954                     push @ropts, $&;
3955                     $cleanmode = 'dpkg-source-d';
3956                 } elsif (s/^-wc$//s) {
3957                     push @ropts, $&;
3958                     $cleanmode = 'check';
3959                 } elsif (m/^-[a-zA-Z]/ && ($oi = $valopts_short{$&})) {
3960                     $val = $'; #';
3961                     $val = undef unless length $val;
3962                     $valopt->($oi->{Short});
3963                     $_ = '';
3964                 } else {
3965                     badusage "unknown short option \`$_'";
3966                 }
3967             }
3968         }
3969     }
3970 }
3971
3972 sub finalise_opts_opts () {
3973     foreach my $k (keys %opts_opt_map) {
3974         my $om = $opts_opt_map{$k};
3975
3976         my $v = access_cfg("cmd-$k", 'RETURN-UNDEF');
3977         if (defined $v) {
3978             badcfg "cannot set command for $k"
3979                 unless length $om->[0];
3980             $om->[0] = $v;
3981         }
3982
3983         foreach my $c (access_cfg_cfgs("opts-$k")) {
3984             my $vl = $gitcfg{$c};
3985             printdebug "CL $c ",
3986                 ($vl ? join " ", map { shellquote } @$vl : ""),
3987                 "\n" if $debuglevel >= 4;
3988             next unless $vl;
3989             badcfg "cannot configure options for $k"
3990                 if $opts_opt_cmdonly{$k};
3991             my $insertpos = $opts_cfg_insertpos{$k};
3992             @$om = ( @$om[0..$insertpos-1],
3993                      @$vl,
3994                      @$om[$insertpos..$#$om] );
3995         }
3996     }
3997 }
3998
3999 if ($ENV{$fakeeditorenv}) {
4000     git_slurp_config();
4001     quilt_fixup_editor();
4002 }
4003
4004 parseopts();
4005 git_slurp_config();
4006
4007 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
4008 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
4009     if $dryrun_level == 1;
4010 if (!@ARGV) {
4011     print STDERR $helpmsg or die $!;
4012     exit 8;
4013 }
4014 my $cmd = shift @ARGV;
4015 $cmd =~ y/-/_/;
4016
4017 if (!defined $rmchanges) {
4018     local $access_forpush;
4019     $rmchanges = access_cfg_bool(0, 'rm-old-changes');
4020 }
4021
4022 if (!defined $quilt_mode) {
4023     local $access_forpush;
4024     $quilt_mode = cfg('dgit.force.quilt-mode', 'RETURN-UNDEF')
4025         // access_cfg('quilt-mode', 'RETURN-UNDEF')
4026         // 'linear';
4027     $quilt_mode =~ m/^($quilt_modes_re)$/ 
4028         or badcfg "unknown quilt-mode \`$quilt_mode'";
4029     $quilt_mode = $1;
4030 }
4031
4032 $need_split_build_invocation ||= quiltmode_splitbrain();
4033
4034 if (!defined $cleanmode) {
4035     local $access_forpush;
4036     $cleanmode = access_cfg('clean-mode', 'RETURN-UNDEF');
4037     $cleanmode //= 'dpkg-source';
4038
4039     badcfg "unknown clean-mode \`$cleanmode'" unless
4040         $cleanmode =~ m/^($cleanmode_re)$(?!\n)/s;
4041 }
4042
4043 my $fn = ${*::}{"cmd_$cmd"};
4044 $fn or badusage "unknown operation $cmd";
4045 $fn->();