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