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