chiark / gitweb /
Do not grobble around in .git/refs/; instead, use git-show-ref. This avoids breaking...
[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 sub git_get_ref ($) {
362     my ($refname) = @_;
363     my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
364     if (!defined $got) {
365         $?==256 or fail "git show-ref failed (status $?)";
366         print DEBUG "ref $refname= [show-ref exited 1]\n";
367         return '';
368     }
369     if ($got =~ m/^(\w+) \Q$refname\E$/m) {
370         print DEBUG "ref $refname=$1\n";
371         return $1;
372     } else {
373         print DEBUG "ref $refname= [no match]\n";
374         return '';
375     }
376 }
377
378 our %rmad;
379
380 sub archive_query ($) {
381     my ($method) = @_;
382     my $query = access_cfg('archive-query','RETURN-UNDEF');
383     if (!defined $query) {
384         my $distro = access_distro();
385         if ($distro eq 'debian') {
386             $query = "sshdakls:".
387                 access_someuserhost('sshdakls').':'.
388                 access_cfg('sshdakls-dir');
389         } else {
390             $query = "madison:$distro";
391         }
392     }
393     $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
394     my $proto = $1;
395     my $data = $'; #';
396     { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
397 }
398
399 sub archive_query_madison ($$) {
400     my ($proto,$data) = @_;
401     die unless $proto eq 'madison';
402     $rmad{$package} ||= cmdoutput
403         qw(rmadison -asource),"-s$isuite","-u$data",$package;
404     my $rmad = $rmad{$package};
405     return madison_parse($rmad);
406 }
407
408 sub archive_query_sshdakls ($$) {
409     my ($proto,$data) = @_;
410     $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
411     my $dakls = cmdoutput
412         access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
413     return madison_parse($dakls);
414 }
415
416 sub canonicalise_suite_sshdakls ($$) {
417     my ($proto,$data) = @_;
418     $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
419     my @cmd =
420         (access_cfg('ssh'), $`,
421          "set -e; cd $';".
422          " if test -h $isuite; then readlink $isuite; exit 0; fi;".
423          " if test -d $isuite; then echo $isuite; exit 0; fi;".
424          " exit 1");
425     my $dakls = cmdoutput @cmd;
426     failedcmd @cmd unless $dakls =~ m/^\w/;
427     return $dakls;
428 }
429
430 sub madison_parse ($) {
431     my ($rmad) = @_;
432     my @out;
433     foreach my $l (split /\n/, $rmad) {
434         $l =~ m{^ \s*( [^ \t|]+ )\s* \|
435                   \s*( [^ \t|]+ )\s* \|
436                   \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
437                   \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
438         $1 eq $package or die "$rmad $package ?";
439         my $vsn = $2;
440         my $newsuite = $3;
441         my $component;
442         if (defined $4) {
443             $component = $4;
444         } else {
445             $component = access_cfg('archive-query-default-component');
446         }
447         $5 eq 'source' or die "$rmad ?";
448         my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
449         my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
450         push @out, [$vsn,$subpath,$newsuite];
451     }
452     return sort { -version_compare_string($a->[0],$b->[0]); } @out;
453 }
454
455 sub canonicalise_suite_madison ($$) {
456     my @r = archive_query_madison($_[0],$_[1]);
457     @r or fail
458         "unable to canonicalise suite using package $package".
459         " which does not appear to exist in suite $isuite;".
460         " --existing-package may help";
461     return $r[0][2];
462 }
463
464 sub canonicalise_suite () {
465     return if defined $csuite;
466     fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
467     $csuite = archive_query('canonicalise_suite');
468     if ($isuite ne $csuite) {
469         # madison canonicalises for us
470         print "canonical suite name for $isuite is $csuite\n";
471     }
472 }
473
474 sub get_archive_dsc () {
475     canonicalise_suite();
476     my @vsns = archive_query('archive_query');
477     foreach my $vinfo (@vsns) {
478         my ($vsn,$subpath) = @$vinfo;
479         $dscurl = access_cfg('mirror').$subpath;
480         $dscdata = url_get($dscurl);
481         if (!$dscdata) {
482             $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
483             next;
484         }
485         my $dscfh = new IO::File \$dscdata, '<' or die $!;
486         print DEBUG Dumper($dscdata) if $debug>1;
487         $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
488         print DEBUG Dumper($dsc) if $debug>1;
489         my $fmt = getfield $dsc, 'Format';
490         fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
491         return;
492     }
493     $dsc = undef;
494 }
495
496 sub check_for_git () {
497     # returns 0 or 1
498     my $how = access_cfg('git-check');
499     if ($how eq 'ssh-cmd') {
500         my @cmd =
501             (access_cfg('ssh'),access_gituserhost(),
502              " set -e; cd ".access_cfg('git-path').";".
503              " if test -d $package.git; then echo 1; else echo 0; fi");
504         my $r= cmdoutput @cmd;
505         failedcmd @cmd unless $r =~ m/^[01]$/;
506         return $r+0;
507     } else {
508         badcfg "unknown git-check \`$how'";
509     }
510 }
511
512 sub create_remote_git_repo () {
513     my $how = access_cfg('git-create');
514     if ($how eq 'ssh-cmd') {
515         runcmd_ordryrun
516             (access_cfg('ssh'),access_gituserhost(),
517              "set -e; cd ".access_cfg('git-path').";".
518              " cp -a _template $package.git");
519     } else {
520         badcfg "unknown git-create \`$how'";
521     }
522 }
523
524 our ($dsc_hash,$lastpush_hash);
525
526 our $ud = '.git/dgit/unpack';
527
528 sub prep_ud () {
529     rmtree($ud);
530     mkpath '.git/dgit';
531     mkdir $ud or die $!;
532 }
533
534 sub mktree_in_ud_from_only_subdir () {
535     # changes into the subdir
536     my (@dirs) = <*/.>;
537     die unless @dirs==1;
538     $dirs[0] =~ m#^([^/]+)/\.$# or die;
539     my $dir = $1;
540     chdir $dir or die "$dir $!";
541     fail "source package contains .git directory" if stat '.git';
542     die $! unless $!==&ENOENT;
543     runcmd qw(git init -q);
544     rmtree('.git/objects');
545     symlink '../../../../objects','.git/objects' or die $!;
546     runcmd @git, qw(add -Af);
547     my $tree = cmdoutput @git, qw(write-tree);
548     $tree =~ m/^\w+$/ or die "$tree ?";
549     return ($tree,$dir);
550 }
551
552 sub dsc_files_info () {
553     foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
554                        ['Checksums-Sha1',  'Digest::SHA', 'new(1)'],
555                        ['Files',           'Digest::MD5', 'new()']) {
556         my ($fname, $module, $method) = @$csumi;
557         my $field = $dsc->{$fname};
558         next unless defined $field;
559         eval "use $module; 1;" or die $@;
560         my @out;
561         foreach (split /\n/, $field) {
562             next unless m/\S/;
563             m/^(\w+) (\d+) (\S+)$/ or
564                 fail "could not parse .dsc $fname line \`$_'";
565             my $digester = eval "$module"."->$method;" or die $@;
566             push @out, {
567                 Hash => $1,
568                 Bytes => $2,
569                 Filename => $3,
570                 Digester => $digester,
571             };
572         }
573         return @out;
574     }
575     fail "missing any supported Checksums-* or Files field in ".
576         $dsc->get_option('name');
577 }
578
579 sub dsc_files () {
580     map { $_->{Filename} } dsc_files_info();
581 }
582
583 sub is_orig_file ($) {
584     local ($_) = @_;
585     m/\.orig(?:-\w+)?\.tar\.\w+$/;
586 }
587
588 sub make_commit ($) {
589     my ($file) = @_;
590     return cmdoutput @git, qw(hash-object -w -t commit), $file;
591 }
592
593 sub generate_commit_from_dsc () {
594     prep_ud();
595     chdir $ud or die $!;
596     my @files;
597     foreach my $f (dsc_files()) {
598         die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
599         push @files, $f;
600         link "../../../$f", $f
601             or $!==&ENOENT
602             or die "$f $!";
603     }
604     runcmd @dget, qw(--), $dscurl;
605     foreach my $f (grep { is_orig_file($_) } @files) {
606         link $f, "../../../../$f"
607             or $!==&EEXIST
608             or die "$f $!";
609     }
610     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
611     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
612     my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
613     my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
614     my $author = getfield $clogp, 'Maintainer';
615     $author =~ s#,.*##ms;
616     my $authline = "$author $date";
617     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
618         fail "unexpected commit author line format \`$authline'".
619             " (was generated from changelog Maintainer field)";
620     my $changes = getfield $clogp, 'Changes';
621     open C, ">../commit.tmp" or die $!;
622     print C <<END or die $!;
623 tree $tree
624 author $authline
625 committer $authline
626
627 $changes
628
629 # imported from the archive
630 END
631     close C or die $!;
632     my $outputhash = make_commit qw(../commit.tmp);
633     my $cversion = getfield $clogp, 'Version';
634     print "synthesised git commit from .dsc $cversion\n";
635     if ($lastpush_hash) {
636         runcmd @git, qw(reset --hard), $lastpush_hash;
637         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
638         my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
639         my $oversion = getfield $oldclogp, 'Version';
640         my $vcmp =
641             version_compare_string($oversion, $cversion);
642         if ($vcmp < 0) {
643             # git upload/ is earlier vsn than archive, use archive
644             open C, ">../commit2.tmp" or die $!;
645             print C <<END or die $!;
646 tree $tree
647 parent $lastpush_hash
648 parent $outputhash
649 author $authline
650 committer $authline
651
652 Record $package ($cversion) in archive suite $csuite
653 END
654             $outputhash = make_commit qw(../commit2.tmp);
655         } elsif ($vcmp > 0) {
656             print STDERR <<END or die $!;
657
658 Version actually in archive:    $cversion (older)
659 Last allegedly pushed/uploaded: $oversion (newer or same)
660 $later_warning_msg
661 END
662             $outputhash = $lastpush_hash;
663         } else {
664             $outputhash = $lastpush_hash;
665         }
666     }
667     chdir '../../../..' or die $!;
668     runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
669             'DGIT_ARCHIVE', $outputhash;
670     cmdoutput @git, qw(log -n2), $outputhash;
671     # ... gives git a chance to complain if our commit is malformed
672     rmtree($ud);
673     return $outputhash;
674 }
675
676 sub ensure_we_have_orig () {
677     foreach my $fi (dsc_files_info()) {
678         my $f = $fi->{Filename};
679         next unless is_orig_file($f);
680         if (open F, "<", "../$f") {
681             $fi->{Digester}->reset();
682             $fi->{Digester}->addfile(*F);
683             F->error and die $!;
684             my $got = $fi->{Digester}->hexdigest();
685             $got eq $fi->{Hash} or
686                 fail "existing file $f has hash $got but .dsc".
687                     " demands hash $fi->{Hash}".
688                     " (perhaps you should delete this file?)";
689             print "using existing $f\n";
690             next;
691         } else {
692             die "$f $!" unless $!==&ENOENT;
693         }
694         my $origurl = $dscurl;
695         $origurl =~ s{/[^/]+$}{};
696         $origurl .= "/$f";
697         die "$f ?" unless $f =~ m/^${package}_/;
698         die "$f ?" if $f =~ m#/#;
699         runcmd_ordryrun_local shell_cmd 'cd ..', @dget,'--',$origurl;
700     }
701 }
702
703 sub rev_parse ($) {
704     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
705 }
706
707 sub is_fast_fwd ($$) {
708     my ($ancestor,$child) = @_;
709     my @cmd = (@git, qw(merge-base), $ancestor, $child);
710     my $mb = cmdoutput_errok @cmd;
711     if (defined $mb) {
712         return rev_parse($mb) eq rev_parse($ancestor);
713     } else {
714         $?==256 or failedcmd @cmd;
715         return 0;
716     }
717 }
718
719 sub git_fetch_us () {
720     runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
721 }
722
723 sub fetch_from_archive () {
724     # ensures that lrref() is what is actually in the archive,
725     #  one way or another
726     get_archive_dsc();
727
728     if ($dsc) {
729         foreach my $field (@ourdscfield) {
730             $dsc_hash = $dsc->{$field};
731             last if defined $dsc_hash;
732         }
733         if (defined $dsc_hash) {
734             $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
735             $dsc_hash = $&;
736             print "last upload to archive specified git hash\n";
737         } else {
738             print "last upload to archive has NO git hash\n";
739         }
740     } else {
741         print "no version available from the archive\n";
742     }
743
744     $lastpush_hash = git_get_ref(lrref());
745     print DEBUG "previous reference hash=$lastpush_hash\n";
746     my $hash;
747     if (defined $dsc_hash) {
748         fail "missing git history even though dsc has hash -".
749             " could not find commit $dsc_hash".
750             " (should be in ".access_giturl()."#".rrref().")"
751             unless $lastpush_hash;
752         $hash = $dsc_hash;
753         ensure_we_have_orig();
754         if ($dsc_hash eq $lastpush_hash) {
755         } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
756             print STDERR <<END or die $!;
757
758 Git commit in archive is behind the last version allegedly pushed/uploaded.
759 Commit referred to by archive:  $dsc_hash
760 Last allegedly pushed/uploaded: $lastpush_hash
761 $later_warning_msg
762 END
763             $hash = $lastpush_hash;
764         } else {
765             fail "archive's .dsc refers to ".$dsc_hash.
766                 " but this is an ancestor of ".$lastpush_hash;
767         }
768     } elsif ($dsc) {
769         $hash = generate_commit_from_dsc();
770     } elsif ($lastpush_hash) {
771         # only in git, not in the archive yet
772         $hash = $lastpush_hash;
773         print STDERR <<END or die $!;
774
775 Package not found in the archive, but has allegedly been pushed using dgit.
776 $later_warning_msg
777 END
778     } else {
779         print DEBUG "nothing found!\n";
780         if (defined $skew_warning_vsn) {
781             print STDERR <<END or die $!;
782
783 Warning: relevant archive skew detected.
784 Archive allegedly contains $skew_warning_vsn
785 But we were not able to obtain any version from the archive or git.
786
787 END
788         }
789         return 0;
790     }
791     print DEBUG "current hash=$hash\n";
792     if ($lastpush_hash) {
793         fail "not fast forward on last upload branch!".
794             " (archive's version left in DGIT_ARCHIVE)"
795             unless is_fast_fwd($lastpush_hash, $hash);
796     }
797     if (defined $skew_warning_vsn) {
798         mkpath '.git/dgit';
799         print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
800         my $clogf = ".git/dgit/changelog.tmp";
801         runcmd shell_cmd "exec >$clogf",
802             @git, qw(cat-file blob), "$hash:debian/changelog";
803         my $gotclogp = parsechangelog("-l$clogf");
804         my $got_vsn = getfield $gotclogp, 'Version';
805         print DEBUG "SKEW CHECK GOT $got_vsn\n";
806         if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
807             print STDERR <<END or die $!;
808
809 Warning: archive skew detected.  Using the available version:
810 Archive allegedly contains    $skew_warning_vsn
811 We were able to obtain only   $got_vsn
812
813 END
814         }
815     }
816     if ($lastpush_hash ne $hash) {
817         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
818         if ($dryrun <= 1) {
819             cmdoutput @upd_cmd;
820         } else {
821             dryrun_report @upd_cmd;
822         }
823     }
824     return 1;
825 }
826
827 sub clone ($) {
828     my ($dstdir) = @_;
829     canonicalise_suite();
830     badusage "dry run makes no sense with clone" if $dryrun > 1;
831     mkdir $dstdir or die "$dstdir $!";
832     chdir "$dstdir" or die "$dstdir $!";
833     runcmd @git, qw(init -q);
834     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
835     open H, "> .git/HEAD" or die $!;
836     print H "ref: ".lref()."\n" or die $!;
837     close H or die $!;
838     runcmd @git, qw(remote add), 'origin', access_giturl();
839     if (check_for_git()) {
840         print "fetching existing git history\n";
841         git_fetch_us();
842         runcmd_ordryrun_local @git, qw(fetch origin);
843     } else {
844         print "starting new git history\n";
845     }
846     fetch_from_archive() or no_such_package;
847     runcmd @git, qw(reset --hard), lrref();
848     printdone "ready for work in $dstdir";
849 }
850
851 sub fetch () {
852     if (check_for_git()) {
853         git_fetch_us();
854     }
855     fetch_from_archive() or no_such_package();
856     printdone "fetched into ".lrref();
857 }
858
859 sub pull () {
860     fetch();
861     runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
862         lrref();
863     printdone "fetched to ".lrref()." and merged into HEAD";
864 }
865
866 sub check_not_dirty () {
867     return if $ignoredirty;
868     my @cmd = (@git, qw(diff --quiet HEAD));
869     printcmd(\*DEBUG,"+",@cmd) if $debug>0;
870     $!=0; $?=0; system @cmd;
871     return if !$! && !$?;
872     if (!$! && $?==256) {
873         fail "working tree is dirty (does not match HEAD)";
874     } else {
875         failedcmd @cmd;
876     }
877 }
878
879 sub commit_quilty_patch () {
880     my $output = cmdoutput @git, qw(status --porcelain);
881     my %adds;
882     foreach my $l (split /\n/, $output) {
883         next unless $l =~ m/\S/;
884         if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
885             $adds{$1}++;
886         }
887     }
888     if (!%adds) {
889         print "nothing quilty to commit, ok.\n";
890         return;
891     }
892     runcmd_ordryrun_local @git, qw(add), sort keys %adds;
893     my $m = "Commit Debian 3.0 (quilt) metadata";
894     print "$m\n";
895     runcmd_ordryrun_local @git, qw(commit -m), $m;
896 }
897
898 sub madformat ($) {
899     my ($format) = @_;
900     return 0 unless $format eq '3.0 (quilt)';
901     print "Format \`$format', urgh\n";
902     if ($noquilt) {
903         print "Not doing any fixup of \`$format' due to --no-quilt-fixup";
904         return 0;
905     }
906     return 1;
907 }
908
909 sub dopush () {
910     print DEBUG "actually entering push\n";
911     my $clogp = parsechangelog();
912     $package = getfield $clogp, 'Source';
913     my $cversion = getfield $clogp, 'Version';
914     my $dscfn = dscfn($cversion);
915     stat "../$dscfn" or
916         fail "looked for .dsc $dscfn, but $!;".
917             " maybe you forgot to build";
918     $dsc = parsecontrol("../$dscfn","$dscfn");
919     my $dscpackage = getfield $dsc, 'Source';
920     my $format = getfield $dsc, 'Format';
921     my $dversion = getfield $dsc, 'Version';
922     ($dscpackage eq $package && $dversion eq $cversion) or
923         fail "$dsc is for $dscpackage $dversion".
924             " but debian/changelog is for $package $cversion";
925     print DEBUG "format $format\n";
926     if (madformat($format)) {
927         commit_quilty_patch();
928     }
929     check_not_dirty();
930     prep_ud();
931     chdir $ud or die $!;
932     print "checking that $dscfn corresponds to HEAD\n";
933     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
934     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
935     chdir '../../../..' or die $!;
936     printcmd \*DEBUG,"+",@_;
937     my @diffcmd = (@git, qw(diff --exit-code), $tree);
938     $!=0; $?=0;
939     if (system @diffcmd) {
940         if ($! && $?==256) {
941             fail "$dscfn specifies a different tree to your HEAD commit;".
942                 " perhaps you forgot to build";
943         } else {
944             failedcmd @diffcmd;
945         }
946     }
947 #fetch from alioth
948 #do fast forward check and maybe fake merge
949 #    if (!is_fast_fwd(mainbranch
950 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
951 #        map { lref($_).":".rref($_) }
952 #        (uploadbranch());
953     $dsc->{$ourdscfield[0]} = rev_parse('HEAD');
954     $dsc->save("../$dscfn.tmp") or die $!;
955     if (!$changesfile) {
956         my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
957         if (stat "$multi") {
958             $changesfile = $multi;
959         } else {
960             $!==&ENOENT or die "$multi: $!";
961             my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
962             my @cs = glob "../$pat";
963             fail "failed to find unique changes file".
964                 " (looked for $pat in .., or $multi);".
965                 " perhaps you need to use dgit -C"
966                 unless @cs==1;
967             ($changesfile) = @cs;
968         }
969     }
970     my $changes = parsecontrol($changesfile,$changesfile);
971     foreach my $field (qw(Source Distribution Version)) {
972         $changes->{$field} eq $clogp->{$field} or
973             fail "changes field $field \`$changes->{$field}'".
974                 " does not match changelog \`$clogp->{$field}'";
975     }
976     my $tag = debiantag($dversion);
977     if (!check_for_git()) {
978         create_remote_git_repo();
979     }
980     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
981     runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
982     if (!$dryrun) {
983         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
984     } else {
985         print "[new .dsc left in $dscfn.tmp]\n";
986     }
987     if ($sign) {
988         if (!defined $keyid) {
989             $keyid = access_cfg('keyid','RETURN-UNDEF');
990         }
991         my @tag_cmd = (@git, qw(tag -m),
992                        "$package release $dversion for $csuite [dgit]");
993         if ($dryrun != 1) {
994             push @tag_cmd, qw(-s);
995             push @tag_cmd, qw(-u),$keyid if defined $keyid;
996         }
997         push @tag_cmd, $tag;
998         runcmd_ordryrun_local @tag_cmd;
999         my @debsign_cmd = @debsign;
1000         push @debsign_cmd, "-k$keyid" if defined $keyid;
1001         push @debsign_cmd, $changesfile;
1002         runcmd_ordryrun @debsign_cmd;
1003     }
1004     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1005     my $host = access_cfg('upload-host','RETURN-UNDEF');
1006     my @hostarg = defined($host) ? ($host,) : ();
1007     runcmd_ordryrun @dput, @hostarg, $changesfile;
1008     printdone "pushed and uploaded $dversion";
1009 }
1010
1011 sub cmd_clone {
1012     parseopts();
1013     my $dstdir;
1014     badusage "-p is not allowed with clone; specify as argument instead"
1015         if defined $package;
1016     if (@ARGV==1) {
1017         ($package) = @ARGV;
1018     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1019         ($package,$isuite) = @ARGV;
1020     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1021         ($package,$dstdir) = @ARGV;
1022     } elsif (@ARGV==3) {
1023         ($package,$isuite,$dstdir) = @ARGV;
1024     } else {
1025         badusage "incorrect arguments to dgit clone";
1026     }
1027     $dstdir ||= "$package";
1028     clone($dstdir);
1029 }
1030
1031 sub branchsuite () {
1032     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1033     if ($branch =~ m#$lbranch_re#o) {
1034         return $1;
1035     } else {
1036         return undef;
1037     }
1038 }
1039
1040 sub fetchpullargs () {
1041     if (!defined $package) {
1042         my $sourcep = parsecontrol('debian/control','debian/control');
1043         $package = getfield $sourcep, 'Source';
1044     }
1045     if (@ARGV==0) {
1046 #       $isuite = branchsuite();  # this doesn't work because dak hates canons
1047         if (!$isuite) {
1048             my $clogp = parsechangelog();
1049             $isuite = getfield $clogp, 'Distribution';
1050         }
1051         canonicalise_suite();
1052         print "fetching from suite $csuite\n";
1053     } elsif (@ARGV==1) {
1054         ($isuite) = @ARGV;
1055         canonicalise_suite();
1056     } else {
1057         badusage "incorrect arguments to dgit fetch or dgit pull";
1058     }
1059 }
1060
1061 sub cmd_fetch {
1062     parseopts();
1063     fetchpullargs();
1064     fetch();
1065 }
1066
1067 sub cmd_pull {
1068     parseopts();
1069     fetchpullargs();
1070     pull();
1071 }
1072
1073 sub cmd_push {
1074     parseopts();
1075     badusage "-p is not allowed with dgit push" if defined $package;
1076     check_not_dirty();
1077     my $clogp = parsechangelog();
1078     $package = getfield $clogp, 'Source';
1079     if (@ARGV==0) {
1080         $isuite = getfield $clogp, 'Distribution';
1081         if ($new_package) {
1082             local ($package) = $existing_package; # this is a hack
1083             canonicalise_suite();
1084         }
1085     } else {
1086         badusage "incorrect arguments to dgit push";
1087     }
1088     if (check_for_git()) {
1089         git_fetch_us();
1090     }
1091     if (fetch_from_archive()) {
1092         is_fast_fwd(lrref(), 'HEAD') or
1093             fail "dgit push: HEAD is not a descendant".
1094                 " of the archive's version.\n".
1095                 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1096     } else {
1097         $new_package or
1098             fail "package appears to be new in this suite;".
1099                 " if this is intentional, use --new";
1100     }
1101     dopush();
1102 }
1103
1104 our $version;
1105 our $sourcechanges;
1106 our $dscfn;
1107
1108 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1109
1110 sub build_maybe_quilt_fixup () {
1111     if (!open F, "debian/source/format") {
1112         die $! unless $!==&ENOENT;
1113         return;
1114     }
1115     $_ = <F>;
1116     F->error and die $!;
1117     chomp;
1118     return unless madformat($_);
1119     # sigh
1120     my $clogp = parsechangelog();
1121     my $version = getfield $clogp, 'Version';
1122     my $author = getfield $clogp, 'Maintainer';
1123     my $headref = rev_parse('HEAD');
1124     my $time = time;
1125     my $ncommits = 3;
1126     my $patchname = "auto-$version-$headref-$time";
1127     my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1128     mkpath '.git/dgit';
1129     my $descfn = ".git/dgit/quilt-description.tmp";
1130     open O, '>', $descfn or die "$descfn: $!";
1131     $msg =~ s/\n/\n /g;
1132     $msg =~ s/^\s+$/ ./mg;
1133     print O <<END or die $!;
1134 Description: Automatically generated patch ($clogp->{Version})
1135  Last (up to) $ncommits git changes, FYI:
1136  .
1137  $msg
1138 Author: $author
1139
1140 ---
1141
1142 END
1143     close O or die $!;
1144     {
1145         local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1146         local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1147         local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1148         runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1149     }
1150
1151     if (!open P, '>>', ".pc/applied-patches") {
1152         $!==&ENOENT or die $!;
1153     } else {
1154         close P;
1155     }
1156
1157     commit_quilty_patch();
1158 }
1159
1160 sub quilt_fixup_editor () {
1161     my $descfn = $ENV{$fakeeditorenv};
1162     my $editing = $ARGV[$#ARGV];
1163     open I1, '<', $descfn or die "$descfn: $!";
1164     open I2, '<', $editing or die "$editing: $!";
1165     unlink $editing or die "$editing: $!";
1166     open O, '>', $editing or die "$editing: $!";
1167     while (<I1>) { print O or die $!; } I1->error and die $!;
1168     my $copying = 0;
1169     while (<I2>) {
1170         $copying ||= m/^\-\-\- /;
1171         next unless $copying;
1172         print O or die $!;
1173     }
1174     I2->error and die $!;
1175     close O or die $1;
1176     exit 0;
1177 }
1178
1179 sub build_prep () {
1180     badusage "-p is not allowed when building" if defined $package;
1181     check_not_dirty();
1182     my $clogp = parsechangelog();
1183     $isuite = getfield $clogp, 'Distribution';
1184     $package = getfield $clogp, 'Source';
1185     $version = getfield $clogp, 'Version';
1186     build_maybe_quilt_fixup();
1187 }
1188
1189 sub cmd_build {
1190     badusage "dgit build implies --clean=dpkg-source"
1191         if $cleanmode ne 'dpkg-source';
1192     build_prep();
1193     runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1194     printdone "build successful\n";
1195 }
1196
1197 sub cmd_git_build {
1198     badusage "dgit git-build implies --clean=dpkg-source"
1199         if $cleanmode ne 'dpkg-source';
1200     build_prep();
1201     my @cmd =
1202         (qw(git-buildpackage -us -uc --git-no-sign-tags),
1203          "--git-builder=@dpkgbuildpackage");
1204     unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1205         canonicalise_suite();
1206         push @cmd, "--git-debian-branch=".lbranch();
1207     }
1208     push @cmd, changesopts();
1209     runcmd_ordryrun_local @cmd, @ARGV;
1210     printdone "build successful\n";
1211 }
1212
1213 sub build_source {
1214     build_prep();
1215     $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1216     $dscfn = dscfn($version);
1217     if ($cleanmode eq 'dpkg-source') {
1218         runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
1219             changesopts();
1220     } else {
1221         if ($cleanmode eq 'git') {
1222             runcmd_ordryrun_local @git, qw(clean -xdf);
1223         } elsif ($cleanmode eq 'none') {
1224         } else {
1225             die "$cleanmode ?";
1226         }
1227         my $pwd = cmdoutput qw(env - pwd);
1228         my $leafdir = basename $pwd;
1229         chdir ".." or die $!;
1230         runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
1231         chdir $pwd or die $!;
1232         runcmd_ordryrun_local qw(sh -ec),
1233             'exec >$1; shift; exec "$@"','x',
1234             "../$sourcechanges",
1235             @dpkggenchanges, qw(-S), changesopts();
1236     }
1237 }
1238
1239 sub cmd_build_source {
1240     badusage "build-source takes no additional arguments" if @ARGV;
1241     build_source();
1242     printdone "source built, results in $dscfn and $sourcechanges";
1243 }
1244
1245 sub cmd_sbuild {
1246     build_source();
1247     chdir ".." or die $!;
1248     my $pat = "${package}_".(stripepoch $version)."_*.changes";
1249     if ($dryrun <= 1) {
1250         stat $dscfn or fail "$dscfn (in parent directory): $!";
1251         stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1252         foreach my $cf (glob $pat) {
1253             next if $cf eq $sourcechanges;
1254             unlink $cf or fail "remove $cf: $!";
1255         }
1256     }
1257     runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1258     runcmd_ordryrun @mergechanges, glob $pat;
1259     my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1260     if ($dryrun <= 1) {
1261         stat $multichanges or fail "$multichanges: $!";
1262     }
1263     printdone "build successful, results in $multichanges\n" or die $!;
1264 }    
1265
1266 sub cmd_quilt_fixup {
1267     badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1268     my $clogp = parsechangelog();
1269     $version = getfield $clogp, 'Version';
1270     build_maybe_quilt_fixup();
1271 }
1272
1273 sub cmd_version {
1274     print "dgit version $our_version\n" or die $!;
1275     exit 0;
1276 }
1277
1278 sub parseopts () {
1279     my $om;
1280     while (@ARGV) {
1281         last unless $ARGV[0] =~ m/^-/;
1282         $_ = shift @ARGV;
1283         last if m/^--?$/;
1284         if (m/^--/) {
1285             if (m/^--dry-run$/) {
1286                 $dryrun=2;
1287             } elsif (m/^--damp-run$/) {
1288                 $dryrun=1;
1289             } elsif (m/^--no-sign$/) {
1290                 $sign=0;
1291             } elsif (m/^--help$/) {
1292                 cmd_help();
1293             } elsif (m/^--version$/) {
1294                 cmd_version();
1295             } elsif (m/^--new$/) {
1296                 $new_package=1;
1297             } elsif (m/^--(\w+)=(.*)/s &&
1298                      ($om = $opts_opt_map{$1}) &&
1299                      length $om->[0]) {
1300                 $om->[0] = $2;
1301             } elsif (m/^--(\w+):(.*)/s &&
1302                      ($om = $opts_opt_map{$1})) {
1303                 push @$om, $2;
1304             } elsif (m/^--existing-package=(.*)/s) {
1305                 $existing_package = $1;
1306             } elsif (m/^--distro=(.*)/s) {
1307                 $idistro = $1;
1308             } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1309                 $cleanmode = $1;
1310             } elsif (m/^--clean=(.*)$/s) {
1311                 badusage "unknown cleaning mode \`$1'";
1312             } elsif (m/^--ignore-dirty$/s) {
1313                 $ignoredirty = 1;
1314             } elsif (m/^--no-quilt-fixup$/s) {
1315                 $noquilt = 1;
1316             } else {
1317                 badusage "unknown long option \`$_'";
1318             }
1319         } else {
1320             while (m/^-./s) {
1321                 if (s/^-n/-/) {
1322                     $dryrun=2;
1323                 } elsif (s/^-L/-/) {
1324                     $dryrun=1;
1325                 } elsif (s/^-h/-/) {
1326                     cmd_help();
1327                 } elsif (s/^-D/-/) {
1328                     open DEBUG, ">&STDERR" or die $!;
1329                     $debug++;
1330                 } elsif (s/^-N/-/) {
1331                     $new_package=1;
1332                 } elsif (m/^-[vm]/) {
1333                     push @changesopts, $_;
1334                     $_ = '';
1335                 } elsif (s/^-c(.*=.*)//s) {
1336                     push @git, '-c', $1;
1337                 } elsif (s/^-d(.*)//s) {
1338                     $idistro = $1;
1339                 } elsif (s/^-C(.*)//s) {
1340                     $changesfile = $1;
1341                 } elsif (s/^-k(.*)//s) {
1342                     $keyid=$1;
1343                 } elsif (s/^-wn//s) {
1344                     $cleanmode = 'none';
1345                 } elsif (s/^-wg//s) {
1346                     $cleanmode = 'git';
1347                 } elsif (s/^-wd//s) {
1348                     $cleanmode = 'dpkg-source';
1349                 } else {
1350                     badusage "unknown short option \`$_'";
1351                 }
1352             }
1353         }
1354     }
1355 }
1356
1357 if ($ENV{$fakeeditorenv}) {
1358     quilt_fixup_editor();
1359 }
1360
1361 delete $ENV{'DGET_UNPACK'};
1362
1363 parseopts();
1364 print STDERR "DRY RUN ONLY\n" if $dryrun > 1;
1365 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n" if $dryrun == 1;
1366 if (!@ARGV) {
1367     print STDERR $helpmsg or die $!;
1368     exit 8;
1369 }
1370 my $cmd = shift @ARGV;
1371 $cmd =~ y/-/_/;
1372 { no strict qw(refs); &{"cmd_$cmd"}(); }