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