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