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