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