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