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