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