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