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