chiark / gitweb /
When generating git tags, quote the (uncanonicalised) changelog's Distribution field...
[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     my $clogsuite = getfield $clogp, 'Distribution';
1156
1157     # We make the git tag by hand because (a) that makes it easier
1158     # to control the "tagger" (b) we can do remote signing
1159     my $authline = clogp_authline $clogp;
1160     open TO, '>', $tfn->('.tmp') or die $!;
1161     print TO <<END or die $!;
1162 object $head
1163 type commit
1164 tag $tag
1165 tagger $authline
1166
1167 $package release $cversion for $clogsuite [dgit]
1168 END
1169     close TO or die $!;
1170
1171     my $tagobjfn = $tfn->('.tmp');
1172     if ($sign) {
1173         if (!defined $keyid) {
1174             $keyid = access_cfg('keyid','RETURN-UNDEF');
1175         }
1176         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1177         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1178         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1179         push @sign_cmd, $tfn->('.tmp');
1180         runcmd_ordryrun @sign_cmd;
1181         if (act_scary()) {
1182             $tagobjfn = $tfn->('.signed.tmp');
1183             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1184                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1185         }
1186     }
1187
1188     return ($tagobjfn);
1189 }
1190
1191 sub sign_changes ($) {
1192     my ($changesfile) = @_;
1193     if ($sign) {
1194         my @debsign_cmd = @debsign;
1195         push @debsign_cmd, "-k$keyid" if defined $keyid;
1196         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1197         push @debsign_cmd, $changesfile;
1198         runcmd_ordryrun @debsign_cmd;
1199     }
1200 }
1201
1202 sub dopush () {
1203     printdebug "actually entering push\n";
1204     prep_ud();
1205
1206     my $clogpfn = ".git/dgit/changelog.822.tmp";
1207     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1208
1209     responder_send_file('parsed-changelog', $clogpfn);
1210
1211     my ($clogp, $cversion, $tag, $dscfn) =
1212         push_parse_changelog("$clogpfn");
1213
1214     stat "../$dscfn" or
1215         fail "looked for .dsc $dscfn, but $!;".
1216             " maybe you forgot to build";
1217
1218     responder_send_file('dsc', "../$dscfn");
1219
1220     push_parse_dsc("../$dscfn", $dscfn, $cversion);
1221
1222     my $format = getfield $dsc, 'Format';
1223     printdebug "format $format\n";
1224     if (madformat($format)) {
1225         commit_quilty_patch();
1226     }
1227     check_not_dirty();
1228     changedir $ud;
1229     progress "checking that $dscfn corresponds to HEAD";
1230     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1231     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1232     changedir '../../../..';
1233     my @diffcmd = (@git, qw(diff --exit-code), $tree);
1234     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1235     $!=0; $?=0;
1236     if (system @diffcmd) {
1237         if ($! && $?==256) {
1238             fail "$dscfn specifies a different tree to your HEAD commit;".
1239                 " perhaps you forgot to build";
1240         } else {
1241             failedcmd @diffcmd;
1242         }
1243     }
1244 #fetch from alioth
1245 #do fast forward check and maybe fake merge
1246 #    if (!is_fast_fwd(mainbranch
1247 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1248 #        map { lref($_).":".rref($_) }
1249 #        (uploadbranch());
1250     my $head = rev_parse('HEAD');
1251     if (!$changesfile) {
1252         my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1253         if (stat "$multi") {
1254             $changesfile = $multi;
1255         } else {
1256             $!==&ENOENT or die "$multi: $!";
1257             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1258             my @cs = glob "../$pat";
1259             fail "failed to find unique changes file".
1260                 " (looked for $pat in .., or $multi);".
1261                 " perhaps you need to use dgit -C"
1262                 unless @cs==1;
1263             ($changesfile) = @cs;
1264         }
1265     }
1266
1267     responder_send_file('changes',$changesfile);
1268     responder_send_command("param head $head");
1269
1270     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1271     my ($tagobjfn) =
1272         $we_are_responder
1273         ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1274         : push_mktag($head,$clogp,$tag,
1275                      "../$dscfn",
1276                      $changesfile,$changesfile,
1277                                  $tfn);
1278
1279     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1280     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1281     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1282     runcmd_ordryrun @git, qw(tag -v --), $tag;
1283
1284     if (!check_for_git()) {
1285         create_remote_git_repo();
1286     }
1287     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1288     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1289
1290     if (!$we_are_responder) {
1291         if (act_local()) {
1292             rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1293         } else {
1294             progress "[new .dsc left in $dscfn.tmp]";
1295         }
1296     }
1297
1298     if ($we_are_responder) {
1299         my $dryrunsuffix = act_local() ? "" : ".tmp";
1300         responder_receive_files('signed-dsc-changes',
1301                                 "../$dscfn$dryrunsuffix",
1302                                 "$changesfile$dryrunsuffix");
1303     } else {
1304         sign_changes $changesfile;
1305     }
1306
1307     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1308     my $host = access_cfg('upload-host','RETURN-UNDEF');
1309     my @hostarg = defined($host) ? ($host,) : ();
1310     runcmd_ordryrun @dput, @hostarg, $changesfile;
1311     printdone "pushed and uploaded $cversion";
1312
1313     responder_send_command("complete");
1314 }
1315
1316 sub cmd_clone {
1317     parseopts();
1318     my $dstdir;
1319     badusage "-p is not allowed with clone; specify as argument instead"
1320         if defined $package;
1321     if (@ARGV==1) {
1322         ($package) = @ARGV;
1323     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1324         ($package,$isuite) = @ARGV;
1325     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1326         ($package,$dstdir) = @ARGV;
1327     } elsif (@ARGV==3) {
1328         ($package,$isuite,$dstdir) = @ARGV;
1329     } else {
1330         badusage "incorrect arguments to dgit clone";
1331     }
1332     $dstdir ||= "$package";
1333     clone($dstdir);
1334 }
1335
1336 sub branchsuite () {
1337     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1338     if ($branch =~ m#$lbranch_re#o) {
1339         return $1;
1340     } else {
1341         return undef;
1342     }
1343 }
1344
1345 sub fetchpullargs () {
1346     if (!defined $package) {
1347         my $sourcep = parsecontrol('debian/control','debian/control');
1348         $package = getfield $sourcep, 'Source';
1349     }
1350     if (@ARGV==0) {
1351 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1352         if (!$isuite) {
1353             my $clogp = parsechangelog();
1354             $isuite = getfield $clogp, 'Distribution';
1355         }
1356         canonicalise_suite();
1357         progress "fetching from suite $csuite";
1358     } elsif (@ARGV==1) {
1359         ($isuite) = @ARGV;
1360         canonicalise_suite();
1361     } else {
1362         badusage "incorrect arguments to dgit fetch or dgit pull";
1363     }
1364 }
1365
1366 sub cmd_fetch {
1367     parseopts();
1368     fetchpullargs();
1369     fetch();
1370 }
1371
1372 sub cmd_pull {
1373     parseopts();
1374     fetchpullargs();
1375     pull();
1376 }
1377
1378 sub cmd_push {
1379     parseopts();
1380     badusage "-p is not allowed with dgit push" if defined $package;
1381     check_not_dirty();
1382     my $clogp = parsechangelog();
1383     $package = getfield $clogp, 'Source';
1384     my $specsuite;
1385     if (@ARGV==0) {
1386     } elsif (@ARGV==1) {
1387         ($specsuite) = (@ARGV);
1388     } else {
1389         badusage "incorrect arguments to dgit push";
1390     }
1391     $isuite = getfield $clogp, 'Distribution';
1392     if ($new_package) {
1393         local ($package) = $existing_package; # this is a hack
1394         canonicalise_suite();
1395     }
1396     if (defined $specsuite && $specsuite ne $isuite) {
1397         canonicalise_suite();
1398         $csuite eq $specsuite or
1399             fail "dgit push: changelog specifies $isuite ($csuite)".
1400                 " but command line specifies $specsuite";
1401     }
1402     if (check_for_git()) {
1403         git_fetch_us();
1404     }
1405     if (fetch_from_archive()) {
1406         is_fast_fwd(lrref(), 'HEAD') or
1407             fail "dgit push: HEAD is not a descendant".
1408                 " of the archive's version.\n".
1409                 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1410     } else {
1411         $new_package or
1412             fail "package appears to be new in this suite;".
1413                 " if this is intentional, use --new";
1414     }
1415     dopush();
1416 }
1417
1418 #---------- remote commands' implementation ----------
1419
1420 sub cmd_remote_push_responder {
1421     my ($nrargs) = shift @ARGV;
1422     my (@rargs) = @ARGV[0..$nrargs-1];
1423     @ARGV = @ARGV[$nrargs..$#ARGV];
1424     die unless @rargs;
1425     my ($dir) = @rargs;
1426     $debugprefix = ' ';
1427     $we_are_responder = 1;
1428
1429     open PI, "<&STDIN" or die $!;
1430     open STDIN, "/dev/null" or die $!;
1431     open PO, ">&STDOUT" or die $!;
1432     autoflush PO 1;
1433     open STDOUT, ">&STDERR" or die $!;
1434     autoflush STDOUT 1;
1435
1436     responder_send_command("dgit-remote-push-ready");
1437
1438     changedir $dir;
1439     &cmd_push;
1440 }
1441
1442 our $i_tmp;
1443 our $i_child_pid;
1444
1445 sub i_cleanup {
1446     local ($@);
1447     if ($i_child_pid) {
1448         printdebug "(killing remote child $i_child_pid)\n";
1449         kill 15, $i_child_pid;
1450     }
1451     if (defined $i_tmp && !defined $initiator_tempdir) {
1452         changedir "/";
1453         eval { rmtree $i_tmp; };
1454     }
1455 }
1456
1457 END { i_cleanup(); }
1458
1459 sub i_method {
1460     my ($base,$selector,@args) = @_;
1461     $selector =~ s/\-/_/g;
1462     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1463 }
1464
1465 sub cmd_rpush {
1466     my $host = nextarg;
1467     my $dir;
1468     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1469         $host = $1;
1470         $dir = $'; #';
1471     } else {
1472         $dir = nextarg;
1473     }
1474     $dir =~ s{^-}{./-};
1475     my @rargs = ($dir);
1476     my @rdgit;
1477     push @rdgit, @dgit;
1478     push @rdgit, @ropts;
1479     push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1480     push @rdgit, @ARGV;
1481     my @cmd = (@ssh, $host, shellquote @rdgit);
1482     printcmd \*DEBUG,$debugprefix."+",@cmd;
1483
1484     if (defined $initiator_tempdir) {
1485         rmtree $initiator_tempdir;
1486         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1487         $i_tmp = $initiator_tempdir;
1488     } else {
1489         $i_tmp = tempdir();
1490     }
1491     $i_child_pid = open2(\*RO, \*RI, @cmd);
1492     changedir $i_tmp;
1493     initiator_expect { m/^dgit-remote-push-ready/ };
1494     for (;;) {
1495         my ($icmd,$iargs) = initiator_expect {
1496             m/^(\S+)(?: (.*))?$/;
1497             ($1,$2);
1498         };
1499         i_method "i_resp", $icmd, $iargs;
1500     }
1501
1502     my $pid = $i_child_pid;
1503     $i_child_pid = undef; # prevents killing some other process with same pid
1504     printdebug "waiting for remote child $pid...";
1505     my $got = waitpid $pid, 0;
1506     die $! unless $got == $pid;
1507     die "remote child failed $?" if $?;
1508
1509     i_cleanup();
1510     exit 0;
1511 }
1512
1513 sub i_resp_progress ($) {
1514     my ($rhs) = @_;
1515     my $msg = protocol_read_bytes \*RO, $rhs;
1516     progress $msg;
1517 }
1518
1519 sub i_resp_complete {
1520     i_cleanup();
1521     exit 0;
1522 }
1523
1524 sub i_resp_file ($) {
1525     my ($keyword) = @_;
1526     my $localname = i_method "i_localname", $keyword;
1527     my $localpath = "$i_tmp/$localname";
1528     stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1529     protocol_receive_file \*RO, $localpath;
1530 }
1531
1532 our %i_param;
1533
1534 sub i_resp_param ($) {
1535     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1536     $i_param{$1} = $2;
1537 }
1538
1539 our %i_wanted;
1540
1541 sub i_resp_want ($) {
1542     my ($keyword) = @_;
1543     die "$keyword ?" if $i_wanted{$keyword}++;
1544     my @localpaths = i_method "i_want", $keyword;
1545     printdebug "]]  $keyword @localpaths\n";
1546     foreach my $localpath (@localpaths) {
1547         protocol_send_file \*RI, $localpath;
1548     }
1549     print RI "end-files\n" or die $!;
1550 }
1551
1552 our ($i_clogp, $i_version, $i_tag, $i_dscfn);
1553
1554 sub i_localname_parsed_changelog { return "remote-changelog.822"; }
1555 sub i_localname_changes { return "remote.changes"; }
1556 sub i_localname_dsc {
1557     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1558         push_parse_changelog "$i_tmp/remote-changelog.822";
1559     die if $i_dscfn =~ m#/|^\W#;
1560     return $i_dscfn;
1561 }
1562
1563 sub i_want_signed_tag {
1564     printdebug Dumper(\%i_param, $i_dscfn);
1565     defined $i_param{'head'} && defined $i_dscfn
1566         or badproto \*RO, "sequencing error";
1567     my $head = $i_param{'head'};
1568     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1569
1570     push_parse_dsc $i_dscfn, 'remote dsc', 
1571
1572     push_mktag $head, $i_clogp, $i_tag,
1573         $i_dscfn,
1574         'remote.changes', 'remote changes',
1575         'tag.tag';
1576
1577     return 'tag.tag';
1578 }
1579
1580 sub i_want_signed_dsc_changes {
1581     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1582     sign_changes 'remote.changes';
1583     return ($i_dscfn, 'remote.changes');
1584 }
1585
1586 #---------- building etc. ----------
1587
1588 our $version;
1589 our $sourcechanges;
1590 our $dscfn;
1591
1592 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1593
1594 sub build_maybe_quilt_fixup () {
1595     if (!open F, "debian/source/format") {
1596         die $! unless $!==&ENOENT;
1597         return;
1598     }
1599     $_ = <F>;
1600     F->error and die $!;
1601     chomp;
1602     return unless madformat($_);
1603     # sigh
1604     my $clogp = parsechangelog();
1605     my $version = getfield $clogp, 'Version';
1606     my $author = getfield $clogp, 'Maintainer';
1607     my $headref = rev_parse('HEAD');
1608     my $time = time;
1609     my $ncommits = 3;
1610     my $patchname = "auto-$version-$headref-$time";
1611     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1612     mkpath '.git/dgit';
1613     my $descfn = ".git/dgit/quilt-description.tmp";
1614     open O, '>', $descfn or die "$descfn: $!";
1615     $msg =~ s/\n/\n /g;
1616     $msg =~ s/^\s+$/ ./mg;
1617     print O <<END or die $!;
1618 Description: Automatically generated patch ($clogp->{Version})
1619  Last (up to) $ncommits git changes, FYI:
1620  .
1621  $msg
1622 Author: $author
1623
1624 ---
1625
1626 END
1627     close O or die $!;
1628     {
1629         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1630         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1631         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1632         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1633     }
1634
1635     if (!open P, '>>', ".pc/applied-patches") {
1636         $!==&ENOENT or die $!;
1637     } else {
1638         close P;
1639     }
1640
1641     commit_quilty_patch();
1642 }
1643
1644 sub quilt_fixup_editor () {
1645     my $descfn = $ENV{$fakeeditorenv};
1646     my $editing = $ARGV[$#ARGV];
1647     open I1, '<', $descfn or die "$descfn: $!";
1648     open I2, '<', $editing or die "$editing: $!";
1649     unlink $editing or die "$editing: $!";
1650     open O, '>', $editing or die "$editing: $!";
1651     while (<I1>) { print O or die $!; } I1->error and die $!;
1652     my $copying = 0;
1653     while (<I2>) {
1654         $copying ||= m/^\-\-\- /;
1655         next unless $copying;
1656         print O or die $!;
1657     }
1658     I2->error and die $!;
1659     close O or die $1;
1660     exit 0;
1661 }
1662
1663 sub build_prep () {
1664     badusage "-p is not allowed when building" if defined $package;
1665     check_not_dirty();
1666     my $clogp = parsechangelog();
1667     $isuite = getfield $clogp, 'Distribution';
1668     $package = getfield $clogp, 'Source';
1669     $version = getfield $clogp, 'Version';
1670     build_maybe_quilt_fixup();
1671 }
1672
1673 sub cmd_build {
1674     badusage "dgit build implies --clean=dpkg-source"
1675         if $cleanmode ne 'dpkg-source';
1676     build_prep();
1677     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1678     printdone "build successful\n";
1679 }
1680
1681 sub cmd_git_build {
1682     badusage "dgit git-build implies --clean=dpkg-source"
1683         if $cleanmode ne 'dpkg-source';
1684     build_prep();
1685     my @cmd =
1686         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1687          "--git-builder=@dpkgbuildpackage");
1688     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1689         canonicalise_suite();
1690         push @cmd, "--git-debian-branch=".lbranch();
1691     }
1692     push @cmd, changesopts();
1693     runcmd_ordryrun_local @cmd, @ARGV;
1694     printdone "build successful\n";
1695 }
1696
1697 sub build_source {
1698     build_prep();
1699     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1700     $dscfn = dscfn($version);
1701     if ($cleanmode eq 'dpkg-source') {
1702         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
1703             changesopts();
1704     } else {
1705         if ($cleanmode eq 'git') {
1706             runcmd_ordryrun_local @git, qw(clean -xdf);
1707         } elsif ($cleanmode eq 'none') {
1708         } else {
1709             die "$cleanmode ?";
1710         }
1711         my $pwd = cmdoutput qw(env - pwd);
1712         my $leafdir = basename $pwd;
1713         changedir "..";
1714         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
1715         changedir $pwd;
1716         runcmd_ordryrun_local qw(sh -ec),
1717             'exec >$1; shift; exec "$@"','x',
1718             "../$sourcechanges",
1719             @dpkggenchanges, qw(-S), changesopts();
1720     }
1721 }
1722
1723 sub cmd_build_source {
1724     badusage "build-source takes no additional arguments" if @ARGV;
1725     build_source();
1726     printdone "source built, results in $dscfn and $sourcechanges";
1727 }
1728
1729 sub cmd_sbuild {
1730     build_source();
1731     changedir "..";
1732     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1733     if (act_local()) {
1734         stat $dscfn or fail "$dscfn (in parent directory): $!";
1735         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1736         foreach my $cf (glob $pat) {
1737             next if $cf eq $sourcechanges;
1738             unlink $cf or fail "remove $cf: $!";
1739         }
1740     }
1741     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1742     runcmd_ordryrun_local @mergechanges, glob $pat;
1743     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1744     if (act_local()) {
1745         stat $multichanges or fail "$multichanges: $!";
1746     }
1747     printdone "build successful, results in $multichanges\n" or die $!;
1748 }    
1749
1750 sub cmd_quilt_fixup {
1751     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1752     my $clogp = parsechangelog();
1753     $version = getfield $clogp, 'Version';
1754     build_maybe_quilt_fixup();
1755 }
1756
1757 #---------- argument parsing and main program ----------
1758
1759 sub cmd_version {
1760     print "dgit version $our_version\n" or die $!;
1761     exit 0;
1762 }
1763
1764 sub parseopts () {
1765     my $om;
1766
1767     if (defined $ENV{'DGIT_SSH'}) {
1768         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1769     } elsif (defined $ENV{'GIT_SSH'}) {
1770         @ssh = ($ENV{'GIT_SSH'});
1771     }
1772
1773     while (@ARGV) {
1774         last unless $ARGV[0] =~ m/^-/;
1775         $_ = shift @ARGV;
1776         last if m/^--?$/;
1777         if (m/^--/) {
1778             if (m/^--dry-run$/) {
1779                 push @ropts, $_;
1780                 $dryrun_level=2;
1781             } elsif (m/^--damp-run$/) {
1782                 push @ropts, $_;
1783                 $dryrun_level=1;
1784             } elsif (m/^--no-sign$/) {
1785                 push @ropts, $_;
1786                 $sign=0;
1787             } elsif (m/^--help$/) {
1788                 cmd_help();
1789             } elsif (m/^--version$/) {
1790                 cmd_version();
1791             } elsif (m/^--new$/) {
1792                 push @ropts, $_;
1793                 $new_package=1;
1794             } elsif (m/^--(\w+)=(.*)/s &&
1795                      ($om = $opts_opt_map{$1}) &&
1796                      length $om->[0]) {
1797                 push @ropts, $_;
1798                 $om->[0] = $2;
1799             } elsif (m/^--(\w+):(.*)/s &&
1800                      !$opts_opt_cmdonly{$1} &&
1801                      ($om = $opts_opt_map{$1})) {
1802                 push @ropts, $_;
1803                 push @$om, $2;
1804             } elsif (m/^--existing-package=(.*)/s) {
1805                 push @ropts, $_;
1806                 $existing_package = $1;
1807             } elsif (m/^--initiator-tempdir=(.*)/s) {
1808                 $initiator_tempdir = $1;
1809                 $initiator_tempdir =~ m#^/# or
1810                     badusage "--initiator-tempdir must be used specify an".
1811                         " absolute, not relative, directory."
1812             } elsif (m/^--distro=(.*)/s) {
1813                 push @ropts, $_;
1814                 $idistro = $1;
1815             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1816                 push @ropts, $_;
1817                 $cleanmode = $1;
1818             } elsif (m/^--clean=(.*)$/s) {
1819                 badusage "unknown cleaning mode \`$1'";
1820             } elsif (m/^--ignore-dirty$/s) {
1821                 push @ropts, $_;
1822                 $ignoredirty = 1;
1823             } elsif (m/^--no-quilt-fixup$/s) {
1824                 push @ropts, $_;
1825                 $noquilt = 1;
1826             } else {
1827                 badusage "unknown long option \`$_'";
1828             }
1829         } else {
1830             while (m/^-./s) {
1831                 if (s/^-n/-/) {
1832                     push @ropts, $&;
1833                     $dryrun_level=2;
1834                 } elsif (s/^-L/-/) {
1835                     push @ropts, $&;
1836                     $dryrun_level=1;
1837                 } elsif (s/^-h/-/) {
1838                     cmd_help();
1839                 } elsif (s/^-D/-/) {
1840                     push @ropts, $&;
1841                     open DEBUG, ">&STDERR" or die $!;
1842                     autoflush DEBUG 1;
1843                     $debug++;
1844                 } elsif (s/^-N/-/) {
1845                     push @ropts, $&;
1846                     $new_package=1;
1847                 } elsif (m/^-[vm]/) {
1848                     push @ropts, $&;
1849                     push @changesopts, $_;
1850                     $_ = '';
1851                 } elsif (s/^-c(.*=.*)//s) {
1852                     push @ropts, $&;
1853                     push @git, '-c', $1;
1854                 } elsif (s/^-d(.*)//s) {
1855                     push @ropts, $&;
1856                     $idistro = $1;
1857                 } elsif (s/^-C(.*)//s) {
1858                     push @ropts, $&;
1859                     $changesfile = $1;
1860                 } elsif (s/^-k(.*)//s) {
1861                     $keyid=$1;
1862                 } elsif (s/^-wn//s) {
1863                     push @ropts, $&;
1864                     $cleanmode = 'none';
1865                 } elsif (s/^-wg//s) {
1866                     push @ropts, $&;
1867                     $cleanmode = 'git';
1868                 } elsif (s/^-wd//s) {
1869                     push @ropts, $&;
1870                     $cleanmode = 'dpkg-source';
1871                 } else {
1872                     badusage "unknown short option \`$_'";
1873                 }
1874             }
1875         }
1876     }
1877 }
1878
1879 if ($ENV{$fakeeditorenv}) {
1880     quilt_fixup_editor();
1881 }
1882
1883 delete $ENV{'DGET_UNPACK'};
1884
1885 parseopts();
1886 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
1887 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
1888     if $dryrun_level == 1;
1889 if (!@ARGV) {
1890     print STDERR $helpmsg or die $!;
1891     exit 8;
1892 }
1893 my $cmd = shift @ARGV;
1894 $cmd =~ y/-/_/;
1895 { no strict qw(refs); &{"cmd_$cmd"}(); }