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