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