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