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