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