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