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