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