chiark / gitweb /
fixes for remote mode
[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
33 our $our_version = 'UNRELEASED'; ###substituted###
34
35 our $isuite = 'unstable';
36 our $idistro;
37 our $package;
38 our @ropts;
39
40 our $sign = 1;
41 our $dryrun = 0;
42 our $changesfile;
43 our $new_package = 0;
44 our $ignoredirty = 0;
45 our $noquilt = 0;
46 our $existing_package = 'dpkg';
47 our $cleanmode = 'dpkg-source';
48 our $we_are_responder;
49
50 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
51
52 our (@git) = qw(git);
53 our (@dget) = qw(dget);
54 our (@dput) = qw(dput);
55 our (@debsign) = qw(debsign);
56 our (@gpg) = qw(gpg);
57 our (@sbuild) = qw(sbuild -A);
58 our (@ssh) = 'ssh';
59 our (@dgit) = qw(dgit);
60 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
61 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
62 our (@dpkggenchanges) = qw(dpkg-genchanges);
63 our (@mergechanges) = qw(mergechanges -f);
64 our (@changesopts) = ('');
65
66 our %opts_opt_map = ('dget' => \@dget,
67                      'dput' => \@dput,
68                      'debsign' => \@debsign,
69                      'gpg' => \@gpg,
70                      'sbuild' => \@sbuild,
71                      'ssh' => \@ssh,
72                      'dgit' => \@dgit,
73                      'dpkg-source' => \@dpkgsource,
74                      'dpkg-buildpackage' => \@dpkgbuildpackage,
75                      'dpkg-genchanges' => \@dpkggenchanges,
76                      'ch' => \@changesopts,
77                      'mergechanges' => \@mergechanges);
78
79 our %opts_opt_cmdonly = ('gpg' => 1);
80
81 our $keyid;
82
83 our $debug = 0;
84 open DEBUG, ">/dev/null" or die $!;
85
86 our $remotename = 'dgit';
87 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
88 our $branchprefix = 'dgit';
89 our $csuite;
90
91 sub lbranch () { return "$branchprefix/$csuite"; }
92 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
93 sub lref () { return "refs/heads/".lbranch(); }
94 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
95 sub rrref () { return "refs/$branchprefix/$csuite"; }
96 sub debiantag ($) { 
97     my ($v) = @_;
98     $v =~ y/~:/_%/;
99     return "debian/$v";
100 }
101
102 sub stripepoch ($) {
103     my ($vsn) = @_;
104     $vsn =~ s/^\d+\://;
105     return $vsn;
106 }
107
108 sub dscfn ($) {
109     my ($vsn) = @_;
110     return "${package}_".(stripepoch $vsn).".dsc";
111 }
112
113 sub changesopts () { return @changesopts[1..$#changesopts]; }
114
115 our $us = 'dgit';
116
117 sub fail { die "$us: @_\n"; }
118
119 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
120
121 sub no_such_package () {
122     print STDERR "$us: package $package does not exist in suite $isuite\n";
123     exit 4;
124 }
125
126 sub fetchspec () {
127     local $csuite = '*';
128     return  "+".rrref().":".lrref();
129 }
130
131 #---------- remote protocol support, common ----------
132
133 # remote push initiator/responder protocol:
134 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
135 #
136 #  > file parsed-changelog
137 #  [indicates that output of dpkg-parsechangelog follows]
138 #  > data-block NBYTES
139 #  > [NBYTES bytes of data (no newline)]
140 #  [maybe some more blocks]
141 #  > data-end
142 #
143 #  > file dsc
144 #  [etc]
145 #
146 #  > file changes
147 #  [etc]
148 #
149 #  > param head HEAD
150 #
151 #  > want signed-tag
152 #  [indicates that signed tag is wanted]
153 #  < data-block NBYTES
154 #  < [NBYTES bytes of data (no newline)]
155 #  [maybe some more blocks]
156 #  < data-end
157 #  < files-end
158 #
159 #  > want signed-dsc-changes
160 #  < data-block NBYTES    [transfer of signed dsc]
161 #  [etc]
162 #  < data-block NBYTES    [transfer of signed changes]
163 #  [etc]
164 #  < files-end
165 #
166 #  > complete
167
168 sub badproto ($$) {
169     my ($fh, $m) = @_;
170     fail "connection lost: $!" if $fh->error;
171     fail "connection terminated" if $fh->eof;
172     fail "protocol violation; $m not expected";
173 }
174
175 sub protocol_expect (&$) {
176     my ($match, $fh) = @_;
177     local $_;
178     $_ = <$fh>;
179     defined && chomp or badproto $fh, "eof";
180     if (wantarray) {
181         my @r = &$match;
182         return @r if @r;
183     } else {
184         my $r = &$match;
185         return $r if $r;
186     }
187     badproto $fh, "\`$_'";
188 }
189
190 sub protocol_send_file ($$) {
191     my ($fh, $ourfn) = @_;
192     open PF, "<", $ourfn or die "$ourfn: $!";
193     for (;;) {
194         my $d;
195         my $got = read PF, $d, 65536;
196         die "$ourfn: $!" unless defined $got;
197         last if $got;
198         print $fh "data-block ".length($d)."\n" or die $!;
199         print $d or die $!;
200     }
201     print $fh "data-end\n" or die $!;
202     close PF;
203 }
204
205 sub protocol_read_bytes ($$) {
206     my ($fh, $nbytes) = @_;
207     $nbytes =~ m/^\d{1,6}$/ or badproto \*RO, "bad byte count";
208     my $d;
209     my $got = read $fh, $d, $nbytes;
210     $got==$nbytes or badproto $fh, "eof during data block";
211     return $d;
212 }
213
214 sub protocol_receive_file ($$) {
215     my ($fh, $ourfn) = @_;
216     open PF, ">", $ourfn or die "$ourfn: $!";
217     for (;;) {
218         my ($y,$l) = protocol_expect {
219             m/^data-block (.*})$|data-end$/;
220             length $1 ? (1,$1) : (0);
221         } \*STDIN;
222         last unless $y;
223         my $d = protocol_read_bytes \*STDIN, $1;
224         print PF $d or die $!;
225     }
226 }
227
228 #---------- remote protocol support, responder ----------
229
230 sub responder_send_command ($) {
231     my ($command) = @_;
232     return unless $we_are_responder;
233     # called even without $we_are_responder
234     print DEBUG "<< $command\n";
235     print $command, "\n" or die $!;
236 }    
237
238 sub responder_send_file ($$) {
239     my ($keyword, $ourfn) = @_;
240     return unless $we_are_responder;
241     responder_send_command "file $keyword";
242     protocol_send_file \*STDOUT, $ourfn;
243 }
244
245 sub responder_receive_files ($@) {
246     my ($keyword, @ourfns) = @_;
247     die unless $we_are_responder;
248     responder_send_command "want $keyword";
249     foreach my $fn (@ourfns) {
250         protocol_receive_file \*STDIN, $fn;
251     }
252     protocol_expect { m/^files-end$/ } \*STDIN;
253 }
254
255 #---------- remote protocol support, initiator ----------
256
257 sub initiator_expect (&) {
258     my ($match) = @_;
259     protocol_expect { &$match } \*RO;
260 }
261
262 #---------- end remote code ----------
263
264 sub progress {
265     if ($we_are_responder) {
266         my $m = join '', @_;
267         responder_send_command "progress ".length($m) or die $!;
268         print $m or die $!;
269     } else {
270         print @_, "\n";
271     }
272 }
273
274 our $ua;
275
276 sub url_get {
277     if (!$ua) {
278         $ua = LWP::UserAgent->new();
279         $ua->env_proxy;
280     }
281     my $what = $_[$#_];
282     progress "downloading $what...";
283     my $r = $ua->get(@_) or die $!;
284     return undef if $r->code == 404;
285     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
286     return $r->decoded_content();
287 }
288
289 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
290
291 sub shellquote {
292     my @out;
293     local $_;
294     foreach my $a (@_) {
295         $_ = $a;
296         if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
297             push @out, "'$_'";
298         } else {
299             push @out, $_;
300         }
301     }
302     return join ' ', @out;
303 }
304
305 sub printcmd {
306     my $fh = shift @_;
307     my $intro = shift @_;
308     print $fh $intro," " or die $!;
309     print $fh shellquote @_ or die $!;
310     print $fh "\n" or die $!;
311 }
312
313 sub failedcmd {
314     { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
315     if ($!) {
316         fail "failed to fork/exec: $!";
317     } elsif (!($? & 0xff)) {
318         fail "subprocess failed with error exit status ".($?>>8);
319     } elsif ($?) {
320         fail "subprocess crashed (wait status $?)";
321     } else {
322         fail "subprocess produced invalid output";
323     }
324 }
325
326 sub runcmd {
327     printcmd(\*DEBUG,"+",@_) if $debug>0;
328     $!=0; $?=0;
329     failedcmd @_ if system @_;
330 }
331
332 sub printdone {
333     if (!$dryrun) {
334         progress "dgit ok: @_";
335     } else {
336         progress "would be ok: @_ (but dry run only)";
337     }
338 }
339
340 sub cmdoutput_errok {
341     die Dumper(\@_)." ?" if grep { !defined } @_;
342     printcmd(\*DEBUG,"|",@_) if $debug>0;
343     open P, "-|", @_ or die $!;
344     my $d;
345     $!=0; $?=0;
346     { local $/ = undef; $d = <P>; }
347     die $! if P->error;
348     if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
349     chomp $d;
350     $d =~ m/^.*/;
351     print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
352     return $d;
353 }
354
355 sub cmdoutput {
356     my $d = cmdoutput_errok @_;
357     defined $d or failedcmd @_;
358     return $d;
359 }
360
361 sub dryrun_report {
362     printcmd(\*STDERR,"#",@_);
363 }
364
365 sub runcmd_ordryrun {
366     if (!$dryrun) {
367         runcmd @_;
368     } else {
369         dryrun_report @_;
370     }
371 }
372
373 sub shell_cmd {
374     my ($first_shell, @cmd) = @_;
375     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
376 }
377
378 our $helpmsg = <<END;
379 main usages:
380   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
381   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
382   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
383   dgit [dgit-opts] push [dgit-opts] [suite]
384   dgit [dgit-opts] rpush build-host:build-dir ...
385 important dgit options:
386   -k<keyid>           sign tag and package with <keyid> instead of default
387   --dry-run -n        do not change anything, but go through the motions
388   --new -N            allow introducing a new package
389   --debug -D          increase debug level
390   -c<name>=<value>    set git config option (used directly by dgit too)
391 END
392
393 our $later_warning_msg = <<END;
394 Perhaps the upload is stuck in incoming.  Using the version from git.
395 END
396
397 sub badusage {
398     print STDERR "$us: @_\n", $helpmsg or die $!;
399     exit 8;
400 }
401
402 sub nextarg {
403     @ARGV or badusage "too few arguments";
404     return scalar shift @ARGV;
405 }
406
407 sub cmd_help () {
408     print $helpmsg or die $!;
409     exit 0;
410 }
411
412 our %defcfg = ('dgit.default.distro' => 'debian',
413                'dgit.default.username' => '',
414                'dgit.default.archive-query-default-component' => 'main',
415                'dgit.default.ssh' => 'ssh',
416                'dgit-distro.debian.git-host' => 'git.debian.org',
417                'dgit-distro.debian.git-proto' => 'git+ssh://',
418                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
419                'dgit-distro.debian.git-check' => 'ssh-cmd',
420                'dgit-distro.debian.git-create' => 'ssh-cmd',
421                'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
422                'dgit-distro.debian.sshdakls-dir' =>
423                    '/srv/ftp-master.debian.org/ftp/dists',
424                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
425                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
426
427 sub cfg {
428     foreach my $c (@_) {
429         return undef if $c =~ /RETURN-UNDEF/;
430         my @cmd = (@git, qw(config --), $c);
431         my $v;
432         {
433             local ($debug) = $debug-1;
434             $v = cmdoutput_errok @cmd;
435         };
436         if ($?==0) {
437             return $v;
438         } elsif ($?!=256) {
439             failedcmd @cmd;
440         }
441         my $dv = $defcfg{$c};
442         return $dv if defined $dv;
443     }
444     badcfg "need value for one of: @_";
445 }
446
447 sub access_distro () {
448     return cfg("dgit-suite.$isuite.distro",
449                "dgit.default.distro");
450 }
451
452 sub access_cfg (@) {
453     my (@keys) = @_;
454     my $distro = $idistro || access_distro();
455     my $value = cfg(map { ("dgit-distro.$distro.$_",
456                            "dgit.default.$_") } @keys);
457     return $value;
458 }
459
460 sub string_to_ssh ($) {
461     my ($spec) = @_;
462     if ($spec =~ m/\s/) {
463         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
464     } else {
465         return ($spec);
466     }
467 }
468
469 sub access_cfg_ssh () {
470     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
471     if (!defined $gitssh) {
472         return @ssh;
473     } else {
474         return string_to_ssh $gitssh;
475     }
476 }
477
478 sub access_someuserhost ($) {
479     my ($some) = @_;
480     my $user = access_cfg("$some-user",'username');
481     my $host = access_cfg("$some-host");
482     return length($user) ? "$user\@$host" : $host;
483 }
484
485 sub access_gituserhost () {
486     return access_someuserhost('git');
487 }
488
489 sub access_giturl () {
490     my $url = access_cfg('git-url','RETURN-UNDEF');
491     if (!defined $url) {
492         $url =
493             access_cfg('git-proto').
494             access_gituserhost().
495             access_cfg('git-path');
496     }
497     return "$url/$package.git";
498 }              
499
500 sub parsecontrolfh ($$@) {
501     my ($fh, $desc, @opts) = @_;
502     my %opts = ('name' => $desc, @opts);
503     my $c = Dpkg::Control::Hash->new(%opts);
504     $c->parse($fh) or die "parsing of $desc failed";
505     return $c;
506 }
507
508 sub parsecontrol {
509     my ($file, $desc) = @_;
510     my $fh = new IO::Handle;
511     open $fh, '<', $file or die "$file: $!";
512     my $c = parsecontrolfh($fh,$desc);
513     $fh->error and die $!;
514     close $fh;
515     return $c;
516 }
517
518 sub getfield ($$) {
519     my ($dctrl,$field) = @_;
520     my $v = $dctrl->{$field};
521     return $v if defined $v;
522     fail "missing field $field in ".$v->get_option('name');
523 }
524
525 sub parsechangelog {
526     my $c = Dpkg::Control::Hash->new();
527     my $p = new IO::Handle;
528     my @cmd = (qw(dpkg-parsechangelog), @_);
529     open $p, '-|', @cmd or die $!;
530     $c->parse($p);
531     $?=0; $!=0; close $p or failedcmd @cmd;
532     return $c;
533 }
534
535 our %rmad;
536
537 sub archive_query ($) {
538     my ($method) = @_;
539     my $query = access_cfg('archive-query','RETURN-UNDEF');
540     if (!defined $query) {
541         my $distro = access_distro();
542         if ($distro eq 'debian') {
543             $query = "sshdakls:".
544                 access_someuserhost('sshdakls').':'.
545                 access_cfg('sshdakls-dir');
546         } else {
547             $query = "madison:$distro";
548         }
549     }
550     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
551     my $proto = $1;
552     my $data = $'; #';
553     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
554 }
555
556 sub archive_query_madison ($$) {
557     my ($proto,$data) = @_;
558     die unless $proto eq 'madison';
559     $rmad{$package} ||= cmdoutput
560         qw(rmadison -asource),"-s$isuite","-u$data",$package;
561     my $rmad = $rmad{$package};
562     return madison_parse($rmad);
563 }
564
565 sub archive_query_sshdakls ($$) {
566     my ($proto,$data) = @_;
567     $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
568     my $dakls = cmdoutput
569         access_cfg_ssh, $data, qw(dak ls -asource),"-s$isuite",$package;
570     return madison_parse($dakls);
571 }
572
573 sub canonicalise_suite_sshdakls ($$) {
574     my ($proto,$data) = @_;
575     $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
576     my @cmd =
577         (access_cfg_ssh, $`,
578          "set -e; cd $';".
579          " if test -h $isuite; then readlink $isuite; exit 0; fi;".
580          " if test -d $isuite; then echo $isuite; exit 0; fi;".
581          " exit 1");
582     my $dakls = cmdoutput @cmd;
583     failedcmd @cmd unless $dakls =~ m/^\w/;
584     return $dakls;
585 }
586
587 sub madison_parse ($) {
588     my ($rmad) = @_;
589     my @out;
590     foreach my $l (split /\n/, $rmad) {
591         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
592                   \s*( [^ \t|]+ )\s* \|
593                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
594                   \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
595         $1 eq $package or die "$rmad $package ?";
596         my $vsn = $2;
597         my $newsuite = $3;
598         my $component;
599         if (defined $4) {
600             $component = $4;
601         } else {
602             $component = access_cfg('archive-query-default-component');
603         }
604         $5 eq 'source' or die "$rmad ?";
605         my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
606         my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
607         push @out, [$vsn,$subpath,$newsuite];
608     }
609     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
610 }
611
612 sub canonicalise_suite_madison ($$) {
613     my @r = archive_query_madison($_[0],$_[1]);
614     @r or fail
615         "unable to canonicalise suite using package $package".
616         " which does not appear to exist in suite $isuite;".
617         " --existing-package may help";
618     return $r[0][2];
619 }
620
621 sub canonicalise_suite () {
622     return if defined $csuite;
623     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
624     $csuite = archive_query('canonicalise_suite');
625     if ($isuite ne $csuite) {
626         # madison canonicalises for us
627         progress "canonical suite name for $isuite is $csuite";
628     }
629 }
630
631 sub get_archive_dsc () {
632     canonicalise_suite();
633     my @vsns = archive_query('archive_query');
634     foreach my $vinfo (@vsns) {
635         my ($vsn,$subpath) = @$vinfo;
636         $dscurl = access_cfg('mirror').$subpath;
637         $dscdata = url_get($dscurl);
638         if (!$dscdata) {
639             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
640             next;
641         }
642         my $dscfh = new IO::File \$dscdata, '<' or die $!;
643         print DEBUG Dumper($dscdata) if $debug>1;
644         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
645         print DEBUG Dumper($dsc) if $debug>1;
646         my $fmt = getfield $dsc, 'Format';
647         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
648         return;
649     }
650     $dsc = undef;
651 }
652
653 sub check_for_git () {
654     # returns 0 or 1
655     my $how = access_cfg('git-check');
656     if ($how eq 'ssh-cmd') {
657         my @cmd =
658             (access_cfg_ssh, access_gituserhost(),
659              " set -e; cd ".access_cfg('git-path').";".
660              " if test -d $package.git; then echo 1; else echo 0; fi");
661         my $r= cmdoutput @cmd;
662         failedcmd @cmd unless $r =~ m/^[01]$/;
663         return $r+0;
664     } else {
665         badcfg "unknown git-check \`$how'";
666     }
667 }
668
669 sub create_remote_git_repo () {
670     my $how = access_cfg('git-create');
671     if ($how eq 'ssh-cmd') {
672         runcmd_ordryrun
673             (access_cfg_ssh, access_gituserhost(),
674              "set -e; cd ".access_cfg('git-path').";".
675              " cp -a _template $package.git");
676     } else {
677         badcfg "unknown git-create \`$how'";
678     }
679 }
680
681 our ($dsc_hash,$lastpush_hash);
682
683 our $ud = '.git/dgit/unpack';
684
685 sub prep_ud () {
686     rmtree($ud);
687     mkpath '.git/dgit';
688     mkdir $ud or die $!;
689 }
690
691 sub mktree_in_ud_from_only_subdir () {
692     # changes into the subdir
693     my (@dirs) = <*/.>;
694     die unless @dirs==1;
695     $dirs[0] =~ m#^([^/]+)/\.$# or die;
696     my $dir = $1;
697     chdir $dir or die "$dir $!";
698     fail "source package contains .git directory" if stat '.git';
699     die $! unless $!==&ENOENT;
700     runcmd qw(git init -q);
701     rmtree('.git/objects');
702     symlink '../../../../objects','.git/objects' or die $!;
703     runcmd @git, qw(add -Af);
704     my $tree = cmdoutput @git, qw(write-tree);
705     $tree =~ m/^\w+$/ or die "$tree ?";
706     return ($tree,$dir);
707 }
708
709 sub dsc_files_info () {
710     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
711                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
712                        ['Files',           'Digest::MD5', 'new()']) {
713         my ($fname, $module, $method) = @$csumi;
714         my $field = $dsc->{$fname};
715         next unless defined $field;
716         eval "use $module; 1;" or die $@;
717         my @out;
718         foreach (split /\n/, $field) {
719             next unless m/\S/;
720             m/^(\w+) (\d+) (\S+)$/ or
721                 fail "could not parse .dsc $fname line \`$_'";
722             my $digester = eval "$module"."->$method;" or die $@;
723             push @out, {
724                 Hash => $1,
725                 Bytes => $2,
726                 Filename => $3,
727                 Digester => $digester,
728             };
729         }
730         return @out;
731     }
732     fail "missing any supported Checksums-* or Files field in ".
733         $dsc->get_option('name');
734 }
735
736 sub dsc_files () {
737     map { $_->{Filename} } dsc_files_info();
738 }
739
740 sub is_orig_file ($) {
741     local ($_) = @_;
742     m/\.orig(?:-\w+)?\.tar\.\w+$/;
743 }
744
745 sub make_commit ($) {
746     my ($file) = @_;
747     return cmdoutput @git, qw(hash-object -w -t commit), $file;
748 }
749
750 sub clogp_authline ($) {
751     my ($clogp) = @_;
752     my $author = getfield $clogp, 'Maintainer';
753     $author =~ s#,.*##ms;
754     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
755     my $authline = "$author $date";
756     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
757         fail "unexpected commit author line format \`$authline'".
758         " (was generated from changelog Maintainer field)";
759     return $authline;
760 }
761
762 sub generate_commit_from_dsc () {
763     prep_ud();
764     chdir $ud or die $!;
765     my @files;
766     foreach my $f (dsc_files()) {
767         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
768         push @files, $f;
769         link "../../../$f", $f
770             or $!==&ENOENT
771             or die "$f $!";
772     }
773     runcmd @dget, qw(--), $dscurl;
774     foreach my $f (grep { is_orig_file($_) } @files) {
775         link $f, "../../../../$f"
776             or $!==&EEXIST
777             or die "$f $!";
778     }
779     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
780     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
781     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
782     my $authline = clogp_authline $clogp;
783     my $changes = getfield $clogp, 'Changes';
784     open C, ">../commit.tmp" or die $!;
785     print C <<END or die $!;
786 tree $tree
787 author $authline
788 committer $authline
789
790 $changes
791
792 # imported from the archive
793 END
794     close C or die $!;
795     my $outputhash = make_commit qw(../commit.tmp);
796     my $cversion = getfield $clogp, 'Version';
797     progress "synthesised git commit from .dsc $cversion";
798     if ($lastpush_hash) {
799         runcmd @git, qw(reset --hard), $lastpush_hash;
800         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
801         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
802         my $oversion = getfield $oldclogp, 'Version';
803         my $vcmp =
804             version_compare_string($oversion, $cversion);
805         if ($vcmp < 0) {
806             # git upload/ is earlier vsn than archive, use archive
807             open C, ">../commit2.tmp" or die $!;
808             print C <<END or die $!;
809 tree $tree
810 parent $lastpush_hash
811 parent $outputhash
812 author $authline
813 committer $authline
814
815 Record $package ($cversion) in archive suite $csuite
816 END
817             $outputhash = make_commit qw(../commit2.tmp);
818         } elsif ($vcmp > 0) {
819             print STDERR <<END or die $!;
820
821 Version actually in archive:    $cversion (older)
822 Last allegedly pushed/uploaded: $oversion (newer or same)
823 $later_warning_msg
824 END
825             $outputhash = $lastpush_hash;
826         } else {
827             $outputhash = $lastpush_hash;
828         }
829     }
830     chdir '../../../..' or die $!;
831     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
832             'DGIT_ARCHIVE', $outputhash;
833     cmdoutput @git, qw(log -n2), $outputhash;
834     # ... gives git a chance to complain if our commit is malformed
835     rmtree($ud);
836     return $outputhash;
837 }
838
839 sub ensure_we_have_orig () {
840     foreach my $fi (dsc_files_info()) {
841         my $f = $fi->{Filename};
842         next unless is_orig_file($f);
843         if (open F, "<", "../$f") {
844             $fi->{Digester}->reset();
845             $fi->{Digester}->addfile(*F);
846             F->error and die $!;
847             my $got = $fi->{Digester}->hexdigest();
848             $got eq $fi->{Hash} or
849                 fail "existing file $f has hash $got but .dsc".
850                     " demands hash $fi->{Hash}".
851                     " (perhaps you should delete this file?)";
852             progress "using existing $f";
853             next;
854         } else {
855             die "$f $!" unless $!==&ENOENT;
856         }
857         my $origurl = $dscurl;
858         $origurl =~ s{/[^/]+$}{};
859         $origurl .= "/$f";
860         die "$f ?" unless $f =~ m/^${package}_/;
861         die "$f ?" if $f =~ m#/#;
862         runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
863     }
864 }
865
866 sub rev_parse ($) {
867     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
868 }
869
870 sub is_fast_fwd ($$) {
871     my ($ancestor,$child) = @_;
872     my @cmd = (@git, qw(merge-base), $ancestor, $child);
873     my $mb = cmdoutput_errok @cmd;
874     if (defined $mb) {
875         return rev_parse($mb) eq rev_parse($ancestor);
876     } else {
877         $?==256 or failedcmd @cmd;
878         return 0;
879     }
880 }
881
882 sub git_fetch_us () {
883     runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
884 }
885
886 sub fetch_from_archive () {
887     # ensures that lrref() is what is actually in the archive,
888     #  one way or another
889     get_archive_dsc();
890
891     if ($dsc) {
892         foreach my $field (@ourdscfield) {
893             $dsc_hash = $dsc->{$field};
894             last if defined $dsc_hash;
895         }
896         if (defined $dsc_hash) {
897             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
898             $dsc_hash = $&;
899             progress "last upload to archive specified git hash";
900         } else {
901             progress "last upload to archive has NO git hash";
902         }
903     } else {
904         progress "no version available from the archive";
905     }
906
907     my $lrref_fn = ".git/".lrref();
908     if (open H, $lrref_fn) {
909         $lastpush_hash = <H>;
910         chomp $lastpush_hash;
911         die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
912     } elsif ($! == &ENOENT) {
913         $lastpush_hash = '';
914     } else {
915         die "$lrref_fn $!";
916     }
917     print DEBUG "previous reference hash=$lastpush_hash\n";
918     my $hash;
919     if (defined $dsc_hash) {
920         fail "missing git history even though dsc has hash -".
921             " could not find commit $dsc_hash".
922             " (should be in ".access_giturl()."#".rrref().")"
923             unless $lastpush_hash;
924         $hash = $dsc_hash;
925         ensure_we_have_orig();
926         if ($dsc_hash eq $lastpush_hash) {
927         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
928             print STDERR <<END or die $!;
929
930 Git commit in archive is behind the last version allegedly pushed/uploaded.
931 Commit referred to by archive:  $dsc_hash
932 Last allegedly pushed/uploaded: $lastpush_hash
933 $later_warning_msg
934 END
935             $hash = $lastpush_hash;
936         } else {
937             fail "archive's .dsc refers to ".$dsc_hash.
938                 " but this is an ancestor of ".$lastpush_hash;
939         }
940     } elsif ($dsc) {
941         $hash = generate_commit_from_dsc();
942     } elsif ($lastpush_hash) {
943         # only in git, not in the archive yet
944         $hash = $lastpush_hash;
945         print STDERR <<END or die $!;
946
947 Package not found in the archive, but has allegedly been pushed using dgit.
948 $later_warning_msg
949 END
950     } else {
951         print DEBUG "nothing found!\n";
952         if (defined $skew_warning_vsn) {
953             print STDERR <<END or die $!;
954
955 Warning: relevant archive skew detected.
956 Archive allegedly contains $skew_warning_vsn
957 But we were not able to obtain any version from the archive or git.
958
959 END
960         }
961         return 0;
962     }
963     print DEBUG "current hash=$hash\n";
964     if ($lastpush_hash) {
965         fail "not fast forward on last upload branch!".
966             " (archive's version left in DGIT_ARCHIVE)"
967             unless is_fast_fwd($lastpush_hash, $hash);
968     }
969     if (defined $skew_warning_vsn) {
970         mkpath '.git/dgit';
971         print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
972         my $clogf = ".git/dgit/changelog.tmp";
973         runcmd shell_cmd "exec >$clogf",
974             @git, qw(cat-file blob), "$hash:debian/changelog";
975         my $gotclogp = parsechangelog("-l$clogf");
976         my $got_vsn = getfield $gotclogp, 'Version';
977         print DEBUG "SKEW CHECK GOT $got_vsn\n";
978         if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
979             print STDERR <<END or die $!;
980
981 Warning: archive skew detected.  Using the available version:
982 Archive allegedly contains    $skew_warning_vsn
983 We were able to obtain only   $got_vsn
984
985 END
986         }
987     }
988     if ($lastpush_hash ne $hash) {
989         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
990         if (!$dryrun) {
991             cmdoutput @upd_cmd;
992         } else {
993             dryrun_report @upd_cmd;
994         }
995     }
996     return 1;
997 }
998
999 sub clone ($) {
1000     my ($dstdir) = @_;
1001     canonicalise_suite();
1002     badusage "dry run makes no sense with clone" if $dryrun;
1003     mkdir $dstdir or die "$dstdir $!";
1004     chdir "$dstdir" or die "$dstdir $!";
1005     runcmd @git, qw(init -q);
1006     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1007     open H, "> .git/HEAD" or die $!;
1008     print H "ref: ".lref()."\n" or die $!;
1009     close H or die $!;
1010     runcmd @git, qw(remote add), 'origin', access_giturl();
1011     if (check_for_git()) {
1012         progress "fetching existing git history";
1013         git_fetch_us();
1014         runcmd_ordryrun @git, qw(fetch origin);
1015     } else {
1016         progress "starting new git history";
1017     }
1018     fetch_from_archive() or no_such_package;
1019     runcmd @git, qw(reset --hard), lrref();
1020     printdone "ready for work in $dstdir";
1021 }
1022
1023 sub fetch () {
1024     if (check_for_git()) {
1025         git_fetch_us();
1026     }
1027     fetch_from_archive() or no_such_package();
1028     printdone "fetched into ".lrref();
1029 }
1030
1031 sub pull () {
1032     fetch();
1033     runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
1034         lrref();
1035     printdone "fetched to ".lrref()." and merged into HEAD";
1036 }
1037
1038 sub check_not_dirty () {
1039     return if $ignoredirty;
1040     my @cmd = (@git, qw(diff --quiet HEAD));
1041     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1042     $!=0; $?=0; system @cmd;
1043     return if !$! && !$?;
1044     if (!$! && $?==256) {
1045         fail "working tree is dirty (does not match HEAD)";
1046     } else {
1047         failedcmd @cmd;
1048     }
1049 }
1050
1051 sub commit_quilty_patch () {
1052     my $output = cmdoutput @git, qw(status --porcelain);
1053     my %adds;
1054     my $bad=0;
1055     foreach my $l (split /\n/, $output) {
1056         next unless $l =~ m/\S/;
1057         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1058             $adds{$1}++;
1059         } else {
1060             print STDERR "git status: $l\n";
1061             $bad++;
1062         }
1063     }
1064     fail "unexpected output from git status (is tree clean?)" if $bad;
1065     if (!%adds) {
1066         progress "nothing quilty to commit, ok.";
1067         return;
1068     }
1069     runcmd_ordryrun @git, qw(add), sort keys %adds;
1070     my $m = "Commit Debian 3.0 (quilt) metadata";
1071     progress "$m";
1072     runcmd_ordryrun @git, qw(commit -m), $m;
1073 }
1074
1075 sub madformat ($) {
1076     my ($format) = @_;
1077     return 0 unless $format eq '3.0 (quilt)';
1078     progress "Format \`$format', urgh";
1079     if ($noquilt) {
1080         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1081         return 0;
1082     }
1083     return 1;
1084 }
1085
1086 sub push_parse_changelog ($) {
1087     my ($clogpfn) = @_;
1088
1089     my $clogp = Dpkg::Control::Hash->new();
1090     $clogp->load($clogpfn);
1091
1092     $package = getfield $clogp, 'Source';
1093     my $cversion = getfield $clogp, 'Version';
1094     my $tag = debiantag($cversion);
1095     runcmd @git, qw(check-ref-format), $tag;
1096
1097     my $dscfn = dscfn($cversion);
1098
1099     return ($clogp, $cversion, $tag, $dscfn);
1100 }
1101
1102 sub push_parse_dsc ($$$) {
1103     my ($dscfn,$dscfnwhat, $cversion) = @_;
1104     $dsc = parsecontrol($dscfn,$dscfnwhat);
1105     my $dversion = getfield $dsc, 'Version';
1106     my $dscpackage = getfield $dsc, 'Source';
1107     ($dscpackage eq $package && $dversion eq $cversion) or
1108         fail "$dsc is for $dscpackage $dversion".
1109             " but debian/changelog is for $package $cversion";
1110 }
1111
1112 sub push_mktag ($$$$$$$$) {
1113     my ($head,$clogp,$tag,
1114         $dsc,$dscfn,
1115         $changesfile,$changesfilewhat,
1116         $tfn) = @_;
1117
1118     $dsc->{$ourdscfield[0]} = $head;
1119     $dsc->save("$dscfn.tmp") or die $!;
1120
1121     my $changes = parsecontrol($changesfile,$changesfilewhat);
1122     foreach my $field (qw(Source Distribution Version)) {
1123         $changes->{$field} eq $clogp->{$field} or
1124             fail "changes field $field \`$changes->{$field}'".
1125                 " does not match changelog \`$clogp->{$field}'";
1126     }
1127
1128     my $cversion = getfield $clogp, 'Version';
1129
1130     # We make the git tag by hand because (a) that makes it easier
1131     # to control the "tagger" (b) we can do remote signing
1132     my $authline = clogp_authline $clogp;
1133     open TO, '>', $tfn->('.tmp') or die $!;
1134     print TO <<END or die $!;
1135 object $head
1136 type commit
1137 tag $tag
1138 tagger $authline
1139
1140 $package release $cversion for $csuite [dgit]
1141 END
1142     close TO or die $!;
1143
1144     my $tagobjfn = $tfn->('.tmp');
1145     if ($sign) {
1146         if (!defined $keyid) {
1147             $keyid = access_cfg('keyid','RETURN-UNDEF');
1148         }
1149         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1150         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1151         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1152         push @sign_cmd, $tfn->('.tmp');
1153         runcmd_ordryrun @sign_cmd;
1154         if (!$dryrun) {
1155             $tagobjfn = $tfn->('.signed.tmp');
1156             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1157                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1158         }
1159     }
1160
1161     return ($tagobjfn);
1162 }
1163
1164 sub sign_changes ($) {
1165     my ($changesfile) = @_;
1166     if ($sign) {
1167         my @debsign_cmd = @debsign;
1168         push @debsign_cmd, "-k$keyid" if defined $keyid;
1169         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1170         push @debsign_cmd, $changesfile;
1171         runcmd_ordryrun @debsign_cmd;
1172     }
1173 }
1174
1175 sub dopush () {
1176     print DEBUG "actually entering push\n";
1177     prep_ud();
1178
1179     my $clogpfn = ".git/dgit/changelog.822.tmp";
1180     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1181
1182     responder_send_file('parsed-changelog', $clogpfn);
1183
1184     my ($clogp, $cversion, $tag, $dscfn) =
1185         push_parse_changelog("$clogpfn");
1186
1187     stat "../$dscfn" or
1188         fail "looked for .dsc $dscfn, but $!;".
1189             " maybe you forgot to build";
1190
1191     responder_send_file('dsc', "../$dscfn");
1192
1193     push_parse_dsc("../$dscfn", $dscfn, $cversion);
1194
1195     my $format = getfield $dsc, 'Format';
1196     print DEBUG "format $format\n";
1197     if (madformat($format)) {
1198         commit_quilty_patch();
1199     }
1200     check_not_dirty();
1201     chdir $ud or die $!;
1202     progress "checking that $dscfn corresponds to HEAD";
1203     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1204     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1205     chdir '../../../..' or die $!;
1206     printcmd \*DEBUG,"+",@_;
1207     my @diffcmd = (@git, qw(diff --exit-code), $tree);
1208     $!=0; $?=0;
1209     if (system @diffcmd) {
1210         if ($! && $?==256) {
1211             fail "$dscfn specifies a different tree to your HEAD commit;".
1212                 " perhaps you forgot to build";
1213         } else {
1214             failedcmd @diffcmd;
1215         }
1216     }
1217 #fetch from alioth
1218 #do fast forward check and maybe fake merge
1219 #    if (!is_fast_fwd(mainbranch
1220 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1221 #        map { lref($_).":".rref($_) }
1222 #        (uploadbranch());
1223     my $head = rev_parse('HEAD');
1224     if (!$changesfile) {
1225         my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1226         if (stat "$multi") {
1227             $changesfile = $multi;
1228         } else {
1229             $!==&ENOENT or die "$multi: $!";
1230             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1231             my @cs = glob "../$pat";
1232             fail "failed to find unique changes file".
1233                 " (looked for $pat in .., or $multi);".
1234                 " perhaps you need to use dgit -C"
1235                 unless @cs==1;
1236             ($changesfile) = @cs;
1237         }
1238     }
1239
1240     responder_send_file('changes',$changesfile);
1241
1242     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1243     my ($tagobjfn) =
1244         $we_are_responder
1245         ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1246         : push_mktag($head,$clogp,$tag,
1247                      $dsc,"../$dscfn",
1248                      $changesfile,$changesfile,
1249                                  $tfn);
1250
1251     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1252     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1253     runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1254     runcmd_ordryrun @git, qw(tag -v --), $tag;
1255
1256     if (!check_for_git()) {
1257         create_remote_git_repo();
1258     }
1259     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1260     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1261
1262     if (!$we_are_responder) {
1263         if (!$dryrun) {
1264             rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1265         } else {
1266             progress "[new .dsc left in $dscfn.tmp]";
1267         }
1268     }
1269
1270     if ($we_are_responder) {
1271         my $dryrunsuffix = $dryrun ? ".tmp" : "";
1272         responder_receive_files('signed-dsc-changes',
1273                                 "../$dscfn$dryrunsuffix",
1274                                 "$changesfile$dryrunsuffix");
1275     } else {
1276         sign_changes $changesfile;
1277     }
1278
1279     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1280     my $host = access_cfg('upload-host','RETURN-UNDEF');
1281     my @hostarg = defined($host) ? ($host,) : ();
1282     runcmd_ordryrun @dput, @hostarg, $changesfile;
1283     printdone "pushed and uploaded $cversion";
1284
1285     responder_send_command("complete");
1286 }
1287
1288 sub cmd_clone {
1289     parseopts();
1290     my $dstdir;
1291     badusage "-p is not allowed with clone; specify as argument instead"
1292         if defined $package;
1293     if (@ARGV==1) {
1294         ($package) = @ARGV;
1295     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1296         ($package,$isuite) = @ARGV;
1297     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1298         ($package,$dstdir) = @ARGV;
1299     } elsif (@ARGV==3) {
1300         ($package,$isuite,$dstdir) = @ARGV;
1301     } else {
1302         badusage "incorrect arguments to dgit clone";
1303     }
1304     $dstdir ||= "$package";
1305     clone($dstdir);
1306 }
1307
1308 sub branchsuite () {
1309     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1310     if ($branch =~ m#$lbranch_re#o) {
1311         return $1;
1312     } else {
1313         return undef;
1314     }
1315 }
1316
1317 sub fetchpullargs () {
1318     if (!defined $package) {
1319         my $sourcep = parsecontrol('debian/control','debian/control');
1320         $package = getfield $sourcep, 'Source';
1321     }
1322     if (@ARGV==0) {
1323 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1324         if (!$isuite) {
1325             my $clogp = parsechangelog();
1326             $isuite = getfield $clogp, 'Distribution';
1327         }
1328         canonicalise_suite();
1329         progress "fetching from suite $csuite";
1330     } elsif (@ARGV==1) {
1331         ($isuite) = @ARGV;
1332         canonicalise_suite();
1333     } else {
1334         badusage "incorrect arguments to dgit fetch or dgit pull";
1335     }
1336 }
1337
1338 sub cmd_fetch {
1339     parseopts();
1340     fetchpullargs();
1341     fetch();
1342 }
1343
1344 sub cmd_pull {
1345     parseopts();
1346     fetchpullargs();
1347     pull();
1348 }
1349
1350 sub cmd_push {
1351     parseopts();
1352     badusage "-p is not allowed with dgit push" if defined $package;
1353     check_not_dirty();
1354     my $clogp = parsechangelog();
1355     $package = getfield $clogp, 'Source';
1356     my $specsuite;
1357     if (@ARGV==0) {
1358     } elsif (@ARGV==1) {
1359         ($specsuite) = (@ARGV);
1360     } else {
1361         badusage "incorrect arguments to dgit push";
1362     }
1363     $isuite = getfield $clogp, 'Distribution';
1364     if ($new_package) {
1365         local ($package) = $existing_package; # this is a hack
1366         canonicalise_suite();
1367     }
1368     if (defined $specsuite && $specsuite ne $isuite) {
1369         canonicalise_suite();
1370         $csuite eq $specsuite or
1371             fail "dgit push: changelog specifies $isuite ($csuite)".
1372                 " but command line specifies $specsuite";
1373     }
1374     if (check_for_git()) {
1375         git_fetch_us();
1376     }
1377     if (fetch_from_archive()) {
1378         is_fast_fwd(lrref(), 'HEAD') or
1379             fail "dgit push: HEAD is not a descendant".
1380                 " of the archive's version.\n".
1381                 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1382     } else {
1383         $new_package or
1384             fail "package appears to be new in this suite;".
1385                 " if this is intentional, use --new";
1386     }
1387     dopush();
1388 }
1389
1390 #---------- remote commands' implementation ----------
1391
1392 sub cmd_remote_push_responder {
1393     my ($nrargs) = shift @ARGV;
1394     my (@rargs) = @ARGV[0..$nrargs-1];
1395     @ARGV = @ARGV[$nrargs..$#ARGV];
1396     die unless @rargs;
1397     my ($dir) = @rargs;
1398     chdir $dir or die "$dir: $!";
1399     $we_are_responder = 1;
1400     $|=1;
1401     responder_send_command("dgit-remote-push-ready");
1402     &cmd_push;
1403 }
1404
1405 our $i_tmp;
1406
1407 sub i_cleanup {
1408     local ($@);
1409     return unless defined $i_tmp;
1410     chdir "/" or die $!;
1411     eval { rmtree $i_tmp; };
1412 }
1413
1414 sub i_method {
1415     my ($base,$selector,@args) = @_;
1416     $selector =~ s/\-/_/g;
1417     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1418 }
1419
1420 sub cmd_rpush {
1421     my $host = nextarg;
1422     my $dir;
1423     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1424         $host = $1;
1425         $dir = $'; #';
1426     } else {
1427         $dir = nextarg;
1428     }
1429     $dir =~ s{^-}{./-};
1430     my @rargs = ($dir);
1431     my @rdgit;
1432     push @rdgit, @dgit;
1433     push @rdgit, @ropts;
1434     push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1435     push @rdgit, @ARGV;
1436     my @cmd = (@ssh, $host, shellquote @rdgit);
1437     printcmd \*DEBUG,"+",@cmd;
1438     eval {
1439         $i_tmp = tempdir();
1440         my $pid = open2(\*RO, \*RI, @cmd);
1441         chdir $i_tmp or die "$i_tmp $!";
1442         initiator_expect { m/^dgit-remote-push-ready/ };
1443         for (;;) {
1444             my ($icmd,$iargs) = initiator_expect {
1445                 m/^(\S+)(?: (.*))?$/;
1446                 ($1,$2);
1447             };
1448             i_method "i_resp", $icmd, $iargs;
1449         }
1450     };
1451     i_cleanup();
1452     die $@;
1453 }
1454
1455 sub i_resp_progress ($) {
1456     my ($rhs) = @_;
1457     my $msg = protocol_read_bytes \*RO, $rhs;
1458     progress $msg;
1459 }
1460
1461 sub i_resp_complete {
1462     i_cleanup();
1463     exit 0;
1464 }
1465
1466 sub i_resp_file ($) {
1467     my ($keyword) = @_;
1468     my $localname = i_method "i_localname", $keyword;
1469     my $localpath = "$i_tmp/$localname";
1470     stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1471     protocol_receive_file \*RO, $localpath;
1472 }
1473
1474 our %i_param;
1475
1476 sub i_param ($) {
1477     $_[0] =~ m/^(\S+) (.*)$/;
1478     $i_param{$1} = $2;
1479 }
1480
1481 our %i_wanted;
1482
1483 sub i_resp_want ($) {
1484     my ($keyword) = @_;
1485     die "$keyword ?" if $i_wanted{$keyword}++;
1486     my @localpaths = i_method "i_want", $keyword;
1487     foreach my $localpath (@localpaths) {
1488         protocol_send_file \*RI, $localpath;
1489     }
1490     print RI "end-files\n" or die $!;
1491 }
1492
1493 our ($i_clogp, $i_version, $i_tag, $i_dscfn);
1494
1495 sub i_localname_parsed_changelog { return "remote-changelog.822"; }
1496 sub i_localname_changes { return "remote.changes"; }
1497 sub i_localname_dsc {
1498     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1499         push_parse_changelog 'remote-changelog.822';
1500     die if $i_dscfn =~ m#/|^\W#;
1501     return $i_dscfn;
1502 }
1503
1504 sub i_want_signed_tag {
1505     defined $i_param{'head'} && defined $i_dscfn
1506         or badproto \*RO, "sequencing error";
1507     my $head = $i_param{'head'};
1508     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1509
1510     push_parse_dsc $i_dscfn, 'remote dsc', 
1511
1512     push_mktag $head, $i_clogp, $i_tag,
1513         $dsc, $i_dscfn,
1514         'remote.changes', 'remote changes',
1515         'tag.tag';
1516
1517     return 'tag.tag';
1518 }
1519
1520 sub i_want_signed_dsc_changes {
1521     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1522     sign_changes 'remote.changes';
1523     return ($i_dscfn, 'remote.changes');
1524 }
1525
1526 #---------- building etc. ----------
1527
1528 our $version;
1529 our $sourcechanges;
1530 our $dscfn;
1531
1532 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1533
1534 sub build_maybe_quilt_fixup () {
1535     if (!open F, "debian/source/format") {
1536         die $! unless $!==&ENOENT;
1537         return;
1538     }
1539     $_ = <F>;
1540     F->error and die $!;
1541     chomp;
1542     return unless madformat($_);
1543     # sigh
1544     my $clogp = parsechangelog();
1545     my $version = getfield $clogp, 'Version';
1546     my $author = getfield $clogp, 'Maintainer';
1547     my $headref = rev_parse('HEAD');
1548     my $time = time;
1549     my $ncommits = 3;
1550     my $patchname = "auto-$version-$headref-$time";
1551     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1552     mkpath '.git/dgit';
1553     my $descfn = ".git/dgit/quilt-description.tmp";
1554     open O, '>', $descfn or die "$descfn: $!";
1555     $msg =~ s/\n/\n /g;
1556     $msg =~ s/^\s+$/ ./mg;
1557     print O <<END or die $!;
1558 Description: Automatically generated patch ($clogp->{Version})
1559  Last (up to) $ncommits git changes, FYI:
1560  .
1561  $msg
1562 Author: $author
1563
1564 ---
1565
1566 END
1567     close O or die $!;
1568     {
1569         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1570         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1571         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1572         runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1573     }
1574
1575     if (!open P, '>>', ".pc/applied-patches") {
1576         $!==&ENOENT or die $!;
1577     } else {
1578         close P;
1579     }
1580
1581     commit_quilty_patch();
1582 }
1583
1584 sub quilt_fixup_editor () {
1585     my $descfn = $ENV{$fakeeditorenv};
1586     my $editing = $ARGV[$#ARGV];
1587     open I1, '<', $descfn or die "$descfn: $!";
1588     open I2, '<', $editing or die "$editing: $!";
1589     unlink $editing or die "$editing: $!";
1590     open O, '>', $editing or die "$editing: $!";
1591     while (<I1>) { print O or die $!; } I1->error and die $!;
1592     my $copying = 0;
1593     while (<I2>) {
1594         $copying ||= m/^\-\-\- /;
1595         next unless $copying;
1596         print O or die $!;
1597     }
1598     I2->error and die $!;
1599     close O or die $1;
1600     exit 0;
1601 }
1602
1603 sub build_prep () {
1604     badusage "-p is not allowed when building" if defined $package;
1605     check_not_dirty();
1606     my $clogp = parsechangelog();
1607     $isuite = getfield $clogp, 'Distribution';
1608     $package = getfield $clogp, 'Source';
1609     $version = getfield $clogp, 'Version';
1610     build_maybe_quilt_fixup();
1611 }
1612
1613 sub cmd_build {
1614     badusage "dgit build implies --clean=dpkg-source"
1615         if $cleanmode ne 'dpkg-source';
1616     build_prep();
1617     runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1618     printdone "build successful\n";
1619 }
1620
1621 sub cmd_git_build {
1622     badusage "dgit git-build implies --clean=dpkg-source"
1623         if $cleanmode ne 'dpkg-source';
1624     build_prep();
1625     my @cmd =
1626         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1627          "--git-builder=@dpkgbuildpackage");
1628     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1629         canonicalise_suite();
1630         push @cmd, "--git-debian-branch=".lbranch();
1631     }
1632     push @cmd, changesopts();
1633     runcmd_ordryrun @cmd, @ARGV;
1634     printdone "build successful\n";
1635 }
1636
1637 sub build_source {
1638     build_prep();
1639     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1640     $dscfn = dscfn($version);
1641     if ($cleanmode eq 'dpkg-source') {
1642         runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1643     } else {
1644         if ($cleanmode eq 'git') {
1645             runcmd_ordryrun @git, qw(clean -xdf);
1646         } elsif ($cleanmode eq 'none') {
1647         } else {
1648             die "$cleanmode ?";
1649         }
1650         my $pwd = cmdoutput qw(env - pwd);
1651         my $leafdir = basename $pwd;
1652         chdir ".." or die $!;
1653         runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1654         chdir $pwd or die $!;
1655         runcmd_ordryrun qw(sh -ec),
1656             'exec >$1; shift; exec "$@"','x',
1657             "../$sourcechanges",
1658             @dpkggenchanges, qw(-S), changesopts();
1659     }
1660 }
1661
1662 sub cmd_build_source {
1663     badusage "build-source takes no additional arguments" if @ARGV;
1664     build_source();
1665     printdone "source built, results in $dscfn and $sourcechanges";
1666 }
1667
1668 sub cmd_sbuild {
1669     build_source();
1670     chdir ".." or die $!;
1671     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1672     if (!$dryrun) {
1673         stat $dscfn or fail "$dscfn (in parent directory): $!";
1674         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1675         foreach my $cf (glob $pat) {
1676             next if $cf eq $sourcechanges;
1677             unlink $cf or fail "remove $cf: $!";
1678         }
1679     }
1680     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1681     runcmd_ordryrun @mergechanges, glob $pat;
1682     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1683     if (!$dryrun) {
1684         stat $multichanges or fail "$multichanges: $!";
1685     }
1686     printdone "build successful, results in $multichanges\n" or die $!;
1687 }    
1688
1689 sub cmd_quilt_fixup {
1690     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1691     my $clogp = parsechangelog();
1692     $version = getfield $clogp, 'Version';
1693     build_maybe_quilt_fixup();
1694 }
1695
1696 #---------- argument parsing and main program ----------
1697
1698 sub cmd_version {
1699     print "dgit version $our_version\n" or die $!;
1700     exit 0;
1701 }
1702
1703 sub parseopts () {
1704     my $om;
1705
1706     if (defined $ENV{'DGIT_SSH'}) {
1707         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1708     } elsif (defined $ENV{'GIT_SSH'}) {
1709         @ssh = ($ENV{'GIT_SSH'});
1710     }
1711
1712     while (@ARGV) {
1713         last unless $ARGV[0] =~ m/^-/;
1714         $_ = shift @ARGV;
1715         last if m/^--?$/;
1716         if (m/^--/) {
1717             if (m/^--dry-run$/) {
1718                 push @ropts, $_;
1719                 $dryrun=1;
1720             } elsif (m/^--no-sign$/) {
1721                 push @ropts, $_;
1722                 $sign=0;
1723             } elsif (m/^--help$/) {
1724                 cmd_help();
1725             } elsif (m/^--version$/) {
1726                 cmd_version();
1727             } elsif (m/^--new$/) {
1728                 push @ropts, $_;
1729                 $new_package=1;
1730             } elsif (m/^--(\w+)=(.*)/s &&
1731                      ($om = $opts_opt_map{$1}) &&
1732                      length $om->[0]) {
1733                 push @ropts, $_;
1734                 $om->[0] = $2;
1735             } elsif (m/^--(\w+):(.*)/s &&
1736                      !$opts_opt_cmdonly{$1} &&
1737                      ($om = $opts_opt_map{$1})) {
1738                 push @ropts, $_;
1739                 push @$om, $2;
1740             } elsif (m/^--existing-package=(.*)/s) {
1741                 push @ropts, $_;
1742                 $existing_package = $1;
1743             } elsif (m/^--distro=(.*)/s) {
1744                 push @ropts, $_;
1745                 $idistro = $1;
1746             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1747                 push @ropts, $_;
1748                 $cleanmode = $1;
1749             } elsif (m/^--clean=(.*)$/s) {
1750                 badusage "unknown cleaning mode \`$1'";
1751             } elsif (m/^--ignore-dirty$/s) {
1752                 push @ropts, $_;
1753                 $ignoredirty = 1;
1754             } elsif (m/^--no-quilt-fixup$/s) {
1755                 push @ropts, $_;
1756                 $noquilt = 1;
1757             } else {
1758                 badusage "unknown long option \`$_'";
1759             }
1760         } else {
1761             while (m/^-./s) {
1762                 if (s/^-n/-/) {
1763                     push @ropts, $_;
1764                     $dryrun=1;
1765                 } elsif (s/^-h/-/) {
1766                     cmd_help();
1767                 } elsif (s/^-D/-/) {
1768                     push @ropts, $&;
1769                     open DEBUG, ">&STDERR" or die $!;
1770                     $debug++;
1771                 } elsif (s/^-N/-/) {
1772                     push @ropts, $&;
1773                     $new_package=1;
1774                 } elsif (m/^-[vm]/) {
1775                     push @ropts, $&;
1776                     push @changesopts, $_;
1777                     $_ = '';
1778                 } elsif (s/^-c(.*=.*)//s) {
1779                     push @ropts, $&;
1780                     push @git, '-c', $1;
1781                 } elsif (s/^-d(.*)//s) {
1782                     push @ropts, $&;
1783                     $idistro = $1;
1784                 } elsif (s/^-C(.*)//s) {
1785                     push @ropts, $&;
1786                     $changesfile = $1;
1787                 } elsif (s/^-k(.*)//s) {
1788                     $keyid=$1;
1789                 } elsif (s/^-wn//s) {
1790                     push @ropts, $&;
1791                     $cleanmode = 'none';
1792                 } elsif (s/^-wg//s) {
1793                     push @ropts, $&;
1794                     $cleanmode = 'git';
1795                 } elsif (s/^-wd//s) {
1796                     push @ropts, $&;
1797                     $cleanmode = 'dpkg-source';
1798                 } else {
1799                     badusage "unknown short option \`$_'";
1800                 }
1801             }
1802         }
1803     }
1804 }
1805
1806 if ($ENV{$fakeeditorenv}) {
1807     quilt_fixup_editor();
1808 }
1809
1810 delete $ENV{'DGET_UNPACK'};
1811
1812 parseopts();
1813 print STDERR "DRY RUN ONLY\n" if $dryrun;
1814 if (!@ARGV) {
1815     print STDERR $helpmsg or die $!;
1816     exit 8;
1817 }
1818 my $cmd = shift @ARGV;
1819 $cmd =~ y/-/_/;
1820 { no strict qw(refs); &{"cmd_$cmd"}(); }