chiark / gitweb /
When cloning, set up a remote `vcs-git' from the package's Vcs-Git (and put an approp...
[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 use Digest::SHA;
33
34 our $our_version = 'UNRELEASED'; ###substituted###
35
36 our $isuite = 'unstable';
37 our $idistro;
38 our $package;
39 our @ropts;
40
41 our $sign = 1;
42 our $dryrun_level = 0;
43 our $changesfile;
44 our $buildproductsdir = '..';
45 our $new_package = 0;
46 our $ignoredirty = 0;
47 our $noquilt = 0;
48 our $rmonerror = 1;
49 our $existing_package = 'dpkg';
50 our $cleanmode = 'dpkg-source';
51 our $changes_since_version;
52 our $we_are_responder;
53 our $initiator_tempdir;
54
55 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
56
57 our $suite_re = '[-+.0-9a-z]+';
58
59 our (@git) = qw(git);
60 our (@dget) = qw(dget);
61 our (@curl) = qw(curl -f);
62 our (@dput) = qw(dput);
63 our (@debsign) = qw(debsign);
64 our (@gpg) = qw(gpg);
65 our (@sbuild) = qw(sbuild -A);
66 our (@ssh) = 'ssh';
67 our (@dgit) = qw(dgit);
68 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
69 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
70 our (@dpkggenchanges) = qw(dpkg-genchanges);
71 our (@mergechanges) = qw(mergechanges -f);
72 our (@changesopts) = ('');
73
74 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
75                      'curl' => \@curl,
76                      'dput' => \@dput,
77                      'debsign' => \@debsign,
78                      'gpg' => \@gpg,
79                      'sbuild' => \@sbuild,
80                      'ssh' => \@ssh,
81                      'dgit' => \@dgit,
82                      'dpkg-source' => \@dpkgsource,
83                      'dpkg-buildpackage' => \@dpkgbuildpackage,
84                      'dpkg-genchanges' => \@dpkggenchanges,
85                      'ch' => \@changesopts,
86                      'mergechanges' => \@mergechanges);
87
88 our %opts_opt_cmdonly = ('gpg' => 1);
89
90 our $keyid;
91
92 our $debug = 0;
93 open DEBUG, ">/dev/null" or die $!;
94
95 autoflush STDOUT 1;
96
97 our $remotename = 'dgit';
98 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
99 our $branchprefix = 'dgit';
100 our $csuite;
101
102 sub lbranch () { return "$branchprefix/$csuite"; }
103 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
104 sub lref () { return "refs/heads/".lbranch(); }
105 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
106 sub rrref () { return "refs/$branchprefix/$csuite"; }
107 sub debiantag ($) { 
108     my ($v) = @_;
109     $v =~ y/~:/_%/;
110     return "debian/$v";
111 }
112
113 sub stripepoch ($) {
114     my ($vsn) = @_;
115     $vsn =~ s/^\d+\://;
116     return $vsn;
117 }
118
119 sub dscfn ($) {
120     my ($vsn) = @_;
121     return "${package}_".(stripepoch $vsn).".dsc";
122 }
123
124 our $us = 'dgit';
125 our $debugprefix = '';
126
127 our @end;
128 END { 
129     local ($?);
130     foreach my $f (@end) {
131         eval { $f->(); };
132         warn "$us: cleanup: $@" if length $@;
133     }
134 };
135
136 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
137
138 sub fail { 
139     die $us.($we_are_responder ? " (build host)" : "").": @_\n";
140 }
141
142 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
143
144 sub no_such_package () {
145     print STDERR "$us: package $package does not exist in suite $isuite\n";
146     exit 4;
147 }
148
149 sub fetchspec () {
150     local $csuite = '*';
151     return  "+".rrref().":".lrref();
152 }
153
154 sub changedir ($) {
155     my ($newdir) = @_;
156     printdebug "CD $newdir\n";
157     chdir $newdir or die "chdir: $newdir: $!";
158 }
159
160 #---------- remote protocol support, common ----------
161
162 # remote push initiator/responder protocol:
163 #  < dgit-remote-push-ready [optional extra info ignored by old initiators]
164 #
165 #  > file parsed-changelog
166 #  [indicates that output of dpkg-parsechangelog follows]
167 #  > data-block NBYTES
168 #  > [NBYTES bytes of data (no newline)]
169 #  [maybe some more blocks]
170 #  > data-end
171 #
172 #  > file dsc
173 #  [etc]
174 #
175 #  > file changes
176 #  [etc]
177 #
178 #  > param head HEAD
179 #
180 #  > want signed-tag
181 #  [indicates that signed tag is wanted]
182 #  < data-block NBYTES
183 #  < [NBYTES bytes of data (no newline)]
184 #  [maybe some more blocks]
185 #  < data-end
186 #  < files-end
187 #
188 #  > want signed-dsc-changes
189 #  < data-block NBYTES    [transfer of signed dsc]
190 #  [etc]
191 #  < data-block NBYTES    [transfer of signed changes]
192 #  [etc]
193 #  < files-end
194 #
195 #  > complete
196
197 sub badproto ($$) {
198     my ($fh, $m) = @_;
199     fail "connection lost: $!" if $fh->error;
200     fail "protocol violation; $m not expected";
201 }
202
203 sub protocol_expect (&$) {
204     my ($match, $fh) = @_;
205     local $_;
206     $_ = <$fh>;
207     defined && chomp or badproto $fh, "eof";
208     if (wantarray) {
209         my @r = &$match;
210         return @r if @r;
211     } else {
212         my $r = &$match;
213         return $r if $r;
214     }
215     badproto $fh, "\`$_'";
216 }
217
218 sub protocol_send_file ($$) {
219     my ($fh, $ourfn) = @_;
220     open PF, "<", $ourfn or die "$ourfn: $!";
221     for (;;) {
222         my $d;
223         my $got = read PF, $d, 65536;
224         die "$ourfn: $!" unless defined $got;
225         last if !$got;
226         print $fh "data-block ".length($d)."\n" or die $!;
227         print $fh $d or die $!;
228     }
229     PF->error and die "$ourfn $!";
230     print $fh "data-end\n" or die $!;
231     close PF;
232 }
233
234 sub protocol_read_bytes ($$) {
235     my ($fh, $nbytes) = @_;
236     $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
237     my $d;
238     my $got = read $fh, $d, $nbytes;
239     $got==$nbytes or badproto $fh, "eof during data block";
240     return $d;
241 }
242
243 sub protocol_receive_file ($$) {
244     my ($fh, $ourfn) = @_;
245     printdebug "() $ourfn\n";
246     open PF, ">", $ourfn or die "$ourfn: $!";
247     for (;;) {
248         my ($y,$l) = protocol_expect {
249             m/^data-block (.*)$/ ? (1,$1) :
250             m/^data-end$/ ? (0,) :
251             ();
252         } $fh;
253         last unless $y;
254         my $d = protocol_read_bytes $fh, $l;
255         print PF $d or die $!;
256     }
257     close PF or die $!;
258 }
259
260 #---------- remote protocol support, responder ----------
261
262 sub responder_send_command ($) {
263     my ($command) = @_;
264     return unless $we_are_responder;
265     # called even without $we_are_responder
266     printdebug ">> $command\n";
267     print PO $command, "\n" or die $!;
268 }    
269
270 sub responder_send_file ($$) {
271     my ($keyword, $ourfn) = @_;
272     return unless $we_are_responder;
273     printdebug "]] $keyword $ourfn\n";
274     responder_send_command "file $keyword";
275     protocol_send_file \*PO, $ourfn;
276 }
277
278 sub responder_receive_files ($@) {
279     my ($keyword, @ourfns) = @_;
280     die unless $we_are_responder;
281     printdebug "[[ $keyword @ourfns\n";
282     responder_send_command "want $keyword";
283     foreach my $fn (@ourfns) {
284         protocol_receive_file \*PI, $fn;
285     }
286     printdebug "[[\$\n";
287     protocol_expect { m/^files-end$/ } \*PI;
288 }
289
290 #---------- remote protocol support, initiator ----------
291
292 sub initiator_expect (&) {
293     my ($match) = @_;
294     protocol_expect { &$match } \*RO;
295 }
296
297 #---------- end remote code ----------
298
299 sub progress {
300     if ($we_are_responder) {
301         my $m = join '', @_;
302         responder_send_command "progress ".length($m) or die $!;
303         print PO $m or die $!;
304     } else {
305         print @_, "\n";
306     }
307 }
308
309 our $ua;
310
311 sub url_get {
312     if (!$ua) {
313         $ua = LWP::UserAgent->new();
314         $ua->env_proxy;
315     }
316     my $what = $_[$#_];
317     progress "downloading $what...";
318     my $r = $ua->get(@_) or die $!;
319     return undef if $r->code == 404;
320     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
321     return $r->decoded_content(charset => 'none');
322 }
323
324 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
325
326 sub shellquote {
327     my @out;
328     local $_;
329     foreach my $a (@_) {
330         $_ = $a;
331         if (m{[^-=_./0-9a-z]}i) {
332             s{['\\]}{'\\$&'}g;
333             push @out, "'$_'";
334         } else {
335             push @out, $_;
336         }
337     }
338     return join ' ', @out;
339 }
340
341 sub printcmd {
342     my $fh = shift @_;
343     my $intro = shift @_;
344     print $fh $intro," " or die $!;
345     print $fh shellquote @_ or die $!;
346     print $fh "\n" or die $!;
347 }
348
349 sub failedcmd {
350     { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
351     if ($!) {
352         fail "failed to fork/exec: $!";
353     } elsif (!($? & 0xff)) {
354         fail "subprocess failed with error exit status ".($?>>8);
355     } elsif ($?) {
356         fail "subprocess crashed (wait status $?)";
357     } else {
358         fail "subprocess produced invalid output";
359     }
360 }
361
362 sub runcmd {
363     printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
364     $!=0; $?=0;
365     failedcmd @_ if system @_;
366 }
367
368 sub act_local () { return $dryrun_level <= 1; }
369 sub act_scary () { return !$dryrun_level; }
370
371 sub printdone {
372     if (!$dryrun_level) {
373         progress "dgit ok: @_";
374     } else {
375         progress "would be ok: @_ (but dry run only)";
376     }
377 }
378
379 sub cmdoutput_errok {
380     die Dumper(\@_)." ?" if grep { !defined } @_;
381     printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
382     open P, "-|", @_ or die $!;
383     my $d;
384     $!=0; $?=0;
385     { local $/ = undef; $d = <P>; }
386     die $! if P->error;
387     if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
388     chomp $d;
389     $d =~ m/^.*/;
390     printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
391     return $d;
392 }
393
394 sub cmdoutput {
395     my $d = cmdoutput_errok @_;
396     defined $d or failedcmd @_;
397     return $d;
398 }
399
400 sub dryrun_report {
401     printcmd(\*STDERR,$debugprefix."#",@_);
402 }
403
404 sub runcmd_ordryrun {
405     if (act_scary()) {
406         runcmd @_;
407     } else {
408         dryrun_report @_;
409     }
410 }
411
412 sub runcmd_ordryrun_local {
413     if (act_local()) {
414         runcmd @_;
415     } else {
416         dryrun_report @_;
417     }
418 }
419
420 sub shell_cmd {
421     my ($first_shell, @cmd) = @_;
422     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
423 }
424
425 our $helpmsg = <<END;
426 main usages:
427   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
428   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
429   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
430   dgit [dgit-opts] push [dgit-opts] [suite]
431   dgit [dgit-opts] rpush build-host:build-dir ...
432 important dgit options:
433   -k<keyid>           sign tag and package with <keyid> instead of default
434   --dry-run -n        do not change anything, but go through the motions
435   --damp-run -L       like --dry-run but make local changes, without signing
436   --new -N            allow introducing a new package
437   --debug -D          increase debug level
438   -c<name>=<value>    set git config option (used directly by dgit too)
439 END
440
441 our $later_warning_msg = <<END;
442 Perhaps the upload is stuck in incoming.  Using the version from git.
443 END
444
445 sub badusage {
446     print STDERR "$us: @_\n", $helpmsg or die $!;
447     exit 8;
448 }
449
450 sub nextarg {
451     @ARGV or badusage "too few arguments";
452     return scalar shift @ARGV;
453 }
454
455 sub cmd_help () {
456     print $helpmsg or die $!;
457     exit 0;
458 }
459
460 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
461
462 our %defcfg = ('dgit.default.distro' => 'debian',
463                'dgit.default.username' => '',
464                'dgit.default.archive-query-default-component' => 'main',
465                'dgit.default.ssh' => 'ssh',
466                'dgit-distro.debian.git-host' => 'git.debian.org',
467                'dgit-distro.debian.git-proto' => 'git+ssh://',
468                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
469                'dgit-distro.debian.git-check' => 'ssh-cmd',
470                'dgit-distro.debian.git-create' => 'ssh-cmd',
471                'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
472                'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
473                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
474                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
475  'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
476  'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
477                'dgit-distro.ubuntu.git-check' => 'false',
478  'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
479                'dgit-distro.test-dummy.ssh' => "$td/ssh",
480                'dgit-distro.test-dummy.username' => "alice",
481                'dgit-distro.test-dummy.git-check' => "ssh-cmd",
482                'dgit-distro.test-dummy.git-create' => "ssh-cmd",
483                'dgit-distro.test-dummy.git-url' => "$td/git",
484                'dgit-distro.test-dummy.git-host' => "git",
485                'dgit-distro.test-dummy.git-path' => "$td/git",
486                'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
487                'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
488                'dgit-distro.test-dummy.upload-host' => 'test-dummy',
489                );
490
491 sub cfg {
492     foreach my $c (@_) {
493         return undef if $c =~ /RETURN-UNDEF/;
494         my @cmd = (@git, qw(config --), $c);
495         my $v;
496         {
497             local ($debug) = $debug-1;
498             $v = cmdoutput_errok @cmd;
499         };
500         if ($?==0) {
501             return $v;
502         } elsif ($?!=256) {
503             failedcmd @cmd;
504         }
505         my $dv = $defcfg{$c};
506         return $dv if defined $dv;
507     }
508     badcfg "need value for one of: @_\n".
509         "$us: distro or suite appears not to be (properly) supported";
510 }
511
512 sub access_basedistro () {
513     if (defined $idistro) {
514         return cfg("dgit-distro.basedistro.distro",
515                    "dgit-suite.$isuite.distro",
516                    'RETURN-UNDEF') // $idistro;
517     } else {    
518         return cfg("dgit-suite.$isuite.distro",
519                    "dgit.default.distro");
520     }
521 }
522
523 sub access_quirk () {
524     # returns (quirk name, distro to use instead, quirk-specific info)
525     my $basedistro = access_basedistro();
526     my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
527                               'RETURN-UNDEF');
528     if (defined $backports_quirk) {
529         my $re = $backports_quirk;
530         $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
531         $re =~ s/\*/.*/g;
532         $re =~ s/\%/([-0-9a-z_]+)/
533             or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
534         if ($isuite =~ m/^$re$/) {
535             return ('backports',"$basedistro-backports",$1);
536         }
537     }
538     return ('none',$basedistro);
539 }
540
541 sub access_distro () {
542     return (access_quirk())[1];
543 }
544
545 sub access_cfg (@) {
546     my (@keys) = @_;
547     my $basedistro = access_basedistro();
548     my $distro = $idistro || access_distro();
549     my $value = cfg(map {
550         ("dgit-distro.$distro.$_",
551          "dgit-distro.$basedistro.$_",
552          "dgit.default.$_")
553                     } @keys);
554     return $value;
555 }
556
557 sub string_to_ssh ($) {
558     my ($spec) = @_;
559     if ($spec =~ m/\s/) {
560         return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
561     } else {
562         return ($spec);
563     }
564 }
565
566 sub access_cfg_ssh () {
567     my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
568     if (!defined $gitssh) {
569         return @ssh;
570     } else {
571         return string_to_ssh $gitssh;
572     }
573 }
574
575 sub access_someuserhost ($) {
576     my ($some) = @_;
577     my $user = access_cfg("$some-user",'username');
578     my $host = access_cfg("$some-host");
579     return length($user) ? "$user\@$host" : $host;
580 }
581
582 sub access_gituserhost () {
583     return access_someuserhost('git');
584 }
585
586 sub access_giturl () {
587     my $url = access_cfg('git-url','RETURN-UNDEF');
588     if (!defined $url) {
589         $url =
590             access_cfg('git-proto').
591             access_gituserhost().
592             access_cfg('git-path');
593     }
594     return "$url/$package.git";
595 }              
596
597 sub parsecontrolfh ($$@) {
598     my ($fh, $desc, @opts) = @_;
599     my %opts = ('name' => $desc, @opts);
600     my $c = Dpkg::Control::Hash->new(%opts);
601     $c->parse($fh) or die "parsing of $desc failed";
602     return $c;
603 }
604
605 sub parsecontrol {
606     my ($file, $desc) = @_;
607     my $fh = new IO::Handle;
608     open $fh, '<', $file or die "$file: $!";
609     my $c = parsecontrolfh($fh,$desc);
610     $fh->error and die $!;
611     close $fh;
612     return $c;
613 }
614
615 sub getfield ($$) {
616     my ($dctrl,$field) = @_;
617     my $v = $dctrl->{$field};
618     return $v if defined $v;
619     fail "missing field $field in ".$v->get_option('name');
620 }
621
622 sub parsechangelog {
623     my $c = Dpkg::Control::Hash->new();
624     my $p = new IO::Handle;
625     my @cmd = (qw(dpkg-parsechangelog), @_);
626     open $p, '-|', @cmd or die $!;
627     $c->parse($p);
628     $?=0; $!=0; close $p or failedcmd @cmd;
629     return $c;
630 }
631
632 sub git_get_ref ($) {
633     my ($refname) = @_;
634     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
635     if (!defined $got) {
636         $?==256 or fail "git show-ref failed (status $?)";
637         printdebug "ref $refname= [show-ref exited 1]\n";
638         return '';
639     }
640     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
641         printdebug "ref $refname=$1\n";
642         return $1;
643     } else {
644         printdebug "ref $refname= [no match]\n";
645         return '';
646     }
647 }
648
649 sub must_getcwd () {
650     my $d = getcwd();
651     defined $d or fail "getcwd failed: $!";
652     return $d;
653 }
654
655 our %rmad;
656
657 sub archive_query ($) {
658     my ($method) = @_;
659     my $query = access_cfg('archive-query','RETURN-UNDEF');
660     if (!defined $query) {
661         my $distro = access_basedistro();
662         if ($distro eq 'debian') {
663             $query = "sshpsql:".
664                 access_someuserhost('sshpsql').':'.
665                 access_cfg('sshpsql-dbname');
666         } else {
667             $query = "madison:$distro";
668         }
669     }
670     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
671     my $proto = $1;
672     my $data = $'; #';
673     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
674 }
675
676 sub pool_dsc_subpath ($$) {
677     my ($vsn,$component) = @_; # $package is implict arg
678     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
679     return "/pool/$component/$prefix/$package/".dscfn($vsn);
680 }
681
682 sub archive_query_madison ($$) {
683     my ($proto,$data) = @_;
684     die unless $proto eq 'madison';
685     $rmad{$package} ||= cmdoutput
686         qw(rmadison -asource),"-s$isuite","-u$data",$package;
687     my $rmad = $rmad{$package};
688     return madison_parse($rmad);
689 }
690
691 sub madison_parse ($) {
692     my ($rmad) = @_;
693     my @out;
694     foreach my $l (split /\n/, $rmad) {
695         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
696                   \s*( [^ \t|]+ )\s* \|
697                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
698                   \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
699         $1 eq $package or die "$rmad $package ?";
700         my $vsn = $2;
701         my $newsuite = $3;
702         my $component;
703         if (defined $4) {
704             $component = $4;
705         } else {
706             $component = access_cfg('archive-query-default-component');
707         }
708         $5 eq 'source' or die "$rmad ?";
709         push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
710     }
711     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
712 }
713
714 sub canonicalise_suite_madison ($$) {
715     # madison canonicalises for us
716     my @r = archive_query_madison($_[0],$_[1]);
717     @r or fail
718         "unable to canonicalise suite using package $package".
719         " which does not appear to exist in suite $isuite;".
720         " --existing-package may help";
721     return $r[0][2];
722 }
723
724 sub sshpsql ($$) {
725     my ($data,$sql) = @_;
726     $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
727     my ($userhost,$dbname) = ($`,$'); #';
728     my @rows;
729     my @cmd = (access_cfg_ssh, $userhost,
730                "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
731     printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
732     open P, "-|", @cmd or die $!;
733     while (<P>) {
734         chomp or die;
735         printdebug("$debugprefix>|$_|\n");
736         push @rows, $_;
737     }
738     $!=0; $?=0; close P or failedcmd @cmd;
739     @rows or die;
740     my $nrows = pop @rows;
741     $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
742     @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
743     @rows = map { [ split /\|/, $_ ] } @rows;
744     my $ncols = scalar @{ shift @rows };
745     die if grep { scalar @$_ != $ncols } @rows;
746     return @rows;
747 }
748
749 sub sql_injection_check {
750     foreach (@_) { die "$_ $& ?" if m/[']/; }
751 }
752
753 sub archive_query_sshpsql ($$) {
754     my ($proto,$data) = @_;
755     sql_injection_check $isuite, $package;
756     my @rows = sshpsql($data, <<END);
757         SELECT source.version, component.name, files.filename, files.sha256sum
758           FROM source
759           JOIN src_associations ON source.id = src_associations.source
760           JOIN suite ON suite.id = src_associations.suite
761           JOIN dsc_files ON dsc_files.source = source.id
762           JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
763           JOIN component ON component.id = files_archive_map.component_id
764           JOIN files ON files.id = dsc_files.file
765          WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
766            AND source.source='$package'
767            AND files.filename LIKE '%.dsc';
768 END
769     @rows = sort { -version_compare_string($a->[0],$b->[0]) } @rows;
770     my $digester = Digest::SHA->new(256);
771     @rows = map {
772         my ($vsn,$component,$filename,$sha256sum) = @$_;
773         [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
774     } @rows;
775     return @rows;
776 }
777
778 sub canonicalise_suite_sshpsql ($$) {
779     my ($proto,$data) = @_;
780     sql_injection_check $isuite;
781     my @rows = sshpsql($data, <<END);
782         SELECT suite.codename
783           FROM suite where suite_name='$isuite' or codename='$isuite';
784 END
785     @rows = map { $_->[0] } @rows;
786     fail "unknown suite $isuite" unless @rows;
787     die "ambiguous $isuite: @rows ?" if @rows>1;
788     return $rows[0];
789 }
790
791 sub canonicalise_suite_dummycat ($$) {
792     my ($proto,$data) = @_;
793     my $dpath = "$data/suite.$isuite";
794     if (!open C, "<", $dpath) {
795         $!==ENOENT or die "$dpath: $!";
796         printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
797         return $isuite;
798     }
799     $!=0; $_ = <C>;
800     chomp or die "$dpath: $!";
801     close C;
802     printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
803     return $_;
804 }
805
806 sub archive_query_dummycat ($$) {
807     my ($proto,$data) = @_;
808     canonicalise_suite();
809     my $dpath = "$data/package.$csuite.$package";
810     if (!open C, "<", $dpath) {
811         $!==ENOENT or die "$dpath: $!";
812         printdebug "dummycat query $csuite $package $dpath ENOENT\n";
813         return ();
814     }
815     my @rows;
816     while (<C>) {
817         next if m/^\#/;
818         next unless m/\S/;
819         die unless chomp;
820         printdebug "dummycat query $csuite $package $dpath | $_\n";
821         my @row = split /\s+/, $_;
822         @row==2 or die "$dpath: $_ ?";
823         push @rows, \@row;
824     }
825     C->error and die "$dpath: $!";
826     close C;
827     return sort { -version_compare_string($a->[0],$b->[0]); } @rows;
828 }
829
830 sub canonicalise_suite () {
831     return if defined $csuite;
832     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
833     $csuite = archive_query('canonicalise_suite');
834     if ($isuite ne $csuite) {
835         progress "canonical suite name for $isuite is $csuite";
836     }
837 }
838
839 sub get_archive_dsc () {
840     canonicalise_suite();
841     my @vsns = archive_query('archive_query');
842     foreach my $vinfo (@vsns) {
843         my ($vsn,$subpath,$digester,$digest) = @$vinfo;
844         $dscurl = access_cfg('mirror').$subpath;
845         $dscdata = url_get($dscurl);
846         if (!$dscdata) {
847             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
848             next;
849         }
850         if ($digester) {
851             $digester->reset();
852             $digester->add($dscdata);
853             my $got = $digester->hexdigest();
854             $got eq $digest or
855                 fail "$dscurl has hash $got but".
856                     " archive told us to expect $digest";
857         }
858         my $dscfh = new IO::File \$dscdata, '<' or die $!;
859         printdebug Dumper($dscdata) if $debug>1;
860         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
861         printdebug Dumper($dsc) if $debug>1;
862         my $fmt = getfield $dsc, 'Format';
863         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
864         $dsc_checked = !!$digester;
865         return;
866     }
867     $dsc = undef;
868 }
869
870 sub check_for_git () {
871     # returns 0 or 1
872     my $how = access_cfg('git-check');
873     if ($how eq 'ssh-cmd') {
874         my @cmd =
875             (access_cfg_ssh, access_gituserhost(),
876              " set -e; cd ".access_cfg('git-path').";".
877              " if test -d $package.git; then echo 1; else echo 0; fi");
878         my $r= cmdoutput @cmd;
879         failedcmd @cmd unless $r =~ m/^[01]$/;
880         return $r+0;
881     } elsif ($how eq 'true') {
882         return 1;
883     } elsif ($how eq 'false') {
884         return 0;
885     } else {
886         badcfg "unknown git-check \`$how'";
887     }
888 }
889
890 sub create_remote_git_repo () {
891     my $how = access_cfg('git-create');
892     if ($how eq 'ssh-cmd') {
893         runcmd_ordryrun
894             (access_cfg_ssh, access_gituserhost(),
895              "set -e; cd ".access_cfg('git-path').";".
896              " cp -a _template $package.git");
897     } elsif ($how eq 'true') {
898         # nothing to do
899     } else {
900         badcfg "unknown git-create \`$how'";
901     }
902 }
903
904 our ($dsc_hash,$lastpush_hash);
905
906 our $ud = '.git/dgit/unpack';
907
908 sub prep_ud () {
909     rmtree($ud);
910     mkpath '.git/dgit';
911     mkdir $ud or die $!;
912 }
913
914 sub mktree_in_ud_from_only_subdir () {
915     # changes into the subdir
916     my (@dirs) = <*/.>;
917     die unless @dirs==1;
918     $dirs[0] =~ m#^([^/]+)/\.$# or die;
919     my $dir = $1;
920     changedir $dir;
921     fail "source package contains .git directory" if stat '.git';
922     die $! unless $!==&ENOENT;
923     runcmd qw(git init -q);
924     rmtree('.git/objects');
925     symlink '../../../../objects','.git/objects' or die $!;
926     runcmd @git, qw(add -Af);
927     my $tree = cmdoutput @git, qw(write-tree);
928     $tree =~ m/^\w+$/ or die "$tree ?";
929     return ($tree,$dir);
930 }
931
932 sub dsc_files_info () {
933     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
934                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
935                        ['Files',           'Digest::MD5', 'new()']) {
936         my ($fname, $module, $method) = @$csumi;
937         my $field = $dsc->{$fname};
938         next unless defined $field;
939         eval "use $module; 1;" or die $@;
940         my @out;
941         foreach (split /\n/, $field) {
942             next unless m/\S/;
943             m/^(\w+) (\d+) (\S+)$/ or
944                 fail "could not parse .dsc $fname line \`$_'";
945             my $digester = eval "$module"."->$method;" or die $@;
946             push @out, {
947                 Hash => $1,
948                 Bytes => $2,
949                 Filename => $3,
950                 Digester => $digester,
951             };
952         }
953         return @out;
954     }
955     fail "missing any supported Checksums-* or Files field in ".
956         $dsc->get_option('name');
957 }
958
959 sub dsc_files () {
960     map { $_->{Filename} } dsc_files_info();
961 }
962
963 sub is_orig_file ($) {
964     local ($_) = @_;
965     m/\.orig(?:-\w+)?\.tar\.\w+$/;
966 }
967
968 sub make_commit ($) {
969     my ($file) = @_;
970     return cmdoutput @git, qw(hash-object -w -t commit), $file;
971 }
972
973 sub clogp_authline ($) {
974     my ($clogp) = @_;
975     my $author = getfield $clogp, 'Maintainer';
976     $author =~ s#,.*##ms;
977     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
978     my $authline = "$author $date";
979     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
980         fail "unexpected commit author line format \`$authline'".
981         " (was generated from changelog Maintainer field)";
982     return $authline;
983 }
984
985 sub generate_commit_from_dsc () {
986     prep_ud();
987     changedir $ud;
988
989     foreach my $fi (dsc_files_info()) {
990         my $f = $fi->{Filename};
991         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
992
993         link "../../../$f", $f
994             or $!==&ENOENT
995             or die "$f $!";
996
997         complete_file_from_dsc('.', $fi);
998
999         if (is_orig_file($f)) {
1000             link $f, "../../../../$f"
1001                 or $!==&EEXIST
1002                 or die "$f $!";
1003         }
1004     }
1005
1006     my $dscfn = "$package.dsc";
1007
1008     open D, ">", $dscfn or die "$dscfn: $!";
1009     print D $dscdata or die "$dscfn: $!";
1010     close D or die "$dscfn: $!";
1011     my @cmd = qw(dpkg-source);
1012     push @cmd, '--no-check' if $dsc_checked;
1013     push @cmd, qw(-x --), $dscfn;
1014     runcmd @cmd;
1015
1016     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1017     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1018     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1019     my $authline = clogp_authline $clogp;
1020     my $changes = getfield $clogp, 'Changes';
1021     open C, ">../commit.tmp" or die $!;
1022     print C <<END or die $!;
1023 tree $tree
1024 author $authline
1025 committer $authline
1026
1027 $changes
1028
1029 # imported from the archive
1030 END
1031     close C or die $!;
1032     my $outputhash = make_commit qw(../commit.tmp);
1033     my $cversion = getfield $clogp, 'Version';
1034     progress "synthesised git commit from .dsc $cversion";
1035     if ($lastpush_hash) {
1036         runcmd @git, qw(reset --hard), $lastpush_hash;
1037         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1038         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1039         my $oversion = getfield $oldclogp, 'Version';
1040         my $vcmp =
1041             version_compare_string($oversion, $cversion);
1042         if ($vcmp < 0) {
1043             # git upload/ is earlier vsn than archive, use archive
1044             open C, ">../commit2.tmp" or die $!;
1045             print C <<END or die $!;
1046 tree $tree
1047 parent $lastpush_hash
1048 parent $outputhash
1049 author $authline
1050 committer $authline
1051
1052 Record $package ($cversion) in archive suite $csuite
1053 END
1054             $outputhash = make_commit qw(../commit2.tmp);
1055         } elsif ($vcmp > 0) {
1056             print STDERR <<END or die $!;
1057
1058 Version actually in archive:    $cversion (older)
1059 Last allegedly pushed/uploaded: $oversion (newer or same)
1060 $later_warning_msg
1061 END
1062             $outputhash = $lastpush_hash;
1063         } else {
1064             $outputhash = $lastpush_hash;
1065         }
1066     }
1067     changedir '../../../..';
1068     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1069             'DGIT_ARCHIVE', $outputhash;
1070     cmdoutput @git, qw(log -n2), $outputhash;
1071     # ... gives git a chance to complain if our commit is malformed
1072     rmtree($ud);
1073     return $outputhash;
1074 }
1075
1076 sub complete_file_from_dsc ($$) {
1077     our ($dstdir, $fi) = @_;
1078     # Ensures that we have, in $dir, the file $fi, with the correct
1079     # contents.  (Downloading it from alongside $dscurl if necessary.)
1080
1081     my $f = $fi->{Filename};
1082     my $tf = "$dstdir/$f";
1083     my $downloaded = 0;
1084
1085     if (stat $tf) {
1086         progress "using existing $f";
1087     } else {
1088         die "$tf $!" unless $!==&ENOENT;
1089
1090         my $furl = $dscurl;
1091         $furl =~ s{/[^/]+$}{};
1092         $furl .= "/$f";
1093         die "$f ?" unless $f =~ m/^${package}_/;
1094         die "$f ?" if $f =~ m#/#;
1095         runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1096         next if !act_local();
1097         $downloaded = 1;
1098     }
1099
1100     open F, "<", "$tf" or die "$tf: $!";
1101     $fi->{Digester}->reset();
1102     $fi->{Digester}->addfile(*F);
1103     F->error and die $!;
1104     my $got = $fi->{Digester}->hexdigest();
1105     $got eq $fi->{Hash} or
1106         fail "file $f has hash $got but .dsc".
1107             " demands hash $fi->{Hash} ".
1108             ($downloaded ? "(got wrong file from archive!)"
1109              : "(perhaps you should delete this file?)");
1110 }
1111
1112 sub ensure_we_have_orig () {
1113     foreach my $fi (dsc_files_info()) {
1114         my $f = $fi->{Filename};
1115         next unless is_orig_file($f);
1116         complete_file_from_dsc('..', $fi);
1117     }
1118 }
1119
1120 sub rev_parse ($) {
1121     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1122 }
1123
1124 sub is_fast_fwd ($$) {
1125     my ($ancestor,$child) = @_;
1126     my @cmd = (@git, qw(merge-base), $ancestor, $child);
1127     my $mb = cmdoutput_errok @cmd;
1128     if (defined $mb) {
1129         return rev_parse($mb) eq rev_parse($ancestor);
1130     } else {
1131         $?==256 or failedcmd @cmd;
1132         return 0;
1133     }
1134 }
1135
1136 sub git_fetch_us () {
1137     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1138 }
1139
1140 sub fetch_from_archive () {
1141     # ensures that lrref() is what is actually in the archive,
1142     #  one way or another
1143     get_archive_dsc();
1144
1145     if ($dsc) {
1146         foreach my $field (@ourdscfield) {
1147             $dsc_hash = $dsc->{$field};
1148             last if defined $dsc_hash;
1149         }
1150         if (defined $dsc_hash) {
1151             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1152             $dsc_hash = $&;
1153             progress "last upload to archive specified git hash";
1154         } else {
1155             progress "last upload to archive has NO git hash";
1156         }
1157     } else {
1158         progress "no version available from the archive";
1159     }
1160
1161     $lastpush_hash = git_get_ref(lrref());
1162     printdebug "previous reference hash=$lastpush_hash\n";
1163     my $hash;
1164     if (defined $dsc_hash) {
1165         fail "missing remote git history even though dsc has hash -".
1166             " could not find ref ".lrref().
1167             " (should have been fetched from ".access_giturl()."#".rrref().")"
1168             unless $lastpush_hash;
1169         $hash = $dsc_hash;
1170         ensure_we_have_orig();
1171         if ($dsc_hash eq $lastpush_hash) {
1172         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1173             print STDERR <<END or die $!;
1174
1175 Git commit in archive is behind the last version allegedly pushed/uploaded.
1176 Commit referred to by archive:  $dsc_hash
1177 Last allegedly pushed/uploaded: $lastpush_hash
1178 $later_warning_msg
1179 END
1180             $hash = $lastpush_hash;
1181         } else {
1182             fail "archive's .dsc refers to ".$dsc_hash.
1183                 " but this is an ancestor of ".$lastpush_hash;
1184         }
1185     } elsif ($dsc) {
1186         $hash = generate_commit_from_dsc();
1187     } elsif ($lastpush_hash) {
1188         # only in git, not in the archive yet
1189         $hash = $lastpush_hash;
1190         print STDERR <<END or die $!;
1191
1192 Package not found in the archive, but has allegedly been pushed using dgit.
1193 $later_warning_msg
1194 END
1195     } else {
1196         printdebug "nothing found!\n";
1197         if (defined $skew_warning_vsn) {
1198             print STDERR <<END or die $!;
1199
1200 Warning: relevant archive skew detected.
1201 Archive allegedly contains $skew_warning_vsn
1202 But we were not able to obtain any version from the archive or git.
1203
1204 END
1205         }
1206         return 0;
1207     }
1208     printdebug "current hash=$hash\n";
1209     if ($lastpush_hash) {
1210         fail "not fast forward on last upload branch!".
1211             " (archive's version left in DGIT_ARCHIVE)"
1212             unless is_fast_fwd($lastpush_hash, $hash);
1213     }
1214     if (defined $skew_warning_vsn) {
1215         mkpath '.git/dgit';
1216         printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1217         my $clogf = ".git/dgit/changelog.tmp";
1218         runcmd shell_cmd "exec >$clogf",
1219             @git, qw(cat-file blob), "$hash:debian/changelog";
1220         my $gotclogp = parsechangelog("-l$clogf");
1221         my $got_vsn = getfield $gotclogp, 'Version';
1222         printdebug "SKEW CHECK GOT $got_vsn\n";
1223         if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
1224             print STDERR <<END or die $!;
1225
1226 Warning: archive skew detected.  Using the available version:
1227 Archive allegedly contains    $skew_warning_vsn
1228 We were able to obtain only   $got_vsn
1229
1230 END
1231         }
1232     }
1233     if ($lastpush_hash ne $hash) {
1234         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1235         if (act_local()) {
1236             cmdoutput @upd_cmd;
1237         } else {
1238             dryrun_report @upd_cmd;
1239         }
1240     }
1241     return 1;
1242 }
1243
1244 sub clone ($) {
1245     my ($dstdir) = @_;
1246     canonicalise_suite();
1247     badusage "dry run makes no sense with clone" unless act_local();
1248     mkdir $dstdir or die "$dstdir $!";
1249     changedir $dstdir;
1250     runcmd @git, qw(init -q);
1251     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1252     open H, "> .git/HEAD" or die $!;
1253     print H "ref: ".lref()."\n" or die $!;
1254     close H or die $!;
1255     runcmd @git, qw(remote add), 'origin', access_giturl();
1256     if (check_for_git()) {
1257         progress "fetching existing git history";
1258         git_fetch_us();
1259         runcmd_ordryrun_local @git, qw(fetch origin);
1260     } else {
1261         progress "starting new git history";
1262     }
1263     fetch_from_archive() or no_such_package;
1264     my $vcsgiturl = $dsc->{'Vcs-Git'};
1265     if (length $vcsgiturl) {
1266         runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1267     }
1268     runcmd @git, qw(reset --hard), lrref();
1269     printdone "ready for work in $dstdir";
1270 }
1271
1272 sub fetch () {
1273     if (check_for_git()) {
1274         git_fetch_us();
1275     }
1276     fetch_from_archive() or no_such_package();
1277     printdone "fetched into ".lrref();
1278 }
1279
1280 sub pull () {
1281     fetch();
1282     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1283         lrref();
1284     printdone "fetched to ".lrref()." and merged into HEAD";
1285 }
1286
1287 sub check_not_dirty () {
1288     return if $ignoredirty;
1289     my @cmd = (@git, qw(diff --quiet HEAD));
1290     printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1291     $!=0; $?=0; system @cmd;
1292     return if !$! && !$?;
1293     if (!$! && $?==256) {
1294         fail "working tree is dirty (does not match HEAD)";
1295     } else {
1296         failedcmd @cmd;
1297     }
1298 }
1299
1300 sub commit_quilty_patch () {
1301     my $output = cmdoutput @git, qw(status --porcelain);
1302     my %adds;
1303     foreach my $l (split /\n/, $output) {
1304         next unless $l =~ m/\S/;
1305         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1306             $adds{$1}++;
1307         }
1308     }
1309     if (!%adds) {
1310         progress "nothing quilty to commit, ok.";
1311         return;
1312     }
1313     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1314     my $m = "Commit Debian 3.0 (quilt) metadata";
1315     progress "$m";
1316     runcmd_ordryrun_local @git, qw(commit -m), $m;
1317 }
1318
1319 sub madformat ($) {
1320     my ($format) = @_;
1321     return 0 unless $format eq '3.0 (quilt)';
1322     progress "Format \`$format', urgh";
1323     if ($noquilt) {
1324         progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1325         return 0;
1326     }
1327     return 1;
1328 }
1329
1330 sub push_parse_changelog ($) {
1331     my ($clogpfn) = @_;
1332
1333     my $clogp = Dpkg::Control::Hash->new();
1334     $clogp->load($clogpfn) or die;
1335
1336     $package = getfield $clogp, 'Source';
1337     my $cversion = getfield $clogp, 'Version';
1338     my $tag = debiantag($cversion);
1339     runcmd @git, qw(check-ref-format), $tag;
1340
1341     my $dscfn = dscfn($cversion);
1342
1343     return ($clogp, $cversion, $tag, $dscfn);
1344 }
1345
1346 sub push_parse_dsc ($$$) {
1347     my ($dscfn,$dscfnwhat, $cversion) = @_;
1348     $dsc = parsecontrol($dscfn,$dscfnwhat);
1349     my $dversion = getfield $dsc, 'Version';
1350     my $dscpackage = getfield $dsc, 'Source';
1351     ($dscpackage eq $package && $dversion eq $cversion) or
1352         fail "$dscfn is for $dscpackage $dversion".
1353             " but debian/changelog is for $package $cversion";
1354 }
1355
1356 sub push_mktag ($$$$$$$) {
1357     my ($head,$clogp,$tag,
1358         $dscfn,
1359         $changesfile,$changesfilewhat,
1360         $tfn) = @_;
1361
1362     $dsc->{$ourdscfield[0]} = $head;
1363     $dsc->save("$dscfn.tmp") or die $!;
1364
1365     my $changes = parsecontrol($changesfile,$changesfilewhat);
1366     foreach my $field (qw(Source Distribution Version)) {
1367         $changes->{$field} eq $clogp->{$field} or
1368             fail "changes field $field \`$changes->{$field}'".
1369                 " does not match changelog \`$clogp->{$field}'";
1370     }
1371
1372     my $cversion = getfield $clogp, 'Version';
1373     my $clogsuite = getfield $clogp, 'Distribution';
1374
1375     # We make the git tag by hand because (a) that makes it easier
1376     # to control the "tagger" (b) we can do remote signing
1377     my $authline = clogp_authline $clogp;
1378     open TO, '>', $tfn->('.tmp') or die $!;
1379     print TO <<END or die $!;
1380 object $head
1381 type commit
1382 tag $tag
1383 tagger $authline
1384
1385 $package release $cversion for $clogsuite ($csuite) [dgit]
1386 END
1387     close TO or die $!;
1388
1389     my $tagobjfn = $tfn->('.tmp');
1390     if ($sign) {
1391         if (!defined $keyid) {
1392             $keyid = access_cfg('keyid','RETURN-UNDEF');
1393         }
1394         unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1395         my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1396         push @sign_cmd, qw(-u),$keyid if defined $keyid;
1397         push @sign_cmd, $tfn->('.tmp');
1398         runcmd_ordryrun @sign_cmd;
1399         if (act_scary()) {
1400             $tagobjfn = $tfn->('.signed.tmp');
1401             runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1402                 $tfn->('.tmp'), $tfn->('.tmp.asc');
1403         }
1404     }
1405
1406     return ($tagobjfn);
1407 }
1408
1409 sub sign_changes ($) {
1410     my ($changesfile) = @_;
1411     if ($sign) {
1412         my @debsign_cmd = @debsign;
1413         push @debsign_cmd, "-k$keyid" if defined $keyid;
1414         push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1415         push @debsign_cmd, $changesfile;
1416         runcmd_ordryrun @debsign_cmd;
1417     }
1418 }
1419
1420 sub dopush () {
1421     printdebug "actually entering push\n";
1422     prep_ud();
1423
1424     access_giturl(); # check that success is vaguely likely
1425
1426     my $clogpfn = ".git/dgit/changelog.822.tmp";
1427     runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1428
1429     responder_send_file('parsed-changelog', $clogpfn);
1430
1431     my ($clogp, $cversion, $tag, $dscfn) =
1432         push_parse_changelog("$clogpfn");
1433
1434     my $dscpath = "$buildproductsdir/$dscfn";
1435     stat $dscpath or
1436         fail "looked for .dsc $dscfn, but $!;".
1437             " maybe you forgot to build";
1438
1439     responder_send_file('dsc', $dscpath);
1440
1441     push_parse_dsc($dscpath, $dscfn, $cversion);
1442
1443     my $format = getfield $dsc, 'Format';
1444     printdebug "format $format\n";
1445     if (madformat($format)) {
1446         commit_quilty_patch();
1447     }
1448     check_not_dirty();
1449     changedir $ud;
1450     progress "checking that $dscfn corresponds to HEAD";
1451     runcmd qw(dpkg-source -x --),
1452         $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1453     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1454     changedir '../../../..';
1455     my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1456     my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1457     printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1458     $!=0; $?=0;
1459     my $r = system @diffcmd;
1460     if ($r) {
1461         if ($r==256) {
1462             fail "$dscfn specifies a different tree to your HEAD commit;".
1463                 " perhaps you forgot to build".
1464                 ($diffopt eq '--exit-code' ? "" :
1465                  " (run with -D to see full diff output)");
1466         } else {
1467             failedcmd @diffcmd;
1468         }
1469     }
1470 #fetch from alioth
1471 #do fast forward check and maybe fake merge
1472 #    if (!is_fast_fwd(mainbranch
1473 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1474 #        map { lref($_).":".rref($_) }
1475 #        (uploadbranch());
1476     my $head = rev_parse('HEAD');
1477     if (!$changesfile) {
1478         my $multi = "$buildproductsdir/".
1479             "${package}_".(stripepoch $cversion)."_multi.changes";
1480         if (stat "$multi") {
1481             $changesfile = $multi;
1482         } else {
1483             $!==&ENOENT or die "$multi: $!";
1484             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1485             my @cs = glob "$buildproductsdir/$pat";
1486             fail "failed to find unique changes file".
1487                 " (looked for $pat in $buildproductsdir, or $multi);".
1488                 " perhaps you need to use dgit -C"
1489                 unless @cs==1;
1490             ($changesfile) = @cs;
1491         }
1492     } else {
1493         $changesfile = "$buildproductsdir/$changesfile";
1494     }
1495
1496     responder_send_file('changes',$changesfile);
1497     responder_send_command("param head $head");
1498     responder_send_command("param csuite $csuite");
1499
1500     my $tfn = sub { ".git/dgit/tag$_[0]"; };
1501     my $tagobjfn;
1502
1503     if ($we_are_responder) {
1504         $tagobjfn = $tfn->('.signed.tmp');
1505         responder_receive_files('signed-tag', $tagobjfn);
1506     } else {
1507         $tagobjfn =
1508             push_mktag($head,$clogp,$tag,
1509                        $dscpath,
1510                        $changesfile,$changesfile,
1511                        $tfn);
1512     }
1513
1514     my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1515     runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1516     runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1517     runcmd_ordryrun @git, qw(tag -v --), $tag;
1518
1519     if (!check_for_git()) {
1520         create_remote_git_repo();
1521     }
1522     runcmd_ordryrun @git, qw(push),access_giturl(),
1523         "HEAD:".rrref(), "refs/tags/$tag";
1524     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1525
1526     if ($we_are_responder) {
1527         my $dryrunsuffix = act_local() ? "" : ".tmp";
1528         responder_receive_files('signed-dsc-changes',
1529                                 "$dscpath$dryrunsuffix",
1530                                 "$changesfile$dryrunsuffix");
1531     } else {
1532         if (act_local()) {
1533             rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1534         } else {
1535             progress "[new .dsc left in $dscpath.tmp]";
1536         }
1537         sign_changes $changesfile;
1538     }
1539
1540     my $host = access_cfg('upload-host','RETURN-UNDEF');
1541     my @hostarg = defined($host) ? ($host,) : ();
1542     runcmd_ordryrun @dput, @hostarg, $changesfile;
1543     printdone "pushed and uploaded $cversion";
1544
1545     responder_send_command("complete");
1546 }
1547
1548 sub cmd_clone {
1549     parseopts();
1550     my $dstdir;
1551     badusage "-p is not allowed with clone; specify as argument instead"
1552         if defined $package;
1553     if (@ARGV==1) {
1554         ($package) = @ARGV;
1555     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1556         ($package,$isuite) = @ARGV;
1557     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1558         ($package,$dstdir) = @ARGV;
1559     } elsif (@ARGV==3) {
1560         ($package,$isuite,$dstdir) = @ARGV;
1561     } else {
1562         badusage "incorrect arguments to dgit clone";
1563     }
1564     $dstdir ||= "$package";
1565
1566     if (stat $dstdir) {
1567         fail "$dstdir already exists";
1568     } elsif ($! != &ENOENT) {
1569         die "$dstdir: $!";
1570     }
1571
1572     my $cwd_remove;
1573     if ($rmonerror && !$dryrun_level) {
1574         $cwd_remove= getcwd();
1575         unshift @end, sub { 
1576             return unless defined $cwd_remove;
1577             if (!chdir "$cwd_remove") {
1578                 return if $!==&ENOENT;
1579                 die "chdir $cwd_remove: $!";
1580             }
1581             rmtree($dstdir) or die "remove $dstdir: $!\n";
1582         };
1583     }
1584
1585     clone($dstdir);
1586     $cwd_remove = undef;
1587 }
1588
1589 sub branchsuite () {
1590     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1591     if ($branch =~ m#$lbranch_re#o) {
1592         return $1;
1593     } else {
1594         return undef;
1595     }
1596 }
1597
1598 sub fetchpullargs () {
1599     if (!defined $package) {
1600         my $sourcep = parsecontrol('debian/control','debian/control');
1601         $package = getfield $sourcep, 'Source';
1602     }
1603     if (@ARGV==0) {
1604 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1605         if (!$isuite) {
1606             my $clogp = parsechangelog();
1607             $isuite = getfield $clogp, 'Distribution';
1608         }
1609         canonicalise_suite();
1610         progress "fetching from suite $csuite";
1611     } elsif (@ARGV==1) {
1612         ($isuite) = @ARGV;
1613         canonicalise_suite();
1614     } else {
1615         badusage "incorrect arguments to dgit fetch or dgit pull";
1616     }
1617 }
1618
1619 sub cmd_fetch {
1620     parseopts();
1621     fetchpullargs();
1622     fetch();
1623 }
1624
1625 sub cmd_pull {
1626     parseopts();
1627     fetchpullargs();
1628     pull();
1629 }
1630
1631 sub cmd_push {
1632     parseopts();
1633     badusage "-p is not allowed with dgit push" if defined $package;
1634     check_not_dirty();
1635     my $clogp = parsechangelog();
1636     $package = getfield $clogp, 'Source';
1637     my $specsuite;
1638     if (@ARGV==0) {
1639     } elsif (@ARGV==1) {
1640         ($specsuite) = (@ARGV);
1641     } else {
1642         badusage "incorrect arguments to dgit push";
1643     }
1644     $isuite = getfield $clogp, 'Distribution';
1645     if ($new_package) {
1646         local ($package) = $existing_package; # this is a hack
1647         canonicalise_suite();
1648     }
1649     if (defined $specsuite && $specsuite ne $isuite) {
1650         canonicalise_suite();
1651         $csuite eq $specsuite or
1652             fail "dgit push: changelog specifies $isuite ($csuite)".
1653                 " but command line specifies $specsuite";
1654     }
1655     if (check_for_git()) {
1656         git_fetch_us();
1657     }
1658     if (fetch_from_archive()) {
1659         is_fast_fwd(lrref(), 'HEAD') or
1660             fail "dgit push: HEAD is not a descendant".
1661                 " of the archive's version.\n".
1662                 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1663     } else {
1664         $new_package or
1665             fail "package appears to be new in this suite;".
1666                 " if this is intentional, use --new";
1667     }
1668     dopush();
1669 }
1670
1671 #---------- remote commands' implementation ----------
1672
1673 sub cmd_remote_push_responder {
1674     my ($nrargs) = shift @ARGV;
1675     my (@rargs) = @ARGV[0..$nrargs-1];
1676     @ARGV = @ARGV[$nrargs..$#ARGV];
1677     die unless @rargs;
1678     my ($dir) = @rargs;
1679     $debugprefix = ' ';
1680     $we_are_responder = 1;
1681
1682     open PI, "<&STDIN" or die $!;
1683     open STDIN, "/dev/null" or die $!;
1684     open PO, ">&STDOUT" or die $!;
1685     autoflush PO 1;
1686     open STDOUT, ">&STDERR" or die $!;
1687     autoflush STDOUT 1;
1688
1689     responder_send_command("dgit-remote-push-ready");
1690
1691     changedir $dir;
1692     &cmd_push;
1693 }
1694
1695 our $i_tmp;
1696 our $i_child_pid;
1697
1698 sub i_cleanup {
1699     local ($@);
1700     if ($i_child_pid) {
1701         printdebug "(killing remote child $i_child_pid)\n";
1702         kill 15, $i_child_pid;
1703     }
1704     if (defined $i_tmp && !defined $initiator_tempdir) {
1705         changedir "/";
1706         eval { rmtree $i_tmp; };
1707     }
1708 }
1709
1710 END { i_cleanup(); }
1711
1712 sub i_method {
1713     my ($base,$selector,@args) = @_;
1714     $selector =~ s/\-/_/g;
1715     { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1716 }
1717
1718 sub cmd_rpush {
1719     my $host = nextarg;
1720     my $dir;
1721     if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1722         $host = $1;
1723         $dir = $'; #';
1724     } else {
1725         $dir = nextarg;
1726     }
1727     $dir =~ s{^-}{./-};
1728     my @rargs = ($dir);
1729     my @rdgit;
1730     push @rdgit, @dgit;
1731     push @rdgit, @ropts;
1732     push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1733     push @rdgit, @ARGV;
1734     my @cmd = (@ssh, $host, shellquote @rdgit);
1735     printcmd \*DEBUG,$debugprefix."+",@cmd;
1736
1737     if (defined $initiator_tempdir) {
1738         rmtree $initiator_tempdir;
1739         mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1740         $i_tmp = $initiator_tempdir;
1741     } else {
1742         $i_tmp = tempdir();
1743     }
1744     $i_child_pid = open2(\*RO, \*RI, @cmd);
1745     changedir $i_tmp;
1746     initiator_expect { m/^dgit-remote-push-ready/ };
1747     for (;;) {
1748         my ($icmd,$iargs) = initiator_expect {
1749             m/^(\S+)(?: (.*))?$/;
1750             ($1,$2);
1751         };
1752         i_method "i_resp", $icmd, $iargs;
1753     }
1754 }
1755
1756 sub i_resp_progress ($) {
1757     my ($rhs) = @_;
1758     my $msg = protocol_read_bytes \*RO, $rhs;
1759     progress $msg;
1760 }
1761
1762 sub i_resp_complete {
1763     my $pid = $i_child_pid;
1764     $i_child_pid = undef; # prevents killing some other process with same pid
1765     printdebug "waiting for remote child $pid...\n";
1766     my $got = waitpid $pid, 0;
1767     die $! unless $got == $pid;
1768     die "remote child failed $?" if $?;
1769
1770     i_cleanup();
1771     printdebug "all done\n";
1772     exit 0;
1773 }
1774
1775 sub i_resp_file ($) {
1776     my ($keyword) = @_;
1777     my $localname = i_method "i_localname", $keyword;
1778     my $localpath = "$i_tmp/$localname";
1779     stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1780     protocol_receive_file \*RO, $localpath;
1781     i_method "i_file", $keyword;
1782 }
1783
1784 our %i_param;
1785
1786 sub i_resp_param ($) {
1787     $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1788     $i_param{$1} = $2;
1789 }
1790
1791 our %i_wanted;
1792
1793 sub i_resp_want ($) {
1794     my ($keyword) = @_;
1795     die "$keyword ?" if $i_wanted{$keyword}++;
1796     my @localpaths = i_method "i_want", $keyword;
1797     printdebug "[[  $keyword @localpaths\n";
1798     foreach my $localpath (@localpaths) {
1799         protocol_send_file \*RI, $localpath;
1800     }
1801     print RI "files-end\n" or die $!;
1802 }
1803
1804 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1805
1806 sub i_localname_parsed_changelog {
1807     return "remote-changelog.822";
1808 }
1809 sub i_file_parsed_changelog {
1810     ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1811         push_parse_changelog "$i_tmp/remote-changelog.822";
1812     die if $i_dscfn =~ m#/|^\W#;
1813 }
1814
1815 sub i_localname_dsc {
1816     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1817     return $i_dscfn;
1818 }
1819 sub i_file_dsc { }
1820
1821 sub i_localname_changes {
1822     defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1823     $i_changesfn = $i_dscfn;
1824     $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1825     return $i_changesfn;
1826 }
1827 sub i_file_changes { }
1828
1829 sub i_want_signed_tag {
1830     printdebug Dumper(\%i_param, $i_dscfn);
1831     defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1832         && defined $i_param{'csuite'}
1833         or badproto \*RO, "premature desire for signed-tag";
1834     my $head = $i_param{'head'};
1835     die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1836
1837     die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1838     $csuite = $&;
1839     push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1840
1841     my $tagobjfn =
1842         push_mktag $head, $i_clogp, $i_tag,
1843             $i_dscfn,
1844             $i_changesfn, 'remote changes',
1845             sub { "tag$_[0]"; };
1846
1847     return $tagobjfn;
1848 }
1849
1850 sub i_want_signed_dsc_changes {
1851     rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1852     sign_changes $i_changesfn;
1853     return ($i_dscfn, $i_changesfn);
1854 }
1855
1856 #---------- building etc. ----------
1857
1858 our $version;
1859 our $sourcechanges;
1860 our $dscfn;
1861
1862 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1863
1864 sub build_maybe_quilt_fixup () {
1865     if (!open F, "debian/source/format") {
1866         die $! unless $!==&ENOENT;
1867         return;
1868     }
1869     $_ = <F>;
1870     F->error and die $!;
1871     chomp;
1872     return unless madformat($_);
1873     # sigh
1874     
1875     my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1876     my $problems = cmdoutput @cmd;
1877     if (length $problems) {
1878         print STDERR "problematic files:\n";
1879         print STDERR "  $_\n" foreach split /\n/, $problems;
1880         fail "Cannot do quilt fixup in tree containing ignored files.  ".
1881             "Perhaps your package's clean target is broken, in which".
1882             " case -wg (which says to use git-clean -xdf) may help.";
1883     }
1884
1885     my $clogp = parsechangelog();
1886     my $version = getfield $clogp, 'Version';
1887     my $author = getfield $clogp, 'Maintainer';
1888     my $headref = rev_parse('HEAD');
1889     my $time = time;
1890     my $ncommits = 3;
1891     my $patchname = "auto-$version-$headref-$time";
1892     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1893     mkpath '.git/dgit';
1894     my $descfn = ".git/dgit/quilt-description.tmp";
1895     open O, '>', $descfn or die "$descfn: $!";
1896     $msg =~ s/\n/\n /g;
1897     $msg =~ s/^\s+$/ ./mg;
1898     print O <<END or die $!;
1899 Description: Automatically generated patch ($clogp->{Version})
1900  Last (up to) $ncommits git changes, FYI:
1901  .
1902  $msg
1903 Author: $author
1904
1905 ---
1906
1907 END
1908     close O or die $!;
1909     {
1910         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1911         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1912         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1913         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1914     }
1915
1916     if (!open P, '>>', ".pc/applied-patches") {
1917         $!==&ENOENT or die $!;
1918     } else {
1919         close P;
1920     }
1921
1922     commit_quilty_patch();
1923 }
1924
1925 sub quilt_fixup_editor () {
1926     my $descfn = $ENV{$fakeeditorenv};
1927     my $editing = $ARGV[$#ARGV];
1928     open I1, '<', $descfn or die "$descfn: $!";
1929     open I2, '<', $editing or die "$editing: $!";
1930     unlink $editing or die "$editing: $!";
1931     open O, '>', $editing or die "$editing: $!";
1932     while (<I1>) { print O or die $!; } I1->error and die $!;
1933     my $copying = 0;
1934     while (<I2>) {
1935         $copying ||= m/^\-\-\- /;
1936         next unless $copying;
1937         print O or die $!;
1938     }
1939     I2->error and die $!;
1940     close O or die $1;
1941     exit 0;
1942 }
1943
1944 sub clean_tree () {
1945     if ($cleanmode eq 'dpkg-source') {
1946         runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
1947     } elsif ($cleanmode eq 'git') {
1948         runcmd_ordryrun_local @git, qw(clean -xdf);
1949     } elsif ($cleanmode eq 'none') {
1950     } else {
1951         die "$cleanmode ?";
1952     }
1953 }
1954
1955 sub cmd_clean () {
1956     badusage "clean takes no additional arguments" if @ARGV;
1957     clean_tree();
1958 }
1959
1960 sub build_prep () {
1961     badusage "-p is not allowed when building" if defined $package;
1962     check_not_dirty();
1963     clean_tree();
1964     my $clogp = parsechangelog();
1965     $isuite = getfield $clogp, 'Distribution';
1966     $package = getfield $clogp, 'Source';
1967     $version = getfield $clogp, 'Version';
1968     build_maybe_quilt_fixup();
1969 }
1970
1971 sub changesopts () {
1972     my @opts =@changesopts[1..$#changesopts];
1973     if (!defined $changes_since_version) {
1974         my @vsns = archive_query('archive_query');
1975         my @quirk = access_quirk();
1976         if ($quirk[0] eq 'backports') {
1977             local $isuite = $quirk[2];
1978             local $csuite;
1979             canonicalise_suite();
1980             push @vsns, archive_query('archive_query');
1981         }
1982         if (@vsns) {
1983             @vsns = map { $_->[0] } @vsns;
1984             @vsns = sort { -version_compare_string($a, $b) } @vsns;
1985             $changes_since_version = $vsns[0];
1986             progress "changelog will contain changes since $vsns[0]";
1987         } else {
1988             $changes_since_version = '_';
1989             progress "package seems new, not specifying -v<version>";
1990         }
1991     }
1992     if ($changes_since_version ne '_') {
1993         unshift @opts, "-v$changes_since_version";
1994     }
1995     return @opts;
1996 }
1997
1998 sub cmd_build {
1999     build_prep();
2000     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2001     printdone "build successful\n";
2002 }
2003
2004 sub cmd_git_build {
2005     build_prep();
2006     my @cmd =
2007         (qw(git-buildpackage -us -uc --git-no-sign-tags),
2008          "--git-builder=@dpkgbuildpackage");
2009     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2010         canonicalise_suite();
2011         push @cmd, "--git-debian-branch=".lbranch();
2012     }
2013     push @cmd, changesopts();
2014     runcmd_ordryrun_local @cmd, @ARGV;
2015     printdone "build successful\n";
2016 }
2017
2018 sub build_source {
2019     build_prep();
2020     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2021     $dscfn = dscfn($version);
2022     if ($cleanmode eq 'dpkg-source') {
2023         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2024             changesopts();
2025     } else {
2026         my $pwd = must_getcwd();
2027         my $leafdir = basename $pwd;
2028         changedir "..";
2029         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2030         changedir $pwd;
2031         runcmd_ordryrun_local qw(sh -ec),
2032             'exec >$1; shift; exec "$@"','x',
2033             "../$sourcechanges",
2034             @dpkggenchanges, qw(-S), changesopts();
2035     }
2036 }
2037
2038 sub cmd_build_source {
2039     badusage "build-source takes no additional arguments" if @ARGV;
2040     build_source();
2041     printdone "source built, results in $dscfn and $sourcechanges";
2042 }
2043
2044 sub cmd_sbuild {
2045     build_source();
2046     changedir "..";
2047     my $pat = "${package}_".(stripepoch $version)."_*.changes";
2048     if (act_local()) {
2049         stat $dscfn or fail "$dscfn (in parent directory): $!";
2050         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
2051         foreach my $cf (glob $pat) {
2052             next if $cf eq $sourcechanges;
2053             unlink $cf or fail "remove $cf: $!";
2054         }
2055     }
2056     runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2057     my @changesfiles = glob $pat;
2058     @changesfiles = sort {
2059         ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2060             or $a cmp $b
2061     } @changesfiles;
2062     fail "wrong number of different changes files (@changesfiles)"
2063         unless @changesfiles;
2064     runcmd_ordryrun_local @mergechanges, @changesfiles;
2065     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2066     if (act_local()) {
2067         stat $multichanges or fail "$multichanges: $!";
2068     }
2069     printdone "build successful, results in $multichanges\n" or die $!;
2070 }    
2071
2072 sub cmd_quilt_fixup {
2073     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2074     my $clogp = parsechangelog();
2075     $version = getfield $clogp, 'Version';
2076     build_maybe_quilt_fixup();
2077 }
2078
2079 #---------- argument parsing and main program ----------
2080
2081 sub cmd_version {
2082     print "dgit version $our_version\n" or die $!;
2083     exit 0;
2084 }
2085
2086 sub parseopts () {
2087     my $om;
2088
2089     if (defined $ENV{'DGIT_SSH'}) {
2090         @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2091     } elsif (defined $ENV{'GIT_SSH'}) {
2092         @ssh = ($ENV{'GIT_SSH'});
2093     }
2094
2095     while (@ARGV) {
2096         last unless $ARGV[0] =~ m/^-/;
2097         $_ = shift @ARGV;
2098         last if m/^--?$/;
2099         if (m/^--/) {
2100             if (m/^--dry-run$/) {
2101                 push @ropts, $_;
2102                 $dryrun_level=2;
2103             } elsif (m/^--damp-run$/) {
2104                 push @ropts, $_;
2105                 $dryrun_level=1;
2106             } elsif (m/^--no-sign$/) {
2107                 push @ropts, $_;
2108                 $sign=0;
2109             } elsif (m/^--help$/) {
2110                 cmd_help();
2111             } elsif (m/^--version$/) {
2112                 cmd_version();
2113             } elsif (m/^--new$/) {
2114                 push @ropts, $_;
2115                 $new_package=1;
2116             } elsif (m/^--since-version=([^_]+|_)$/) {
2117                 push @ropts, $_;
2118                 $changes_since_version = $1;
2119             } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2120                      ($om = $opts_opt_map{$1}) &&
2121                      length $om->[0]) {
2122                 push @ropts, $_;
2123                 $om->[0] = $2;
2124             } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2125                      !$opts_opt_cmdonly{$1} &&
2126                      ($om = $opts_opt_map{$1})) {
2127                 push @ropts, $_;
2128                 push @$om, $2;
2129             } elsif (m/^--existing-package=(.*)/s) {
2130                 push @ropts, $_;
2131                 $existing_package = $1;
2132             } elsif (m/^--initiator-tempdir=(.*)/s) {
2133                 $initiator_tempdir = $1;
2134                 $initiator_tempdir =~ m#^/# or
2135                     badusage "--initiator-tempdir must be used specify an".
2136                         " absolute, not relative, directory."
2137             } elsif (m/^--distro=(.*)/s) {
2138                 push @ropts, $_;
2139                 $idistro = $1;
2140             } elsif (m/^--build-products-dir=(.*)/s) {
2141                 push @ropts, $_;
2142                 $buildproductsdir = $1;
2143             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2144                 push @ropts, $_;
2145                 $cleanmode = $1;
2146             } elsif (m/^--clean=(.*)$/s) {
2147                 badusage "unknown cleaning mode \`$1'";
2148             } elsif (m/^--ignore-dirty$/s) {
2149                 push @ropts, $_;
2150                 $ignoredirty = 1;
2151             } elsif (m/^--no-quilt-fixup$/s) {
2152                 push @ropts, $_;
2153                 $noquilt = 1;
2154             } elsif (m/^--no-rm-on-error$/s) {
2155                 push @ropts, $_;
2156                 $rmonerror = 0;
2157             } else {
2158                 badusage "unknown long option \`$_'";
2159             }
2160         } else {
2161             while (m/^-./s) {
2162                 if (s/^-n/-/) {
2163                     push @ropts, $&;
2164                     $dryrun_level=2;
2165                 } elsif (s/^-L/-/) {
2166                     push @ropts, $&;
2167                     $dryrun_level=1;
2168                 } elsif (s/^-h/-/) {
2169                     cmd_help();
2170                 } elsif (s/^-D/-/) {
2171                     push @ropts, $&;
2172                     open DEBUG, ">&STDERR" or die $!;
2173                     autoflush DEBUG 1;
2174                     $debug++;
2175                 } elsif (s/^-N/-/) {
2176                     push @ropts, $&;
2177                     $new_package=1;
2178                 } elsif (s/^-v([^_]+|_)$//s) {
2179                     push @ropts, $&;
2180                     $changes_since_version = $1;
2181                 } elsif (m/^-m/) {
2182                     push @ropts, $&;
2183                     push @changesopts, $_;
2184                     $_ = '';
2185                 } elsif (s/^-c(.*=.*)//s) {
2186                     push @ropts, $&;
2187                     push @git, '-c', $1;
2188                 } elsif (s/^-d(.*)//s) {
2189                     push @ropts, $&;
2190                     $idistro = $1;
2191                 } elsif (s/^-C(.*)//s) {
2192                     push @ropts, $&;
2193                     $changesfile = $1;
2194                     if ($changesfile =~ s#^(.*)/##) {
2195                         $buildproductsdir = $1;
2196                     }
2197                 } elsif (s/^-k(.*)//s) {
2198                     $keyid=$1;
2199                 } elsif (s/^-wn//s) {
2200                     push @ropts, $&;
2201                     $cleanmode = 'none';
2202                 } elsif (s/^-wg//s) {
2203                     push @ropts, $&;
2204                     $cleanmode = 'git';
2205                 } elsif (s/^-wd//s) {
2206                     push @ropts, $&;
2207                     $cleanmode = 'dpkg-source';
2208                 } else {
2209                     badusage "unknown short option \`$_'";
2210                 }
2211             }
2212         }
2213     }
2214 }
2215
2216 if ($ENV{$fakeeditorenv}) {
2217     quilt_fixup_editor();
2218 }
2219
2220 parseopts();
2221 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2222 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2223     if $dryrun_level == 1;
2224 if (!@ARGV) {
2225     print STDERR $helpmsg or die $!;
2226     exit 8;
2227 }
2228 my $cmd = shift @ARGV;
2229 $cmd =~ y/-/_/;
2230
2231 my $fn = ${*::}{"cmd_$cmd"};
2232 $fn or badusage "unknown operation $cmd";
2233 $fn->();