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