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