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