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