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