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