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