chiark / gitweb /
finalise 0.16
[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::Basename;
28 use Dpkg::Version;
29 use POSIX;
30
31 our $our_version = 'UNRELEASED'; ###substituted###
32
33 our $isuite = 'unstable';
34 our $idistro;
35 our $package;
36
37 our $sign = 1;
38 our $dryrun = 0;
39 our $changesfile;
40 our $new_package = 0;
41 our $ignoredirty = 0;
42 our $noquilt = 0;
43 our $existing_package = 'dpkg';
44 our $cleanmode = 'dpkg-source';
45
46 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
47
48 our (@git) = qw(git);
49 our (@dget) = qw(dget);
50 our (@dput) = qw(dput);
51 our (@debsign) = qw(debsign);
52 our (@sbuild) = qw(sbuild -A);
53 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
54 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
55 our (@dpkggenchanges) = qw(dpkg-genchanges);
56 our (@mergechanges) = qw(mergechanges -f);
57 our (@changesopts) = ('');
58
59 our %opts_opt_map = ('dget' => \@dget,
60                      'dput' => \@dput,
61                      'debsign' => \@debsign,
62                      'sbuild' => \@sbuild,
63                      'dpkg-source' => \@dpkgsource,
64                      'dpkg-buildpackage' => \@dpkgbuildpackage,
65                      'dpkg-genchanges' => \@dpkggenchanges,
66                      'ch' => \@changesopts,
67                      'mergechanges' => \@mergechanges);
68
69 our $keyid;
70
71 our $debug = 0;
72 open DEBUG, ">/dev/null" or die $!;
73
74 autoflush STDOUT 1;
75
76 our $remotename = 'dgit';
77 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
78 our $branchprefix = 'dgit';
79 our $csuite;
80
81 sub lbranch () { return "$branchprefix/$csuite"; }
82 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
83 sub lref () { return "refs/heads/".lbranch(); }
84 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
85 sub rrref () { return "refs/$branchprefix/$csuite"; }
86 sub debiantag ($) { 
87     my ($v) = @_;
88     $v =~ y/~:/_%/;
89     return "debian/$v";
90 }
91
92 sub stripepoch ($) {
93     my ($vsn) = @_;
94     $vsn =~ s/^\d+\://;
95     return $vsn;
96 }
97
98 sub dscfn ($) {
99     my ($vsn) = @_;
100     return "${package}_".(stripepoch $vsn).".dsc";
101 }
102
103 sub changesopts () { return @changesopts[1..$#changesopts]; }
104
105 our $us = 'dgit';
106
107 sub fail { die "$us: @_\n"; }
108
109 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
110
111 sub no_such_package () {
112     print STDERR "$us: package $package does not exist in suite $isuite\n";
113     exit 4;
114 }
115
116 sub fetchspec () {
117     local $csuite = '*';
118     return  "+".rrref().":".lrref();
119 }
120
121 our $ua;
122
123 sub url_get {
124     if (!$ua) {
125         $ua = LWP::UserAgent->new();
126         $ua->env_proxy;
127     }
128     my $what = $_[$#_];
129     print "downloading $what...\n";
130     my $r = $ua->get(@_) or die $!;
131     return undef if $r->code == 404;
132     $r->is_success or fail "failed to fetch $what: ".$r->status_line;
133     return $r->decoded_content();
134 }
135
136 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
137
138 sub printcmd {
139     my $fh = shift @_;
140     my $intro = shift @_;
141     print $fh $intro or die $!;
142     local $_;
143     foreach my $a (@_) {
144         $_ = $a;
145         if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
146             print $fh " '$_'" or die $!;
147         } else {
148             print $fh " $_" or die $!;
149         }
150     }
151     print $fh "\n" or die $!;
152 }
153
154 sub failedcmd {
155     { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
156     if ($!) {
157         fail "failed to fork/exec: $!";
158     } elsif (!($? & 0xff)) {
159         fail "subprocess failed with error exit status ".($?>>8);
160     } elsif ($?) {
161         fail "subprocess crashed (wait status $?)";
162     } else {
163         fail "subprocess produced invalid output";
164     }
165 }
166
167 sub runcmd {
168     printcmd(\*DEBUG,"+",@_) if $debug>0;
169     $!=0; $?=0;
170     failedcmd @_ if system @_;
171 }
172
173 sub printdone {
174     if (!$dryrun) {
175         print "dgit ok: @_\n";
176     } else {
177         print "would be ok: @_ (but dry run only)\n";
178     }
179 }
180
181 sub cmdoutput_errok {
182     die Dumper(\@_)." ?" if grep { !defined } @_;
183     printcmd(\*DEBUG,"|",@_) if $debug>0;
184     open P, "-|", @_ or die $!;
185     my $d;
186     $!=0; $?=0;
187     { local $/ = undef; $d = <P>; }
188     die $! if P->error;
189     if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
190     chomp $d;
191     $d =~ m/^.*/;
192     print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
193     return $d;
194 }
195
196 sub cmdoutput {
197     my $d = cmdoutput_errok @_;
198     defined $d or failedcmd @_;
199     return $d;
200 }
201
202 sub dryrun_report {
203     printcmd(\*STDOUT,"#",@_);
204 }
205
206 sub runcmd_ordryrun {
207     if (!$dryrun) {
208         runcmd @_;
209     } else {
210         dryrun_report @_;
211     }
212 }
213
214 sub runcmd_ordryrun_local {
215     if ($dryrun <= 1) {
216         runcmd @_;
217     } else {
218         dryrun_report @_;
219     }
220 }
221
222 sub shell_cmd {
223     my ($first_shell, @cmd) = @_;
224     return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
225 }
226
227 our $helpmsg = <<END;
228 main usages:
229   dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
230   dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
231   dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
232   dgit [dgit-opts] push [dgit-opts] [suite]
233 important dgit options:
234   -k<keyid>           sign tag and package with <keyid> instead of default
235   --dry-run -n        do not change anything, but go through the motions
236   --damp-run -L       like --dry-run but make local changes, without signing
237   --new -N            allow introducing a new package
238   --debug -D          increase debug level
239   -c<name>=<value>    set git config option (used directly by dgit too)
240 END
241
242 our $later_warning_msg = <<END;
243 Perhaps the upload is stuck in incoming.  Using the version from git.
244 END
245
246 sub badusage {
247     print STDERR "$us: @_\n", $helpmsg or die $!;
248     exit 8;
249 }
250
251 sub cmd_help () {
252     print $helpmsg or die $!;
253     exit 0;
254 }
255
256 our %defcfg = ('dgit.default.distro' => 'debian',
257                'dgit.default.username' => '',
258                'dgit.default.archive-query-default-component' => 'main',
259                'dgit.default.ssh' => 'ssh',
260                'dgit-distro.debian.git-host' => 'git.debian.org',
261                'dgit-distro.debian.git-proto' => 'git+ssh://',
262                'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
263                'dgit-distro.debian.git-check' => 'ssh-cmd',
264                'dgit-distro.debian.git-create' => 'ssh-cmd',
265                'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
266                'dgit-distro.debian.sshdakls-dir' =>
267                    '/srv/ftp-master.debian.org/ftp/dists',
268                'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
269                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
270
271 sub cfg {
272     foreach my $c (@_) {
273         return undef if $c =~ /RETURN-UNDEF/;
274         my @cmd = (@git, qw(config --), $c);
275         my $v;
276         {
277             local ($debug) = $debug-1;
278             $v = cmdoutput_errok @cmd;
279         };
280         if ($?==0) {
281             return $v;
282         } elsif ($?!=256) {
283             failedcmd @cmd;
284         }
285         my $dv = $defcfg{$c};
286         return $dv if defined $dv;
287     }
288     badcfg "need value for one of: @_";
289 }
290
291 sub access_distro () {
292     return cfg("dgit-suite.$isuite.distro",
293                "dgit.default.distro");
294 }
295
296 sub access_cfg (@) {
297     my (@keys) = @_;
298     my $distro = $idistro || access_distro();
299     my $value = cfg(map { ("dgit-distro.$distro.$_",
300                            "dgit.default.$_") } @keys);
301     return $value;
302 }
303
304 sub access_someuserhost ($) {
305     my ($some) = @_;
306     my $user = access_cfg("$some-user",'username');
307     my $host = access_cfg("$some-host");
308     return length($user) ? "$user\@$host" : $host;
309 }
310
311 sub access_gituserhost () {
312     return access_someuserhost('git');
313 }
314
315 sub access_giturl () {
316     my $url = access_cfg('git-url','RETURN-UNDEF');
317     if (!defined $url) {
318         $url =
319             access_cfg('git-proto').
320             access_gituserhost().
321             access_cfg('git-path');
322     }
323     return "$url/$package.git";
324 }              
325
326 sub parsecontrolfh ($$@) {
327     my ($fh, $desc, @opts) = @_;
328     my %opts = ('name' => $desc, @opts);
329     my $c = Dpkg::Control::Hash->new(%opts);
330     $c->parse($fh) or die "parsing of $desc failed";
331     return $c;
332 }
333
334 sub parsecontrol {
335     my ($file, $desc) = @_;
336     my $fh = new IO::Handle;
337     open $fh, '<', $file or die "$file: $!";
338     my $c = parsecontrolfh($fh,$desc);
339     $fh->error and die $!;
340     close $fh;
341     return $c;
342 }
343
344 sub getfield ($$) {
345     my ($dctrl,$field) = @_;
346     my $v = $dctrl->{$field};
347     return $v if defined $v;
348     fail "missing field $field in ".$v->get_option('name');
349 }
350
351 sub parsechangelog {
352     my $c = Dpkg::Control::Hash->new();
353     my $p = new IO::Handle;
354     my @cmd = (qw(dpkg-parsechangelog), @_);
355     open $p, '-|', @cmd or die $!;
356     $c->parse($p);
357     $?=0; $!=0; close $p or failedcmd @cmd;
358     return $c;
359 }
360
361 our %rmad;
362
363 sub archive_query ($) {
364     my ($method) = @_;
365     my $query = access_cfg('archive-query','RETURN-UNDEF');
366     if (!defined $query) {
367         my $distro = access_distro();
368         if ($distro eq 'debian') {
369             $query = "sshdakls:".
370                 access_someuserhost('sshdakls').':'.
371                 access_cfg('sshdakls-dir');
372         } else {
373             $query = "madison:$distro";
374         }
375     }
376     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
377     my $proto = $1;
378     my $data = $'; #';
379     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
380 }
381
382 sub archive_query_madison ($$) {
383     my ($proto,$data) = @_;
384     die unless $proto eq 'madison';
385     $rmad{$package} ||= cmdoutput
386         qw(rmadison -asource),"-s$isuite","-u$data",$package;
387     my $rmad = $rmad{$package};
388     return madison_parse($rmad);
389 }
390
391 sub archive_query_sshdakls ($$) {
392     my ($proto,$data) = @_;
393     $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
394     my $dakls = cmdoutput
395         access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
396     return madison_parse($dakls);
397 }
398
399 sub canonicalise_suite_sshdakls ($$) {
400     my ($proto,$data) = @_;
401     $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
402     my @cmd =
403         (access_cfg('ssh'), $`,
404          "set -e; cd $';".
405          " if test -h $isuite; then readlink $isuite; exit 0; fi;".
406          " if test -d $isuite; then echo $isuite; exit 0; fi;".
407          " exit 1");
408     my $dakls = cmdoutput @cmd;
409     failedcmd @cmd unless $dakls =~ m/^\w/;
410     return $dakls;
411 }
412
413 sub madison_parse ($) {
414     my ($rmad) = @_;
415     my @out;
416     foreach my $l (split /\n/, $rmad) {
417         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
418                   \s*( [^ \t|]+ )\s* \|
419                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
420                   \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
421         $1 eq $package or die "$rmad $package ?";
422         my $vsn = $2;
423         my $newsuite = $3;
424         my $component;
425         if (defined $4) {
426             $component = $4;
427         } else {
428             $component = access_cfg('archive-query-default-component');
429         }
430         $5 eq 'source' or die "$rmad ?";
431         my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
432         my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
433         push @out, [$vsn,$subpath,$newsuite];
434     }
435     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
436 }
437
438 sub canonicalise_suite_madison ($$) {
439     my @r = archive_query_madison($_[0],$_[1]);
440     @r or fail
441         "unable to canonicalise suite using package $package".
442         " which does not appear to exist in suite $isuite;".
443         " --existing-package may help";
444     return $r[0][2];
445 }
446
447 sub canonicalise_suite () {
448     return if defined $csuite;
449     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
450     $csuite = archive_query('canonicalise_suite');
451     if ($isuite ne $csuite) {
452         # madison canonicalises for us
453         print "canonical suite name for $isuite is $csuite\n";
454     }
455 }
456
457 sub get_archive_dsc () {
458     canonicalise_suite();
459     my @vsns = archive_query('archive_query');
460     foreach my $vinfo (@vsns) {
461         my ($vsn,$subpath) = @$vinfo;
462         $dscurl = access_cfg('mirror').$subpath;
463         $dscdata = url_get($dscurl);
464         if (!$dscdata) {
465             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
466             next;
467         }
468         my $dscfh = new IO::File \$dscdata, '<' or die $!;
469         print DEBUG Dumper($dscdata) if $debug>1;
470         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
471         print DEBUG Dumper($dsc) if $debug>1;
472         my $fmt = getfield $dsc, 'Format';
473         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
474         return;
475     }
476     $dsc = undef;
477 }
478
479 sub check_for_git () {
480     # returns 0 or 1
481     my $how = access_cfg('git-check');
482     if ($how eq 'ssh-cmd') {
483         my @cmd =
484             (access_cfg('ssh'),access_gituserhost(),
485              " set -e; cd ".access_cfg('git-path').";".
486              " if test -d $package.git; then echo 1; else echo 0; fi");
487         my $r= cmdoutput @cmd;
488         failedcmd @cmd unless $r =~ m/^[01]$/;
489         return $r+0;
490     } else {
491         badcfg "unknown git-check \`$how'";
492     }
493 }
494
495 sub create_remote_git_repo () {
496     my $how = access_cfg('git-create');
497     if ($how eq 'ssh-cmd') {
498         runcmd_ordryrun
499             (access_cfg('ssh'),access_gituserhost(),
500              "set -e; cd ".access_cfg('git-path').";".
501              " cp -a _template $package.git");
502     } else {
503         badcfg "unknown git-create \`$how'";
504     }
505 }
506
507 our ($dsc_hash,$lastpush_hash);
508
509 our $ud = '.git/dgit/unpack';
510
511 sub prep_ud () {
512     rmtree($ud);
513     mkpath '.git/dgit';
514     mkdir $ud or die $!;
515 }
516
517 sub mktree_in_ud_from_only_subdir () {
518     # changes into the subdir
519     my (@dirs) = <*/.>;
520     die unless @dirs==1;
521     $dirs[0] =~ m#^([^/]+)/\.$# or die;
522     my $dir = $1;
523     chdir $dir or die "$dir $!";
524     fail "source package contains .git directory" if stat '.git';
525     die $! unless $!==&ENOENT;
526     runcmd qw(git init -q);
527     rmtree('.git/objects');
528     symlink '../../../../objects','.git/objects' or die $!;
529     runcmd @git, qw(add -Af);
530     my $tree = cmdoutput @git, qw(write-tree);
531     $tree =~ m/^\w+$/ or die "$tree ?";
532     return ($tree,$dir);
533 }
534
535 sub dsc_files_info () {
536     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
537                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
538                        ['Files',           'Digest::MD5', 'new()']) {
539         my ($fname, $module, $method) = @$csumi;
540         my $field = $dsc->{$fname};
541         next unless defined $field;
542         eval "use $module; 1;" or die $@;
543         my @out;
544         foreach (split /\n/, $field) {
545             next unless m/\S/;
546             m/^(\w+) (\d+) (\S+)$/ or
547                 fail "could not parse .dsc $fname line \`$_'";
548             my $digester = eval "$module"."->$method;" or die $@;
549             push @out, {
550                 Hash => $1,
551                 Bytes => $2,
552                 Filename => $3,
553                 Digester => $digester,
554             };
555         }
556         return @out;
557     }
558     fail "missing any supported Checksums-* or Files field in ".
559         $dsc->get_option('name');
560 }
561
562 sub dsc_files () {
563     map { $_->{Filename} } dsc_files_info();
564 }
565
566 sub is_orig_file ($) {
567     local ($_) = @_;
568     m/\.orig(?:-\w+)?\.tar\.\w+$/;
569 }
570
571 sub make_commit ($) {
572     my ($file) = @_;
573     return cmdoutput @git, qw(hash-object -w -t commit), $file;
574 }
575
576 sub generate_commit_from_dsc () {
577     prep_ud();
578     chdir $ud or die $!;
579     my @files;
580     foreach my $f (dsc_files()) {
581         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
582         push @files, $f;
583         link "../../../$f", $f
584             or $!==&ENOENT
585             or die "$f $!";
586     }
587     runcmd @dget, qw(--), $dscurl;
588     foreach my $f (grep { is_orig_file($_) } @files) {
589         link $f, "../../../../$f"
590             or $!==&EEXIST
591             or die "$f $!";
592     }
593     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
594     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
595     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
596     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
597     my $author = getfield $clogp, 'Maintainer';
598     $author =~ s#,.*##ms;
599     my $authline = "$author $date";
600     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
601         fail "unexpected commit author line format \`$authline'".
602             " (was generated from changelog Maintainer field)";
603     my $changes = getfield $clogp, 'Changes';
604     open C, ">../commit.tmp" or die $!;
605     print C <<END or die $!;
606 tree $tree
607 author $authline
608 committer $authline
609
610 $changes
611
612 # imported from the archive
613 END
614     close C or die $!;
615     my $outputhash = make_commit qw(../commit.tmp);
616     my $cversion = getfield $clogp, 'Version';
617     print "synthesised git commit from .dsc $cversion\n";
618     if ($lastpush_hash) {
619         runcmd @git, qw(reset --hard), $lastpush_hash;
620         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
621         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
622         my $oversion = getfield $oldclogp, 'Version';
623         my $vcmp =
624             version_compare_string($oversion, $cversion);
625         if ($vcmp < 0) {
626             # git upload/ is earlier vsn than archive, use archive
627             open C, ">../commit2.tmp" or die $!;
628             print C <<END or die $!;
629 tree $tree
630 parent $lastpush_hash
631 parent $outputhash
632 author $authline
633 committer $authline
634
635 Record $package ($cversion) in archive suite $csuite
636 END
637             $outputhash = make_commit qw(../commit2.tmp);
638         } elsif ($vcmp > 0) {
639             print STDERR <<END or die $!;
640
641 Version actually in archive:    $cversion (older)
642 Last allegedly pushed/uploaded: $oversion (newer or same)
643 $later_warning_msg
644 END
645             $outputhash = $lastpush_hash;
646         } else {
647             $outputhash = $lastpush_hash;
648         }
649     }
650     chdir '../../../..' or die $!;
651     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
652             'DGIT_ARCHIVE', $outputhash;
653     cmdoutput @git, qw(log -n2), $outputhash;
654     # ... gives git a chance to complain if our commit is malformed
655     rmtree($ud);
656     return $outputhash;
657 }
658
659 sub ensure_we_have_orig () {
660     foreach my $fi (dsc_files_info()) {
661         my $f = $fi->{Filename};
662         next unless is_orig_file($f);
663         if (open F, "<", "../$f") {
664             $fi->{Digester}->reset();
665             $fi->{Digester}->addfile(*F);
666             F->error and die $!;
667             my $got = $fi->{Digester}->hexdigest();
668             $got eq $fi->{Hash} or
669                 fail "existing file $f has hash $got but .dsc".
670                     " demands hash $fi->{Hash}".
671                     " (perhaps you should delete this file?)";
672             print "using existing $f\n";
673             next;
674         } else {
675             die "$f $!" unless $!==&ENOENT;
676         }
677         my $origurl = $dscurl;
678         $origurl =~ s{/[^/]+$}{};
679         $origurl .= "/$f";
680         die "$f ?" unless $f =~ m/^${package}_/;
681         die "$f ?" if $f =~ m#/#;
682         runcmd_ordryrun_local shell_cmd 'cd ..', @dget,'--',$origurl;
683     }
684 }
685
686 sub rev_parse ($) {
687     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
688 }
689
690 sub is_fast_fwd ($$) {
691     my ($ancestor,$child) = @_;
692     my @cmd = (@git, qw(merge-base), $ancestor, $child);
693     my $mb = cmdoutput_errok @cmd;
694     if (defined $mb) {
695         return rev_parse($mb) eq rev_parse($ancestor);
696     } else {
697         $?==256 or failedcmd @cmd;
698         return 0;
699     }
700 }
701
702 sub git_fetch_us () {
703     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
704 }
705
706 sub fetch_from_archive () {
707     # ensures that lrref() is what is actually in the archive,
708     #  one way or another
709     get_archive_dsc();
710
711     if ($dsc) {
712         foreach my $field (@ourdscfield) {
713             $dsc_hash = $dsc->{$field};
714             last if defined $dsc_hash;
715         }
716         if (defined $dsc_hash) {
717             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
718             $dsc_hash = $&;
719             print "last upload to archive specified git hash\n";
720         } else {
721             print "last upload to archive has NO git hash\n";
722         }
723     } else {
724         print "no version available from the archive\n";
725     }
726
727     my $lrref_fn = ".git/".lrref();
728     if (open H, $lrref_fn) {
729         $lastpush_hash = <H>;
730         chomp $lastpush_hash;
731         die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
732     } elsif ($! == &ENOENT) {
733         $lastpush_hash = '';
734     } else {
735         die "$lrref_fn $!";
736     }
737     print DEBUG "previous reference hash=$lastpush_hash\n";
738     my $hash;
739     if (defined $dsc_hash) {
740         fail "missing git history even though dsc has hash -".
741             " could not find commit $dsc_hash".
742             " (should be in ".access_giturl()."#".rrref().")"
743             unless $lastpush_hash;
744         $hash = $dsc_hash;
745         ensure_we_have_orig();
746         if ($dsc_hash eq $lastpush_hash) {
747         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
748             print STDERR <<END or die $!;
749
750 Git commit in archive is behind the last version allegedly pushed/uploaded.
751 Commit referred to by archive:  $dsc_hash
752 Last allegedly pushed/uploaded: $lastpush_hash
753 $later_warning_msg
754 END
755             $hash = $lastpush_hash;
756         } else {
757             fail "archive's .dsc refers to ".$dsc_hash.
758                 " but this is an ancestor of ".$lastpush_hash;
759         }
760     } elsif ($dsc) {
761         $hash = generate_commit_from_dsc();
762     } elsif ($lastpush_hash) {
763         # only in git, not in the archive yet
764         $hash = $lastpush_hash;
765         print STDERR <<END or die $!;
766
767 Package not found in the archive, but has allegedly been pushed using dgit.
768 $later_warning_msg
769 END
770     } else {
771         print DEBUG "nothing found!\n";
772         if (defined $skew_warning_vsn) {
773             print STDERR <<END or die $!;
774
775 Warning: relevant archive skew detected.
776 Archive allegedly contains $skew_warning_vsn
777 But we were not able to obtain any version from the archive or git.
778
779 END
780         }
781         return 0;
782     }
783     print DEBUG "current hash=$hash\n";
784     if ($lastpush_hash) {
785         fail "not fast forward on last upload branch!".
786             " (archive's version left in DGIT_ARCHIVE)"
787             unless is_fast_fwd($lastpush_hash, $hash);
788     }
789     if (defined $skew_warning_vsn) {
790         mkpath '.git/dgit';
791         print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
792         my $clogf = ".git/dgit/changelog.tmp";
793         runcmd shell_cmd "exec >$clogf",
794             @git, qw(cat-file blob), "$hash:debian/changelog";
795         my $gotclogp = parsechangelog("-l$clogf");
796         my $got_vsn = getfield $gotclogp, 'Version';
797         print DEBUG "SKEW CHECK GOT $got_vsn\n";
798         if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
799             print STDERR <<END or die $!;
800
801 Warning: archive skew detected.  Using the available version:
802 Archive allegedly contains    $skew_warning_vsn
803 We were able to obtain only   $got_vsn
804
805 END
806         }
807     }
808     if ($lastpush_hash ne $hash) {
809         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
810         if ($dryrun <= 1) {
811             cmdoutput @upd_cmd;
812         } else {
813             dryrun_report @upd_cmd;
814         }
815     }
816     return 1;
817 }
818
819 sub clone ($) {
820     my ($dstdir) = @_;
821     canonicalise_suite();
822     badusage "dry run makes no sense with clone" if $dryrun > 1;
823     mkdir $dstdir or die "$dstdir $!";
824     chdir "$dstdir" or die "$dstdir $!";
825     runcmd @git, qw(init -q);
826     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
827     open H, "> .git/HEAD" or die $!;
828     print H "ref: ".lref()."\n" or die $!;
829     close H or die $!;
830     runcmd @git, qw(remote add), 'origin', access_giturl();
831     if (check_for_git()) {
832         print "fetching existing git history\n";
833         git_fetch_us();
834         runcmd_ordryrun_local @git, qw(fetch origin);
835     } else {
836         print "starting new git history\n";
837     }
838     fetch_from_archive() or no_such_package;
839     runcmd @git, qw(reset --hard), lrref();
840     printdone "ready for work in $dstdir";
841 }
842
843 sub fetch () {
844     if (check_for_git()) {
845         git_fetch_us();
846     }
847     fetch_from_archive() or no_such_package();
848     printdone "fetched into ".lrref();
849 }
850
851 sub pull () {
852     fetch();
853     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
854         lrref();
855     printdone "fetched to ".lrref()." and merged into HEAD";
856 }
857
858 sub check_not_dirty () {
859     return if $ignoredirty;
860     my @cmd = (@git, qw(diff --quiet HEAD));
861     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
862     $!=0; $?=0; system @cmd;
863     return if !$! && !$?;
864     if (!$! && $?==256) {
865         fail "working tree is dirty (does not match HEAD)";
866     } else {
867         failedcmd @cmd;
868     }
869 }
870
871 sub commit_quilty_patch () {
872     my $output = cmdoutput @git, qw(status --porcelain);
873     my %adds;
874     foreach my $l (split /\n/, $output) {
875         next unless $l =~ m/\S/;
876         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
877             $adds{$1}++;
878         }
879     }
880     if (!%adds) {
881         print "nothing quilty to commit, ok.\n";
882         return;
883     }
884     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
885     my $m = "Commit Debian 3.0 (quilt) metadata";
886     print "$m\n";
887     runcmd_ordryrun_local @git, qw(commit -m), $m;
888 }
889
890 sub madformat ($) {
891     my ($format) = @_;
892     return 0 unless $format eq '3.0 (quilt)';
893     print "Format \`$format', urgh\n";
894     if ($noquilt) {
895         print "Not doing any fixup of \`$format' due to --no-quilt-fixup";
896         return 0;
897     }
898     return 1;
899 }
900
901 sub dopush () {
902     print DEBUG "actually entering push\n";
903     my $clogp = parsechangelog();
904     $package = getfield $clogp, 'Source';
905     my $cversion = getfield $clogp, 'Version';
906     my $dscfn = dscfn($cversion);
907     stat "../$dscfn" or
908         fail "looked for .dsc $dscfn, but $!;".
909             " maybe you forgot to build";
910     $dsc = parsecontrol("../$dscfn","$dscfn");
911     my $dscpackage = getfield $dsc, 'Source';
912     my $format = getfield $dsc, 'Format';
913     my $dversion = getfield $dsc, 'Version';
914     ($dscpackage eq $package && $dversion eq $cversion) or
915         fail "$dsc is for $dscpackage $dversion".
916             " but debian/changelog is for $package $cversion";
917     print DEBUG "format $format\n";
918     if (madformat($format)) {
919         commit_quilty_patch();
920     }
921     check_not_dirty();
922     prep_ud();
923     chdir $ud or die $!;
924     print "checking that $dscfn corresponds to HEAD\n";
925     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
926     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
927     chdir '../../../..' or die $!;
928     printcmd \*DEBUG,"+",@_;
929     my @diffcmd = (@git, qw(diff --exit-code), $tree);
930     $!=0; $?=0;
931     if (system @diffcmd) {
932         if ($! && $?==256) {
933             fail "$dscfn specifies a different tree to your HEAD commit;".
934                 " perhaps you forgot to build";
935         } else {
936             failedcmd @diffcmd;
937         }
938     }
939 #fetch from alioth
940 #do fast forward check and maybe fake merge
941 #    if (!is_fast_fwd(mainbranch
942 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
943 #        map { lref($_).":".rref($_) }
944 #        (uploadbranch());
945     $dsc->{$ourdscfield[0]} = rev_parse('HEAD');
946     $dsc->save("../$dscfn.tmp") or die $!;
947     if (!$changesfile) {
948         my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
949         if (stat "$multi") {
950             $changesfile = $multi;
951         } else {
952             $!==&ENOENT or die "$multi: $!";
953             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
954             my @cs = glob "../$pat";
955             fail "failed to find unique changes file".
956                 " (looked for $pat in .., or $multi);".
957                 " perhaps you need to use dgit -C"
958                 unless @cs==1;
959             ($changesfile) = @cs;
960         }
961     }
962     my $changes = parsecontrol($changesfile,$changesfile);
963     foreach my $field (qw(Source Distribution Version)) {
964         $changes->{$field} eq $clogp->{$field} or
965             fail "changes field $field \`$changes->{$field}'".
966                 " does not match changelog \`$clogp->{$field}'";
967     }
968     my $tag = debiantag($dversion);
969     if (!check_for_git()) {
970         create_remote_git_repo();
971     }
972     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
973     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
974     if (!$dryrun) {
975         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
976     } else {
977         print "[new .dsc left in $dscfn.tmp]\n";
978     }
979     if ($sign) {
980         if (!defined $keyid) {
981             $keyid = access_cfg('keyid','RETURN-UNDEF');
982         }
983         my @tag_cmd = (@git, qw(tag -m),
984                        "$package release $dversion for $csuite [dgit]");
985         if ($dryrun != 1) {
986             push @tag_cmd, qw(-s);
987             push @tag_cmd, qw(-u),$keyid if defined $keyid;
988         }
989         push @tag_cmd, $tag;
990         runcmd_ordryrun_local @tag_cmd;
991         my @debsign_cmd = @debsign;
992         push @debsign_cmd, "-k$keyid" if defined $keyid;
993         push @debsign_cmd, $changesfile;
994         runcmd_ordryrun @debsign_cmd;
995     }
996     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
997     my $host = access_cfg('upload-host','RETURN-UNDEF');
998     my @hostarg = defined($host) ? ($host,) : ();
999     runcmd_ordryrun @dput, @hostarg, $changesfile;
1000     printdone "pushed and uploaded $dversion";
1001 }
1002
1003 sub cmd_clone {
1004     parseopts();
1005     my $dstdir;
1006     badusage "-p is not allowed with clone; specify as argument instead"
1007         if defined $package;
1008     if (@ARGV==1) {
1009         ($package) = @ARGV;
1010     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1011         ($package,$isuite) = @ARGV;
1012     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1013         ($package,$dstdir) = @ARGV;
1014     } elsif (@ARGV==3) {
1015         ($package,$isuite,$dstdir) = @ARGV;
1016     } else {
1017         badusage "incorrect arguments to dgit clone";
1018     }
1019     $dstdir ||= "$package";
1020     clone($dstdir);
1021 }
1022
1023 sub branchsuite () {
1024     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1025     if ($branch =~ m#$lbranch_re#o) {
1026         return $1;
1027     } else {
1028         return undef;
1029     }
1030 }
1031
1032 sub fetchpullargs () {
1033     if (!defined $package) {
1034         my $sourcep = parsecontrol('debian/control','debian/control');
1035         $package = getfield $sourcep, 'Source';
1036     }
1037     if (@ARGV==0) {
1038 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1039         if (!$isuite) {
1040             my $clogp = parsechangelog();
1041             $isuite = getfield $clogp, 'Distribution';
1042         }
1043         canonicalise_suite();
1044         print "fetching from suite $csuite\n";
1045     } elsif (@ARGV==1) {
1046         ($isuite) = @ARGV;
1047         canonicalise_suite();
1048     } else {
1049         badusage "incorrect arguments to dgit fetch or dgit pull";
1050     }
1051 }
1052
1053 sub cmd_fetch {
1054     parseopts();
1055     fetchpullargs();
1056     fetch();
1057 }
1058
1059 sub cmd_pull {
1060     parseopts();
1061     fetchpullargs();
1062     pull();
1063 }
1064
1065 sub cmd_push {
1066     parseopts();
1067     badusage "-p is not allowed with dgit push" if defined $package;
1068     check_not_dirty();
1069     my $clogp = parsechangelog();
1070     $package = getfield $clogp, 'Source';
1071     if (@ARGV==0) {
1072         $isuite = getfield $clogp, 'Distribution';
1073         if ($new_package) {
1074             local ($package) = $existing_package; # this is a hack
1075             canonicalise_suite();
1076         }
1077     } else {
1078         badusage "incorrect arguments to dgit push";
1079     }
1080     if (check_for_git()) {
1081         git_fetch_us();
1082     }
1083     if (fetch_from_archive()) {
1084         is_fast_fwd(lrref(), 'HEAD') or
1085             fail "dgit push: HEAD is not a descendant".
1086                 " of the archive's version.\n".
1087                 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1088     } else {
1089         $new_package or
1090             fail "package appears to be new in this suite;".
1091                 " if this is intentional, use --new";
1092     }
1093     dopush();
1094 }
1095
1096 our $version;
1097 our $sourcechanges;
1098 our $dscfn;
1099
1100 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1101
1102 sub build_maybe_quilt_fixup () {
1103     if (!open F, "debian/source/format") {
1104         die $! unless $!==&ENOENT;
1105         return;
1106     }
1107     $_ = <F>;
1108     F->error and die $!;
1109     chomp;
1110     return unless madformat($_);
1111     # sigh
1112     my $clogp = parsechangelog();
1113     my $version = getfield $clogp, 'Version';
1114     my $author = getfield $clogp, 'Maintainer';
1115     my $headref = rev_parse('HEAD');
1116     my $time = time;
1117     my $ncommits = 3;
1118     my $patchname = "auto-$version-$headref-$time";
1119     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1120     mkpath '.git/dgit';
1121     my $descfn = ".git/dgit/quilt-description.tmp";
1122     open O, '>', $descfn or die "$descfn: $!";
1123     $msg =~ s/\n/\n /g;
1124     $msg =~ s/^\s+$/ ./mg;
1125     print O <<END or die $!;
1126 Description: Automatically generated patch ($clogp->{Version})
1127  Last (up to) $ncommits git changes, FYI:
1128  .
1129  $msg
1130 Author: $author
1131
1132 ---
1133
1134 END
1135     close O or die $!;
1136     {
1137         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1138         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1139         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1140         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1141     }
1142
1143     if (!open P, '>>', ".pc/applied-patches") {
1144         $!==&ENOENT or die $!;
1145     } else {
1146         close P;
1147     }
1148
1149     commit_quilty_patch();
1150 }
1151
1152 sub quilt_fixup_editor () {
1153     my $descfn = $ENV{$fakeeditorenv};
1154     my $editing = $ARGV[$#ARGV];
1155     open I1, '<', $descfn or die "$descfn: $!";
1156     open I2, '<', $editing or die "$editing: $!";
1157     unlink $editing or die "$editing: $!";
1158     open O, '>', $editing or die "$editing: $!";
1159     while (<I1>) { print O or die $!; } I1->error and die $!;
1160     my $copying = 0;
1161     while (<I2>) {
1162         $copying ||= m/^\-\-\- /;
1163         next unless $copying;
1164         print O or die $!;
1165     }
1166     I2->error and die $!;
1167     close O or die $1;
1168     exit 0;
1169 }
1170
1171 sub build_prep () {
1172     badusage "-p is not allowed when building" if defined $package;
1173     check_not_dirty();
1174     my $clogp = parsechangelog();
1175     $isuite = getfield $clogp, 'Distribution';
1176     $package = getfield $clogp, 'Source';
1177     $version = getfield $clogp, 'Version';
1178     build_maybe_quilt_fixup();
1179 }
1180
1181 sub cmd_build {
1182     badusage "dgit build implies --clean=dpkg-source"
1183         if $cleanmode ne 'dpkg-source';
1184     build_prep();
1185     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1186     printdone "build successful\n";
1187 }
1188
1189 sub cmd_git_build {
1190     badusage "dgit git-build implies --clean=dpkg-source"
1191         if $cleanmode ne 'dpkg-source';
1192     build_prep();
1193     my @cmd =
1194         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1195          "--git-builder=@dpkgbuildpackage");
1196     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1197         canonicalise_suite();
1198         push @cmd, "--git-debian-branch=".lbranch();
1199     }
1200     push @cmd, changesopts();
1201     runcmd_ordryrun_local @cmd, @ARGV;
1202     printdone "build successful\n";
1203 }
1204
1205 sub build_source {
1206     build_prep();
1207     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1208     $dscfn = dscfn($version);
1209     if ($cleanmode eq 'dpkg-source') {
1210         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
1211             changesopts();
1212     } else {
1213         if ($cleanmode eq 'git') {
1214             runcmd_ordryrun_local @git, qw(clean -xdf);
1215         } elsif ($cleanmode eq 'none') {
1216         } else {
1217             die "$cleanmode ?";
1218         }
1219         my $pwd = cmdoutput qw(env - pwd);
1220         my $leafdir = basename $pwd;
1221         chdir ".." or die $!;
1222         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
1223         chdir $pwd or die $!;
1224         runcmd_ordryrun_local qw(sh -ec),
1225             'exec >$1; shift; exec "$@"','x',
1226             "../$sourcechanges",
1227             @dpkggenchanges, qw(-S), changesopts();
1228     }
1229 }
1230
1231 sub cmd_build_source {
1232     badusage "build-source takes no additional arguments" if @ARGV;
1233     build_source();
1234     printdone "source built, results in $dscfn and $sourcechanges";
1235 }
1236
1237 sub cmd_sbuild {
1238     build_source();
1239     chdir ".." or die $!;
1240     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1241     if ($dryrun <= 1) {
1242         stat $dscfn or fail "$dscfn (in parent directory): $!";
1243         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1244         foreach my $cf (glob $pat) {
1245             next if $cf eq $sourcechanges;
1246             unlink $cf or fail "remove $cf: $!";
1247         }
1248     }
1249     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1250     runcmd_ordryrun @mergechanges, glob $pat;
1251     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1252     if ($dryrun <= 1) {
1253         stat $multichanges or fail "$multichanges: $!";
1254     }
1255     printdone "build successful, results in $multichanges\n" or die $!;
1256 }    
1257
1258 sub cmd_quilt_fixup {
1259     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1260     my $clogp = parsechangelog();
1261     $version = getfield $clogp, 'Version';
1262     build_maybe_quilt_fixup();
1263 }
1264
1265 sub cmd_version {
1266     print "dgit version $our_version\n" or die $!;
1267     exit 0;
1268 }
1269
1270 sub parseopts () {
1271     my $om;
1272     while (@ARGV) {
1273         last unless $ARGV[0] =~ m/^-/;
1274         $_ = shift @ARGV;
1275         last if m/^--?$/;
1276         if (m/^--/) {
1277             if (m/^--dry-run$/) {
1278                 $dryrun=2;
1279             } elsif (m/^--damp-run$/) {
1280                 $dryrun=1;
1281             } elsif (m/^--no-sign$/) {
1282                 $sign=0;
1283             } elsif (m/^--help$/) {
1284                 cmd_help();
1285             } elsif (m/^--version$/) {
1286                 cmd_version();
1287             } elsif (m/^--new$/) {
1288                 $new_package=1;
1289             } elsif (m/^--(\w+)=(.*)/s &&
1290                      ($om = $opts_opt_map{$1}) &&
1291                      length $om->[0]) {
1292                 $om->[0] = $2;
1293             } elsif (m/^--(\w+):(.*)/s &&
1294                      ($om = $opts_opt_map{$1})) {
1295                 push @$om, $2;
1296             } elsif (m/^--existing-package=(.*)/s) {
1297                 $existing_package = $1;
1298             } elsif (m/^--distro=(.*)/s) {
1299                 $idistro = $1;
1300             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1301                 $cleanmode = $1;
1302             } elsif (m/^--clean=(.*)$/s) {
1303                 badusage "unknown cleaning mode \`$1'";
1304             } elsif (m/^--ignore-dirty$/s) {
1305                 $ignoredirty = 1;
1306             } elsif (m/^--no-quilt-fixup$/s) {
1307                 $noquilt = 1;
1308             } else {
1309                 badusage "unknown long option \`$_'";
1310             }
1311         } else {
1312             while (m/^-./s) {
1313                 if (s/^-n/-/) {
1314                     $dryrun=2;
1315                 } elsif (s/^-L/-/) {
1316                     $dryrun=1;
1317                 } elsif (s/^-h/-/) {
1318                     cmd_help();
1319                 } elsif (s/^-D/-/) {
1320                     open DEBUG, ">&STDERR" or die $!;
1321                     $debug++;
1322                 } elsif (s/^-N/-/) {
1323                     $new_package=1;
1324                 } elsif (m/^-[vm]/) {
1325                     push @changesopts, $_;
1326                     $_ = '';
1327                 } elsif (s/^-c(.*=.*)//s) {
1328                     push @git, '-c', $1;
1329                 } elsif (s/^-d(.*)//s) {
1330                     $idistro = $1;
1331                 } elsif (s/^-C(.*)//s) {
1332                     $changesfile = $1;
1333                 } elsif (s/^-k(.*)//s) {
1334                     $keyid=$1;
1335                 } elsif (s/^-wn//s) {
1336                     $cleanmode = 'none';
1337                 } elsif (s/^-wg//s) {
1338                     $cleanmode = 'git';
1339                 } elsif (s/^-wd//s) {
1340                     $cleanmode = 'dpkg-source';
1341                 } else {
1342                     badusage "unknown short option \`$_'";
1343                 }
1344             }
1345         }
1346     }
1347 }
1348
1349 if ($ENV{$fakeeditorenv}) {
1350     quilt_fixup_editor();
1351 }
1352
1353 delete $ENV{'DGET_UNPACK'};
1354
1355 parseopts();
1356 print STDERR "DRY RUN ONLY\n" if $dryrun > 1;
1357 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n" if $dryrun == 1;
1358 if (!@ARGV) {
1359     print STDERR $helpmsg or die $!;
1360     exit 8;
1361 }
1362 my $cmd = shift @ARGV;
1363 $cmd =~ y/-/_/;
1364 { no strict qw(refs); &{"cmd_$cmd"}(); }