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