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