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