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