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