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