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