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