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