3 # Integration between git and Debian-style archives
5 # Copyright (C)2013 Ian Jackson
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.
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.
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/>.
25 use Dpkg::Control::Hash;
27 use File::Temp qw(tempdir);
35 our $our_version = 'UNRELEASED'; ###substituted###
37 our $rpushprotovsn = 2;
39 our $isuite = 'unstable';
45 our $dryrun_level = 0;
47 our $buildproductsdir = '..';
52 our $existing_package = 'dpkg';
53 our $cleanmode = 'dpkg-source';
54 our $changes_since_version;
55 our $we_are_responder;
56 our $initiator_tempdir;
58 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
60 our $suite_re = '[-+.0-9a-z]+';
63 our (@dget) = qw(dget);
64 our (@curl) = qw(curl -f);
65 our (@dput) = qw(dput);
66 our (@debsign) = qw(debsign);
68 our (@sbuild) = qw(sbuild -A);
70 our (@dgit) = qw(dgit);
71 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
72 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
73 our (@dpkggenchanges) = qw(dpkg-genchanges);
74 our (@mergechanges) = qw(mergechanges -f);
75 our (@changesopts) = ('');
77 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
80 'debsign' => \@debsign,
85 'dpkg-source' => \@dpkgsource,
86 'dpkg-buildpackage' => \@dpkgbuildpackage,
87 'dpkg-genchanges' => \@dpkggenchanges,
88 'ch' => \@changesopts,
89 'mergechanges' => \@mergechanges);
91 our %opts_opt_cmdonly = ('gpg' => 1);
96 open DEBUG, ">/dev/null" or die $!;
100 our $remotename = 'dgit';
101 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
102 our $branchprefix = 'dgit';
105 sub lbranch () { return "$branchprefix/$csuite"; }
106 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
107 sub lref () { return "refs/heads/".lbranch(); }
108 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
109 sub rrref () { return "refs/$branchprefix/$csuite"; }
124 return "${package}_".(stripepoch $vsn).$sfx
129 return srcfn($vsn,".dsc");
133 our $debugprefix = '';
138 foreach my $f (@end) {
140 warn "$us: cleanup: $@" if length $@;
144 our @signames = split / /, $Config{sig_name};
146 sub waitstatusmsg () {
148 return "terminated, reporting successful completion";
149 } elsif (!($? & 255)) {
150 return "failed with error exit status ".WEXITSTATUS($?);
151 } elsif (WIFSIGNALED($?)) {
152 my $signum=WTERMSIG($?);
153 return "died due to fatal signal ".
154 ($signames[$signum] // "number $signum").
155 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
157 return "failed with unknown wait status ".$?;
161 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
164 die $us.($we_are_responder ? " (build host)" : "").": @_\n";
167 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
169 sub no_such_package () {
170 print STDERR "$us: package $package does not exist in suite $isuite\n";
176 return "+".rrref().":".lrref();
181 printdebug "CD $newdir\n";
182 chdir $newdir or die "chdir: $newdir: $!";
185 sub stat_exists ($) {
188 return 0 if $!==&ENOENT;
192 #---------- remote protocol support, common ----------
194 # remote push initiator/responder protocol:
195 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
197 # > file parsed-changelog
198 # [indicates that output of dpkg-parsechangelog follows]
199 # > data-block NBYTES
200 # > [NBYTES bytes of data (no newline)]
201 # [maybe some more blocks]
213 # [indicates that signed tag is wanted]
214 # < data-block NBYTES
215 # < [NBYTES bytes of data (no newline)]
216 # [maybe some more blocks]
220 # > want signed-dsc-changes
221 # < data-block NBYTES [transfer of signed dsc]
223 # < data-block NBYTES [transfer of signed changes]
231 sub i_child_report () {
232 # Sees if our child has died, and reap it if so. Returns a string
233 # describing how it died if it failed, or undef otherwise.
234 return undef unless $i_child_pid;
235 my $got = waitpid $i_child_pid, WNOHANG;
236 return undef if $got <= 0;
237 die unless $got == $i_child_pid;
238 $i_child_pid = undef;
239 return undef unless $?;
240 return "build host child ".waitstatusmsg();
245 fail "connection lost: $!" if $fh->error;
246 fail "protocol violation; $m not expected";
249 sub badproto_badread ($$) {
251 fail "connection lost: $!" if $!;
252 my $report = i_child_report();
253 fail $report if defined $report;
254 badproto $fh, "eof (reading $wh)";
257 sub protocol_expect (&$) {
258 my ($match, $fh) = @_;
261 defined && chomp or badproto_badread $fh, "protocol message";
269 badproto $fh, "\`$_'";
272 sub protocol_send_file ($$) {
273 my ($fh, $ourfn) = @_;
274 open PF, "<", $ourfn or die "$ourfn: $!";
277 my $got = read PF, $d, 65536;
278 die "$ourfn: $!" unless defined $got;
280 print $fh "data-block ".length($d)."\n" or die $!;
281 print $fh $d or die $!;
283 PF->error and die "$ourfn $!";
284 print $fh "data-end\n" or die $!;
288 sub protocol_read_bytes ($$) {
289 my ($fh, $nbytes) = @_;
290 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
292 my $got = read $fh, $d, $nbytes;
293 $got==$nbytes or badproto_badread $fh, "data block";
297 sub protocol_receive_file ($$) {
298 my ($fh, $ourfn) = @_;
299 printdebug "() $ourfn\n";
300 open PF, ">", $ourfn or die "$ourfn: $!";
302 my ($y,$l) = protocol_expect {
303 m/^data-block (.*)$/ ? (1,$1) :
304 m/^data-end$/ ? (0,) :
308 my $d = protocol_read_bytes $fh, $l;
309 print PF $d or die $!;
314 #---------- remote protocol support, responder ----------
316 sub responder_send_command ($) {
318 return unless $we_are_responder;
319 # called even without $we_are_responder
320 printdebug ">> $command\n";
321 print PO $command, "\n" or die $!;
324 sub responder_send_file ($$) {
325 my ($keyword, $ourfn) = @_;
326 return unless $we_are_responder;
327 printdebug "]] $keyword $ourfn\n";
328 responder_send_command "file $keyword";
329 protocol_send_file \*PO, $ourfn;
332 sub responder_receive_files ($@) {
333 my ($keyword, @ourfns) = @_;
334 die unless $we_are_responder;
335 printdebug "[[ $keyword @ourfns\n";
336 responder_send_command "want $keyword";
337 foreach my $fn (@ourfns) {
338 protocol_receive_file \*PI, $fn;
341 protocol_expect { m/^files-end$/ } \*PI;
344 #---------- remote protocol support, initiator ----------
346 sub initiator_expect (&) {
348 protocol_expect { &$match } \*RO;
351 #---------- end remote code ----------
354 if ($we_are_responder) {
356 responder_send_command "progress ".length($m) or die $!;
357 print PO $m or die $!;
367 $ua = LWP::UserAgent->new();
371 progress "downloading $what...";
372 my $r = $ua->get(@_) or die $!;
373 return undef if $r->code == 404;
374 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
375 return $r->decoded_content(charset => 'none');
378 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
385 if (m{[^-=_./0-9a-z]}i) {
392 return join ' ', @out;
397 my $intro = shift @_;
398 print $fh $intro," " or die $!;
399 print $fh shellquote @_ or die $!;
400 print $fh "\n" or die $!;
404 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
406 fail "failed to fork/exec: $!";
408 fail "subprocess ".waitstatusmsg();
410 fail "subprocess produced invalid output";
415 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
417 failedcmd @_ if system @_;
420 sub act_local () { return $dryrun_level <= 1; }
421 sub act_scary () { return !$dryrun_level; }
424 if (!$dryrun_level) {
425 progress "dgit ok: @_";
427 progress "would be ok: @_ (but dry run only)";
431 sub cmdoutput_errok {
432 die Dumper(\@_)." ?" if grep { !defined } @_;
433 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
434 open P, "-|", @_ or die $!;
437 { local $/ = undef; $d = <P>; }
439 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
442 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
447 my $d = cmdoutput_errok @_;
448 defined $d or failedcmd @_;
453 printcmd(\*STDERR,$debugprefix."#",@_);
456 sub runcmd_ordryrun {
464 sub runcmd_ordryrun_local {
473 my ($first_shell, @cmd) = @_;
474 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
477 our $helpmsg = <<END;
479 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
480 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
481 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
482 dgit [dgit-opts] push [dgit-opts] [suite]
483 dgit [dgit-opts] rpush build-host:build-dir ...
484 important dgit options:
485 -k<keyid> sign tag and package with <keyid> instead of default
486 --dry-run -n do not change anything, but go through the motions
487 --damp-run -L like --dry-run but make local changes, without signing
488 --new -N allow introducing a new package
489 --debug -D increase debug level
490 -c<name>=<value> set git config option (used directly by dgit too)
493 our $later_warning_msg = <<END;
494 Perhaps the upload is stuck in incoming. Using the version from git.
498 print STDERR "$us: @_\n", $helpmsg or die $!;
503 @ARGV or badusage "too few arguments";
504 return scalar shift @ARGV;
508 print $helpmsg or die $!;
512 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
514 our %defcfg = ('dgit.default.distro' => 'debian',
515 'dgit.default.username' => '',
516 'dgit.default.archive-query-default-component' => 'main',
517 'dgit.default.ssh' => 'ssh',
518 'dgit-distro.debian.git-host' => 'git.debian.org',
519 'dgit-distro.debian.git-proto' => 'git+ssh://',
520 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
521 'dgit-distro.debian.git-check' => 'ssh-cmd',
522 'dgit-distro.debian.git-create' => 'ssh-cmd',
523 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
524 'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
525 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
526 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
527 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
528 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
529 'dgit-distro.ubuntu.git-check' => 'false',
530 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
531 'dgit-distro.test-dummy.ssh' => "$td/ssh",
532 'dgit-distro.test-dummy.username' => "alice",
533 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
534 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
535 'dgit-distro.test-dummy.git-url' => "$td/git",
536 'dgit-distro.test-dummy.git-host' => "git",
537 'dgit-distro.test-dummy.git-path' => "$td/git",
538 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
539 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
540 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
545 return undef if $c =~ /RETURN-UNDEF/;
546 my @cmd = (@git, qw(config --), $c);
549 local ($debug) = $debug-1;
550 $v = cmdoutput_errok @cmd;
557 my $dv = $defcfg{$c};
558 return $dv if defined $dv;
560 badcfg "need value for one of: @_\n".
561 "$us: distro or suite appears not to be (properly) supported";
564 sub access_basedistro () {
565 if (defined $idistro) {
566 return cfg("dgit-distro.basedistro.distro",
567 "dgit-suite.$isuite.distro",
568 'RETURN-UNDEF') // $idistro;
570 return cfg("dgit-suite.$isuite.distro",
571 "dgit.default.distro");
575 sub access_quirk () {
576 # returns (quirk name, distro to use instead, quirk-specific info)
577 my $basedistro = access_basedistro();
578 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
580 if (defined $backports_quirk) {
581 my $re = $backports_quirk;
582 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
584 $re =~ s/\%/([-0-9a-z_]+)/
585 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
586 if ($isuite =~ m/^$re$/) {
587 return ('backports',"$basedistro-backports",$1);
590 return ('none',$basedistro);
593 sub access_distro () {
594 return (access_quirk())[1];
599 my $basedistro = access_basedistro();
600 my $distro = $idistro || access_distro();
601 my $value = cfg(map {
602 ("dgit-distro.$distro.$_",
603 "dgit-distro.$basedistro.$_",
609 sub string_to_ssh ($) {
611 if ($spec =~ m/\s/) {
612 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
618 sub access_cfg_ssh () {
619 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
620 if (!defined $gitssh) {
623 return string_to_ssh $gitssh;
627 sub access_someuserhost ($) {
629 my $user = access_cfg("$some-user",'username');
630 my $host = access_cfg("$some-host");
631 return length($user) ? "$user\@$host" : $host;
634 sub access_gituserhost () {
635 return access_someuserhost('git');
638 sub access_giturl () {
639 my $url = access_cfg('git-url','RETURN-UNDEF');
642 access_cfg('git-proto').
643 access_gituserhost().
644 access_cfg('git-path');
646 return "$url/$package.git";
649 sub parsecontrolfh ($$;$) {
650 my ($fh, $desc, $allowsigned) = @_;
651 our $dpkgcontrolhash_noissigned;
654 my %opts = ('name' => $desc);
655 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
656 $c = Dpkg::Control::Hash->new(%opts);
657 $c->parse($fh,$desc) or die "parsing of $desc failed";
658 last if $allowsigned;
659 last if $dpkgcontrolhash_noissigned;
660 my $issigned= $c->get_option('is_pgp_signed');
661 if (!defined $issigned) {
662 $dpkgcontrolhash_noissigned= 1;
663 seek $fh, 0,0 or die "seek $desc: $!";
664 } elsif ($issigned) {
665 fail "control file $desc is (already) PGP-signed. ".
666 " Note that dgit push needs to modify the .dsc and then".
667 " do the signature itself";
676 my ($file, $desc) = @_;
677 my $fh = new IO::Handle;
678 open $fh, '<', $file or die "$file: $!";
679 my $c = parsecontrolfh($fh,$desc);
680 $fh->error and die $!;
686 my ($dctrl,$field) = @_;
687 my $v = $dctrl->{$field};
688 return $v if defined $v;
689 fail "missing field $field in ".$v->get_option('name');
693 my $c = Dpkg::Control::Hash->new();
694 my $p = new IO::Handle;
695 my @cmd = (qw(dpkg-parsechangelog), @_);
696 open $p, '-|', @cmd or die $!;
698 $?=0; $!=0; close $p or failedcmd @cmd;
702 sub git_get_ref ($) {
704 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
706 $?==256 or fail "git show-ref failed (status $?)";
707 printdebug "ref $refname= [show-ref exited 1]\n";
710 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
711 printdebug "ref $refname=$1\n";
714 printdebug "ref $refname= [no match]\n";
721 defined $d or fail "getcwd failed: $!";
727 sub archive_query ($) {
729 my $query = access_cfg('archive-query','RETURN-UNDEF');
730 if (!defined $query) {
731 my $distro = access_basedistro();
732 if ($distro eq 'debian') {
734 access_someuserhost('sshpsql').':'.
735 access_cfg('sshpsql-dbname');
737 $query = "madison:$distro";
740 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
743 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
746 sub pool_dsc_subpath ($$) {
747 my ($vsn,$component) = @_; # $package is implict arg
748 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
749 return "/pool/$component/$prefix/$package/".dscfn($vsn);
752 sub archive_query_madison ($$) {
753 my ($proto,$data) = @_;
754 die unless $proto eq 'madison';
755 $rmad{$package} ||= cmdoutput
756 qw(rmadison -asource),"-s$isuite","-u$data",$package;
757 my $rmad = $rmad{$package};
758 return madison_parse($rmad);
761 sub madison_parse ($) {
764 foreach my $l (split /\n/, $rmad) {
765 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
766 \s*( [^ \t|]+ )\s* \|
767 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
768 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
769 $1 eq $package or die "$rmad $package ?";
776 $component = access_cfg('archive-query-default-component');
778 $5 eq 'source' or die "$rmad ?";
779 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
781 return sort { -version_compare($a->[0],$b->[0]); } @out;
784 sub canonicalise_suite_madison ($$) {
785 # madison canonicalises for us
786 my @r = archive_query_madison($_[0],$_[1]);
788 "unable to canonicalise suite using package $package".
789 " which does not appear to exist in suite $isuite;".
790 " --existing-package may help";
795 my ($data,$sql) = @_;
796 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
797 my ($userhost,$dbname) = ($`,$'); #';
799 my @cmd = (access_cfg_ssh, $userhost,
800 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
801 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
802 open P, "-|", @cmd or die $!;
805 printdebug("$debugprefix>|$_|\n");
808 $!=0; $?=0; close P or failedcmd @cmd;
810 my $nrows = pop @rows;
811 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
812 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
813 @rows = map { [ split /\|/, $_ ] } @rows;
814 my $ncols = scalar @{ shift @rows };
815 die if grep { scalar @$_ != $ncols } @rows;
819 sub sql_injection_check {
820 foreach (@_) { die "$_ $& ?" if m/[']/; }
823 sub archive_query_sshpsql ($$) {
824 my ($proto,$data) = @_;
825 sql_injection_check $isuite, $package;
826 my @rows = sshpsql($data, <<END);
827 SELECT source.version, component.name, files.filename, files.sha256sum
829 JOIN src_associations ON source.id = src_associations.source
830 JOIN suite ON suite.id = src_associations.suite
831 JOIN dsc_files ON dsc_files.source = source.id
832 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
833 JOIN component ON component.id = files_archive_map.component_id
834 JOIN files ON files.id = dsc_files.file
835 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
836 AND source.source='$package'
837 AND files.filename LIKE '%.dsc';
839 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
840 my $digester = Digest::SHA->new(256);
842 my ($vsn,$component,$filename,$sha256sum) = @$_;
843 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
848 sub canonicalise_suite_sshpsql ($$) {
849 my ($proto,$data) = @_;
850 sql_injection_check $isuite;
851 my @rows = sshpsql($data, <<END);
852 SELECT suite.codename
853 FROM suite where suite_name='$isuite' or codename='$isuite';
855 @rows = map { $_->[0] } @rows;
856 fail "unknown suite $isuite" unless @rows;
857 die "ambiguous $isuite: @rows ?" if @rows>1;
861 sub canonicalise_suite_dummycat ($$) {
862 my ($proto,$data) = @_;
863 my $dpath = "$data/suite.$isuite";
864 if (!open C, "<", $dpath) {
865 $!==ENOENT or die "$dpath: $!";
866 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
870 chomp or die "$dpath: $!";
872 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
876 sub archive_query_dummycat ($$) {
877 my ($proto,$data) = @_;
878 canonicalise_suite();
879 my $dpath = "$data/package.$csuite.$package";
880 if (!open C, "<", $dpath) {
881 $!==ENOENT or die "$dpath: $!";
882 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
890 printdebug "dummycat query $csuite $package $dpath | $_\n";
891 my @row = split /\s+/, $_;
892 @row==2 or die "$dpath: $_ ?";
895 C->error and die "$dpath: $!";
897 return sort { -version_compare($a->[0],$b->[0]); } @rows;
900 sub canonicalise_suite () {
901 return if defined $csuite;
902 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
903 $csuite = archive_query('canonicalise_suite');
904 if ($isuite ne $csuite) {
905 progress "canonical suite name for $isuite is $csuite";
909 sub get_archive_dsc () {
910 canonicalise_suite();
911 my @vsns = archive_query('archive_query');
912 foreach my $vinfo (@vsns) {
913 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
914 $dscurl = access_cfg('mirror').$subpath;
915 $dscdata = url_get($dscurl);
917 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
922 $digester->add($dscdata);
923 my $got = $digester->hexdigest();
925 fail "$dscurl has hash $got but".
926 " archive told us to expect $digest";
928 my $dscfh = new IO::File \$dscdata, '<' or die $!;
929 printdebug Dumper($dscdata) if $debug>1;
930 $dsc = parsecontrolfh($dscfh,$dscurl,1);
931 printdebug Dumper($dsc) if $debug>1;
932 my $fmt = getfield $dsc, 'Format';
933 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
934 $dsc_checked = !!$digester;
940 sub check_for_git () {
942 my $how = access_cfg('git-check');
943 if ($how eq 'ssh-cmd') {
945 (access_cfg_ssh, access_gituserhost(),
946 " set -e; cd ".access_cfg('git-path').";".
947 " if test -d $package.git; then echo 1; else echo 0; fi");
948 my $r= cmdoutput @cmd;
949 failedcmd @cmd unless $r =~ m/^[01]$/;
951 } elsif ($how eq 'true') {
953 } elsif ($how eq 'false') {
956 badcfg "unknown git-check \`$how'";
960 sub create_remote_git_repo () {
961 my $how = access_cfg('git-create');
962 if ($how eq 'ssh-cmd') {
964 (access_cfg_ssh, access_gituserhost(),
965 "set -e; cd ".access_cfg('git-path').";".
966 " cp -a _template $package.git");
967 } elsif ($how eq 'true') {
970 badcfg "unknown git-create \`$how'";
974 our ($dsc_hash,$lastpush_hash);
976 our $ud = '.git/dgit/unpack';
984 sub mktree_in_ud_here () {
985 runcmd qw(git init -q);
986 rmtree('.git/objects');
987 symlink '../../../../objects','.git/objects' or die $!;
990 sub mktree_in_ud_from_only_subdir () {
991 # changes into the subdir
994 $dirs[0] =~ m#^([^/]+)/\.$# or die;
997 fail "source package contains .git directory" if stat_exists '.git';
999 runcmd @git, qw(add -Af);
1000 my $tree = cmdoutput @git, qw(write-tree);
1001 $tree =~ m/^\w+$/ or die "$tree ?";
1002 return ($tree,$dir);
1005 sub dsc_files_info () {
1006 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1007 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1008 ['Files', 'Digest::MD5', 'new()']) {
1009 my ($fname, $module, $method) = @$csumi;
1010 my $field = $dsc->{$fname};
1011 next unless defined $field;
1012 eval "use $module; 1;" or die $@;
1014 foreach (split /\n/, $field) {
1016 m/^(\w+) (\d+) (\S+)$/ or
1017 fail "could not parse .dsc $fname line \`$_'";
1018 my $digester = eval "$module"."->$method;" or die $@;
1023 Digester => $digester,
1028 fail "missing any supported Checksums-* or Files field in ".
1029 $dsc->get_option('name');
1033 map { $_->{Filename} } dsc_files_info();
1036 sub is_orig_file ($;$) {
1039 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1040 defined $base or return 1;
1044 sub make_commit ($) {
1046 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1049 sub clogp_authline ($) {
1051 my $author = getfield $clogp, 'Maintainer';
1052 $author =~ s#,.*##ms;
1053 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1054 my $authline = "$author $date";
1055 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1056 fail "unexpected commit author line format \`$authline'".
1057 " (was generated from changelog Maintainer field)";
1061 sub generate_commit_from_dsc () {
1065 foreach my $fi (dsc_files_info()) {
1066 my $f = $fi->{Filename};
1067 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1069 link "../../../$f", $f
1073 complete_file_from_dsc('.', $fi);
1075 if (is_orig_file($f)) {
1076 link $f, "../../../../$f"
1082 my $dscfn = "$package.dsc";
1084 open D, ">", $dscfn or die "$dscfn: $!";
1085 print D $dscdata or die "$dscfn: $!";
1086 close D or die "$dscfn: $!";
1087 my @cmd = qw(dpkg-source);
1088 push @cmd, '--no-check' if $dsc_checked;
1089 push @cmd, qw(-x --), $dscfn;
1092 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1093 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1094 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1095 my $authline = clogp_authline $clogp;
1096 my $changes = getfield $clogp, 'Changes';
1097 open C, ">../commit.tmp" or die $!;
1098 print C <<END or die $!;
1105 # imported from the archive
1108 my $outputhash = make_commit qw(../commit.tmp);
1109 my $cversion = getfield $clogp, 'Version';
1110 progress "synthesised git commit from .dsc $cversion";
1111 if ($lastpush_hash) {
1112 runcmd @git, qw(reset --hard), $lastpush_hash;
1113 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1114 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1115 my $oversion = getfield $oldclogp, 'Version';
1117 version_compare($oversion, $cversion);
1119 # git upload/ is earlier vsn than archive, use archive
1120 open C, ">../commit2.tmp" or die $!;
1121 print C <<END or die $!;
1123 parent $lastpush_hash
1128 Record $package ($cversion) in archive suite $csuite
1130 $outputhash = make_commit qw(../commit2.tmp);
1131 } elsif ($vcmp > 0) {
1132 print STDERR <<END or die $!;
1134 Version actually in archive: $cversion (older)
1135 Last allegedly pushed/uploaded: $oversion (newer or same)
1138 $outputhash = $lastpush_hash;
1140 $outputhash = $lastpush_hash;
1143 changedir '../../../..';
1144 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1145 'DGIT_ARCHIVE', $outputhash;
1146 cmdoutput @git, qw(log -n2), $outputhash;
1147 # ... gives git a chance to complain if our commit is malformed
1152 sub complete_file_from_dsc ($$) {
1153 our ($dstdir, $fi) = @_;
1154 # Ensures that we have, in $dir, the file $fi, with the correct
1155 # contents. (Downloading it from alongside $dscurl if necessary.)
1157 my $f = $fi->{Filename};
1158 my $tf = "$dstdir/$f";
1161 if (stat_exists $tf) {
1162 progress "using existing $f";
1165 $furl =~ s{/[^/]+$}{};
1167 die "$f ?" unless $f =~ m/^${package}_/;
1168 die "$f ?" if $f =~ m#/#;
1169 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1170 next if !act_local();
1174 open F, "<", "$tf" or die "$tf: $!";
1175 $fi->{Digester}->reset();
1176 $fi->{Digester}->addfile(*F);
1177 F->error and die $!;
1178 my $got = $fi->{Digester}->hexdigest();
1179 $got eq $fi->{Hash} or
1180 fail "file $f has hash $got but .dsc".
1181 " demands hash $fi->{Hash} ".
1182 ($downloaded ? "(got wrong file from archive!)"
1183 : "(perhaps you should delete this file?)");
1186 sub ensure_we_have_orig () {
1187 foreach my $fi (dsc_files_info()) {
1188 my $f = $fi->{Filename};
1189 next unless is_orig_file($f);
1190 complete_file_from_dsc('..', $fi);
1195 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1198 sub is_fast_fwd ($$) {
1199 my ($ancestor,$child) = @_;
1200 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1201 my $mb = cmdoutput_errok @cmd;
1203 return rev_parse($mb) eq rev_parse($ancestor);
1205 $?==256 or failedcmd @cmd;
1210 sub git_fetch_us () {
1211 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1214 sub fetch_from_archive () {
1215 # ensures that lrref() is what is actually in the archive,
1216 # one way or another
1220 foreach my $field (@ourdscfield) {
1221 $dsc_hash = $dsc->{$field};
1222 last if defined $dsc_hash;
1224 if (defined $dsc_hash) {
1225 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1227 progress "last upload to archive specified git hash";
1229 progress "last upload to archive has NO git hash";
1232 progress "no version available from the archive";
1235 $lastpush_hash = git_get_ref(lrref());
1236 printdebug "previous reference hash=$lastpush_hash\n";
1238 if (defined $dsc_hash) {
1239 fail "missing remote git history even though dsc has hash -".
1240 " could not find ref ".lrref().
1241 " (should have been fetched from ".access_giturl()."#".rrref().")"
1242 unless $lastpush_hash;
1244 ensure_we_have_orig();
1245 if ($dsc_hash eq $lastpush_hash) {
1246 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1247 print STDERR <<END or die $!;
1249 Git commit in archive is behind the last version allegedly pushed/uploaded.
1250 Commit referred to by archive: $dsc_hash
1251 Last allegedly pushed/uploaded: $lastpush_hash
1254 $hash = $lastpush_hash;
1256 fail "archive's .dsc refers to ".$dsc_hash.
1257 " but this is an ancestor of ".$lastpush_hash;
1260 $hash = generate_commit_from_dsc();
1261 } elsif ($lastpush_hash) {
1262 # only in git, not in the archive yet
1263 $hash = $lastpush_hash;
1264 print STDERR <<END or die $!;
1266 Package not found in the archive, but has allegedly been pushed using dgit.
1270 printdebug "nothing found!\n";
1271 if (defined $skew_warning_vsn) {
1272 print STDERR <<END or die $!;
1274 Warning: relevant archive skew detected.
1275 Archive allegedly contains $skew_warning_vsn
1276 But we were not able to obtain any version from the archive or git.
1282 printdebug "current hash=$hash\n";
1283 if ($lastpush_hash) {
1284 fail "not fast forward on last upload branch!".
1285 " (archive's version left in DGIT_ARCHIVE)"
1286 unless is_fast_fwd($lastpush_hash, $hash);
1288 if (defined $skew_warning_vsn) {
1290 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1291 my $clogf = ".git/dgit/changelog.tmp";
1292 runcmd shell_cmd "exec >$clogf",
1293 @git, qw(cat-file blob), "$hash:debian/changelog";
1294 my $gotclogp = parsechangelog("-l$clogf");
1295 my $got_vsn = getfield $gotclogp, 'Version';
1296 printdebug "SKEW CHECK GOT $got_vsn\n";
1297 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1298 print STDERR <<END or die $!;
1300 Warning: archive skew detected. Using the available version:
1301 Archive allegedly contains $skew_warning_vsn
1302 We were able to obtain only $got_vsn
1307 if ($lastpush_hash ne $hash) {
1308 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1312 dryrun_report @upd_cmd;
1320 canonicalise_suite();
1321 badusage "dry run makes no sense with clone" unless act_local();
1322 mkdir $dstdir or die "$dstdir $!";
1324 runcmd @git, qw(init -q);
1325 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1326 open H, "> .git/HEAD" or die $!;
1327 print H "ref: ".lref()."\n" or die $!;
1329 runcmd @git, qw(remote add), 'origin', access_giturl();
1330 if (check_for_git()) {
1331 progress "fetching existing git history";
1333 runcmd_ordryrun_local @git, qw(fetch origin);
1335 progress "starting new git history";
1337 fetch_from_archive() or no_such_package;
1338 my $vcsgiturl = $dsc->{'Vcs-Git'};
1339 if (length $vcsgiturl) {
1340 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1342 runcmd @git, qw(reset --hard), lrref();
1343 printdone "ready for work in $dstdir";
1347 if (check_for_git()) {
1350 fetch_from_archive() or no_such_package();
1351 printdone "fetched into ".lrref();
1356 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1358 printdone "fetched to ".lrref()." and merged into HEAD";
1361 sub check_not_dirty () {
1362 return if $ignoredirty;
1363 my @cmd = (@git, qw(diff --quiet HEAD));
1364 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1365 $!=0; $?=0; system @cmd;
1366 return if !$! && !$?;
1367 if (!$! && $?==256) {
1368 fail "working tree is dirty (does not match HEAD)";
1374 sub commit_admin ($) {
1377 runcmd_ordryrun_local @git, qw(commit -m), $m;
1380 sub commit_quilty_patch () {
1381 my $output = cmdoutput @git, qw(status --porcelain);
1383 foreach my $l (split /\n/, $output) {
1384 next unless $l =~ m/\S/;
1385 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1390 progress "nothing quilty to commit, ok.";
1393 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1394 commit_admin "Commit Debian 3.0 (quilt) metadata";
1397 sub get_source_format () {
1398 if (!open F, "debian/source/format") {
1399 die $! unless $!==&ENOENT;
1403 F->error and die $!;
1410 return 0 unless $format eq '3.0 (quilt)';
1411 progress "Format \`$format', urgh";
1413 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1419 sub push_parse_changelog ($) {
1422 my $clogp = Dpkg::Control::Hash->new();
1423 $clogp->load($clogpfn) or die;
1425 $package = getfield $clogp, 'Source';
1426 my $cversion = getfield $clogp, 'Version';
1427 my $tag = debiantag($cversion);
1428 runcmd @git, qw(check-ref-format), $tag;
1430 my $dscfn = dscfn($cversion);
1432 return ($clogp, $cversion, $tag, $dscfn);
1435 sub push_parse_dsc ($$$) {
1436 my ($dscfn,$dscfnwhat, $cversion) = @_;
1437 $dsc = parsecontrol($dscfn,$dscfnwhat);
1438 my $dversion = getfield $dsc, 'Version';
1439 my $dscpackage = getfield $dsc, 'Source';
1440 ($dscpackage eq $package && $dversion eq $cversion) or
1441 fail "$dscfn is for $dscpackage $dversion".
1442 " but debian/changelog is for $package $cversion";
1445 sub push_mktag ($$$$$$$) {
1446 my ($head,$clogp,$tag,
1448 $changesfile,$changesfilewhat,
1451 $dsc->{$ourdscfield[0]} = $head;
1452 $dsc->save("$dscfn.tmp") or die $!;
1454 my $changes = parsecontrol($changesfile,$changesfilewhat);
1455 foreach my $field (qw(Source Distribution Version)) {
1456 $changes->{$field} eq $clogp->{$field} or
1457 fail "changes field $field \`$changes->{$field}'".
1458 " does not match changelog \`$clogp->{$field}'";
1461 my $cversion = getfield $clogp, 'Version';
1462 my $clogsuite = getfield $clogp, 'Distribution';
1464 # We make the git tag by hand because (a) that makes it easier
1465 # to control the "tagger" (b) we can do remote signing
1466 my $authline = clogp_authline $clogp;
1467 open TO, '>', $tfn->('.tmp') or die $!;
1468 print TO <<END or die $!;
1474 $package release $cversion for $clogsuite ($csuite) [dgit]
1478 my $tagobjfn = $tfn->('.tmp');
1480 if (!defined $keyid) {
1481 $keyid = access_cfg('keyid','RETURN-UNDEF');
1483 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1484 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1485 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1486 push @sign_cmd, $tfn->('.tmp');
1487 runcmd_ordryrun @sign_cmd;
1489 $tagobjfn = $tfn->('.signed.tmp');
1490 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1491 $tfn->('.tmp'), $tfn->('.tmp.asc');
1498 sub sign_changes ($) {
1499 my ($changesfile) = @_;
1501 my @debsign_cmd = @debsign;
1502 push @debsign_cmd, "-k$keyid" if defined $keyid;
1503 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1504 push @debsign_cmd, $changesfile;
1505 runcmd_ordryrun @debsign_cmd;
1510 printdebug "actually entering push\n";
1513 access_giturl(); # check that success is vaguely likely
1515 my $clogpfn = ".git/dgit/changelog.822.tmp";
1516 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1518 responder_send_file('parsed-changelog', $clogpfn);
1520 my ($clogp, $cversion, $tag, $dscfn) =
1521 push_parse_changelog("$clogpfn");
1523 my $dscpath = "$buildproductsdir/$dscfn";
1524 stat_exists $dscpath or
1525 fail "looked for .dsc $dscfn, but $!;".
1526 " maybe you forgot to build";
1528 responder_send_file('dsc', $dscpath);
1530 push_parse_dsc($dscpath, $dscfn, $cversion);
1532 my $format = getfield $dsc, 'Format';
1533 printdebug "format $format\n";
1534 if (madformat($format)) {
1535 commit_quilty_patch();
1539 progress "checking that $dscfn corresponds to HEAD";
1540 runcmd qw(dpkg-source -x --),
1541 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1542 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1543 changedir '../../../..';
1544 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1545 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1546 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1548 my $r = system @diffcmd;
1551 fail "$dscfn specifies a different tree to your HEAD commit;".
1552 " perhaps you forgot to build".
1553 ($diffopt eq '--exit-code' ? "" :
1554 " (run with -D to see full diff output)");
1560 #do fast forward check and maybe fake merge
1561 # if (!is_fast_fwd(mainbranch
1562 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1563 # map { lref($_).":".rref($_) }
1565 my $head = rev_parse('HEAD');
1566 if (!$changesfile) {
1567 my $multi = "$buildproductsdir/".
1568 "${package}_".(stripepoch $cversion)."_multi.changes";
1569 if (stat_exists "$multi") {
1570 $changesfile = $multi;
1572 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1573 my @cs = glob "$buildproductsdir/$pat";
1574 fail "failed to find unique changes file".
1575 " (looked for $pat in $buildproductsdir, or $multi);".
1576 " perhaps you need to use dgit -C"
1578 ($changesfile) = @cs;
1581 $changesfile = "$buildproductsdir/$changesfile";
1584 responder_send_file('changes',$changesfile);
1585 responder_send_command("param head $head");
1586 responder_send_command("param csuite $csuite");
1588 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1591 if ($we_are_responder) {
1592 $tagobjfn = $tfn->('.signed.tmp');
1593 responder_receive_files('signed-tag', $tagobjfn);
1596 push_mktag($head,$clogp,$tag,
1598 $changesfile,$changesfile,
1602 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1603 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1604 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1605 runcmd_ordryrun @git, qw(tag -v --), $tag;
1607 if (!check_for_git()) {
1608 create_remote_git_repo();
1610 runcmd_ordryrun @git, qw(push),access_giturl(),
1611 "HEAD:".rrref(), "refs/tags/$tag";
1612 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1614 if ($we_are_responder) {
1615 my $dryrunsuffix = act_local() ? "" : ".tmp";
1616 responder_receive_files('signed-dsc-changes',
1617 "$dscpath$dryrunsuffix",
1618 "$changesfile$dryrunsuffix");
1621 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1623 progress "[new .dsc left in $dscpath.tmp]";
1625 sign_changes $changesfile;
1628 my $host = access_cfg('upload-host','RETURN-UNDEF');
1629 my @hostarg = defined($host) ? ($host,) : ();
1630 runcmd_ordryrun @dput, @hostarg, $changesfile;
1631 printdone "pushed and uploaded $cversion";
1633 responder_send_command("complete");
1639 badusage "-p is not allowed with clone; specify as argument instead"
1640 if defined $package;
1643 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1644 ($package,$isuite) = @ARGV;
1645 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1646 ($package,$dstdir) = @ARGV;
1647 } elsif (@ARGV==3) {
1648 ($package,$isuite,$dstdir) = @ARGV;
1650 badusage "incorrect arguments to dgit clone";
1652 $dstdir ||= "$package";
1654 if (stat_exists $dstdir) {
1655 fail "$dstdir already exists";
1659 if ($rmonerror && !$dryrun_level) {
1660 $cwd_remove= getcwd();
1662 return unless defined $cwd_remove;
1663 if (!chdir "$cwd_remove") {
1664 return if $!==&ENOENT;
1665 die "chdir $cwd_remove: $!";
1667 rmtree($dstdir) or die "remove $dstdir: $!\n";
1672 $cwd_remove = undef;
1675 sub branchsuite () {
1676 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1677 if ($branch =~ m#$lbranch_re#o) {
1684 sub fetchpullargs () {
1685 if (!defined $package) {
1686 my $sourcep = parsecontrol('debian/control','debian/control');
1687 $package = getfield $sourcep, 'Source';
1690 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1692 my $clogp = parsechangelog();
1693 $isuite = getfield $clogp, 'Distribution';
1695 canonicalise_suite();
1696 progress "fetching from suite $csuite";
1697 } elsif (@ARGV==1) {
1699 canonicalise_suite();
1701 badusage "incorrect arguments to dgit fetch or dgit pull";
1719 badusage "-p is not allowed with dgit push" if defined $package;
1721 my $clogp = parsechangelog();
1722 $package = getfield $clogp, 'Source';
1725 } elsif (@ARGV==1) {
1726 ($specsuite) = (@ARGV);
1728 badusage "incorrect arguments to dgit push";
1730 $isuite = getfield $clogp, 'Distribution';
1732 local ($package) = $existing_package; # this is a hack
1733 canonicalise_suite();
1735 if (defined $specsuite && $specsuite ne $isuite) {
1736 canonicalise_suite();
1737 $csuite eq $specsuite or
1738 fail "dgit push: changelog specifies $isuite ($csuite)".
1739 " but command line specifies $specsuite";
1741 if (check_for_git()) {
1744 if (fetch_from_archive()) {
1745 is_fast_fwd(lrref(), 'HEAD') or
1746 fail "dgit push: HEAD is not a descendant".
1747 " of the archive's version.\n".
1748 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1751 fail "package appears to be new in this suite;".
1752 " if this is intentional, use --new";
1757 #---------- remote commands' implementation ----------
1759 sub cmd_remote_push_build_host {
1760 my ($nrargs) = shift @ARGV;
1761 my (@rargs) = @ARGV[0..$nrargs-1];
1762 @ARGV = @ARGV[$nrargs..$#ARGV];
1764 my ($dir,$vsnwant) = @rargs;
1765 # vsnwant is a comma-separated list; we report which we have
1766 # chosen in our ready response (so other end can tell if they
1769 $we_are_responder = 1;
1771 open PI, "<&STDIN" or die $!;
1772 open STDIN, "/dev/null" or die $!;
1773 open PO, ">&STDOUT" or die $!;
1775 open STDOUT, ">&STDERR" or die $!;
1779 fail "build host has dgit rpush protocol version".
1780 " $rpushprotovsn but invocation host has $vsnwant"
1781 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1783 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1789 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1790 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1791 # a good error message)
1797 my $report = i_child_report();
1798 if (defined $report) {
1799 printdebug "($report)\n";
1800 } elsif ($i_child_pid) {
1801 printdebug "(killing build host child $i_child_pid)\n";
1802 kill 15, $i_child_pid;
1804 if (defined $i_tmp && !defined $initiator_tempdir) {
1806 eval { rmtree $i_tmp; };
1810 END { i_cleanup(); }
1813 my ($base,$selector,@args) = @_;
1814 $selector =~ s/\-/_/g;
1815 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1821 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1828 my @rargs = ($dir,$rpushprotovsn);
1831 push @rdgit, @ropts;
1832 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1834 my @cmd = (@ssh, $host, shellquote @rdgit);
1835 printcmd \*DEBUG,$debugprefix."+",@cmd;
1837 if (defined $initiator_tempdir) {
1838 rmtree $initiator_tempdir;
1839 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1840 $i_tmp = $initiator_tempdir;
1844 $i_child_pid = open2(\*RO, \*RI, @cmd);
1846 initiator_expect { m/^dgit-remote-push-ready/ };
1848 my ($icmd,$iargs) = initiator_expect {
1849 m/^(\S+)(?: (.*))?$/;
1852 i_method "i_resp", $icmd, $iargs;
1856 sub i_resp_progress ($) {
1858 my $msg = protocol_read_bytes \*RO, $rhs;
1862 sub i_resp_complete {
1863 my $pid = $i_child_pid;
1864 $i_child_pid = undef; # prevents killing some other process with same pid
1865 printdebug "waiting for build host child $pid...\n";
1866 my $got = waitpid $pid, 0;
1867 die $! unless $got == $pid;
1868 die "build host child failed $?" if $?;
1871 printdebug "all done\n";
1875 sub i_resp_file ($) {
1877 my $localname = i_method "i_localname", $keyword;
1878 my $localpath = "$i_tmp/$localname";
1879 stat_exists $localpath and
1880 badproto \*RO, "file $keyword ($localpath) twice";
1881 protocol_receive_file \*RO, $localpath;
1882 i_method "i_file", $keyword;
1887 sub i_resp_param ($) {
1888 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1894 sub i_resp_want ($) {
1896 die "$keyword ?" if $i_wanted{$keyword}++;
1897 my @localpaths = i_method "i_want", $keyword;
1898 printdebug "[[ $keyword @localpaths\n";
1899 foreach my $localpath (@localpaths) {
1900 protocol_send_file \*RI, $localpath;
1902 print RI "files-end\n" or die $!;
1905 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1907 sub i_localname_parsed_changelog {
1908 return "remote-changelog.822";
1910 sub i_file_parsed_changelog {
1911 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1912 push_parse_changelog "$i_tmp/remote-changelog.822";
1913 die if $i_dscfn =~ m#/|^\W#;
1916 sub i_localname_dsc {
1917 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1922 sub i_localname_changes {
1923 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1924 $i_changesfn = $i_dscfn;
1925 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1926 return $i_changesfn;
1928 sub i_file_changes { }
1930 sub i_want_signed_tag {
1931 printdebug Dumper(\%i_param, $i_dscfn);
1932 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1933 && defined $i_param{'csuite'}
1934 or badproto \*RO, "premature desire for signed-tag";
1935 my $head = $i_param{'head'};
1936 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1938 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1940 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1943 push_mktag $head, $i_clogp, $i_tag,
1945 $i_changesfn, 'remote changes',
1946 sub { "tag$_[0]"; };
1951 sub i_want_signed_dsc_changes {
1952 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1953 sign_changes $i_changesfn;
1954 return ($i_dscfn, $i_changesfn);
1957 #---------- building etc. ----------
1963 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1965 sub build_maybe_quilt_fixup () {
1966 my $format=get_source_format;
1967 return unless madformat $format;
1970 my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1971 my $problems = cmdoutput @cmd;
1972 if (length $problems) {
1973 print STDERR "problematic files:\n";
1974 print STDERR " $_\n" foreach split /\n/, $problems;
1975 fail "Cannot do quilt fixup in tree containing ignored files. ".
1976 "Perhaps your package's clean target is broken, in which".
1977 " case -wg (which says to use git-clean -xdf) may help.";
1980 my $clogp = parsechangelog();
1981 my $version = getfield $clogp, 'Version';
1982 my $author = getfield $clogp, 'Maintainer';
1983 my $headref = rev_parse('HEAD');
1986 my $patchname = "auto-$version-$headref-$time";
1987 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1989 my $descfn = ".git/dgit/quilt-description.tmp";
1990 open O, '>', $descfn or die "$descfn: $!";
1992 $msg =~ s/^\s+$/ ./mg;
1993 print O <<END or die $!;
1994 Description: Automatically generated patch ($clogp->{Version})
1995 Last (up to) $ncommits git changes, FYI:
2005 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2006 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2007 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2008 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2011 if (!open P, '>>', ".pc/applied-patches") {
2012 $!==&ENOENT or die $!;
2017 commit_quilty_patch();
2020 sub quilt_fixup_editor () {
2021 my $descfn = $ENV{$fakeeditorenv};
2022 my $editing = $ARGV[$#ARGV];
2023 open I1, '<', $descfn or die "$descfn: $!";
2024 open I2, '<', $editing or die "$editing: $!";
2025 unlink $editing or die "$editing: $!";
2026 open O, '>', $editing or die "$editing: $!";
2027 while (<I1>) { print O or die $!; } I1->error and die $!;
2030 $copying ||= m/^\-\-\- /;
2031 next unless $copying;
2034 I2->error and die $!;
2040 if ($cleanmode eq 'dpkg-source') {
2041 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2042 } elsif ($cleanmode eq 'git') {
2043 runcmd_ordryrun_local @git, qw(clean -xdf);
2044 } elsif ($cleanmode eq 'none') {
2051 badusage "clean takes no additional arguments" if @ARGV;
2056 badusage "-p is not allowed when building" if defined $package;
2059 my $clogp = parsechangelog();
2060 $isuite = getfield $clogp, 'Distribution';
2061 $package = getfield $clogp, 'Source';
2062 $version = getfield $clogp, 'Version';
2063 build_maybe_quilt_fixup();
2066 sub changesopts () {
2067 my @opts =@changesopts[1..$#changesopts];
2068 if (!defined $changes_since_version) {
2069 my @vsns = archive_query('archive_query');
2070 my @quirk = access_quirk();
2071 if ($quirk[0] eq 'backports') {
2072 local $isuite = $quirk[2];
2074 canonicalise_suite();
2075 push @vsns, archive_query('archive_query');
2078 @vsns = map { $_->[0] } @vsns;
2079 @vsns = sort { -version_compare($a, $b) } @vsns;
2080 $changes_since_version = $vsns[0];
2081 progress "changelog will contain changes since $vsns[0]";
2083 $changes_since_version = '_';
2084 progress "package seems new, not specifying -v<version>";
2087 if ($changes_since_version ne '_') {
2088 unshift @opts, "-v$changes_since_version";
2095 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2096 printdone "build successful\n";
2102 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2103 "--git-builder=@dpkgbuildpackage");
2104 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2105 canonicalise_suite();
2106 push @cmd, "--git-debian-branch=".lbranch();
2108 push @cmd, changesopts();
2109 runcmd_ordryrun_local @cmd, @ARGV;
2110 printdone "build successful\n";
2115 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2116 $dscfn = dscfn($version);
2117 if ($cleanmode eq 'dpkg-source') {
2118 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2121 my $pwd = must_getcwd();
2122 my $leafdir = basename $pwd;
2124 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2126 runcmd_ordryrun_local qw(sh -ec),
2127 'exec >$1; shift; exec "$@"','x',
2128 "../$sourcechanges",
2129 @dpkggenchanges, qw(-S), changesopts();
2133 sub cmd_build_source {
2134 badusage "build-source takes no additional arguments" if @ARGV;
2136 printdone "source built, results in $dscfn and $sourcechanges";
2142 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2144 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2145 stat_exists $sourcechanges
2146 or fail "$sourcechanges (in parent directory): $!";
2147 foreach my $cf (glob $pat) {
2148 next if $cf eq $sourcechanges;
2149 unlink $cf or fail "remove $cf: $!";
2152 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2153 my @changesfiles = glob $pat;
2154 @changesfiles = sort {
2155 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2158 fail "wrong number of different changes files (@changesfiles)"
2159 unless @changesfiles;
2160 runcmd_ordryrun_local @mergechanges, @changesfiles;
2161 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2163 stat_exists $multichanges or fail "$multichanges: $!";
2165 printdone "build successful, results in $multichanges\n" or die $!;
2168 sub cmd_quilt_fixup {
2169 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2170 my $clogp = parsechangelog();
2171 $version = getfield $clogp, 'Version';
2172 build_maybe_quilt_fixup();
2175 #---------- argument parsing and main program ----------
2178 print "dgit version $our_version\n" or die $!;
2185 if (defined $ENV{'DGIT_SSH'}) {
2186 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2187 } elsif (defined $ENV{'GIT_SSH'}) {
2188 @ssh = ($ENV{'GIT_SSH'});
2192 last unless $ARGV[0] =~ m/^-/;
2196 if (m/^--dry-run$/) {
2199 } elsif (m/^--damp-run$/) {
2202 } elsif (m/^--no-sign$/) {
2205 } elsif (m/^--help$/) {
2207 } elsif (m/^--version$/) {
2209 } elsif (m/^--new$/) {
2212 } elsif (m/^--since-version=([^_]+|_)$/) {
2214 $changes_since_version = $1;
2215 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2216 ($om = $opts_opt_map{$1}) &&
2220 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2221 !$opts_opt_cmdonly{$1} &&
2222 ($om = $opts_opt_map{$1})) {
2225 } elsif (m/^--existing-package=(.*)/s) {
2227 $existing_package = $1;
2228 } elsif (m/^--initiator-tempdir=(.*)/s) {
2229 $initiator_tempdir = $1;
2230 $initiator_tempdir =~ m#^/# or
2231 badusage "--initiator-tempdir must be used specify an".
2232 " absolute, not relative, directory."
2233 } elsif (m/^--distro=(.*)/s) {
2236 } elsif (m/^--build-products-dir=(.*)/s) {
2238 $buildproductsdir = $1;
2239 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2242 } elsif (m/^--clean=(.*)$/s) {
2243 badusage "unknown cleaning mode \`$1'";
2244 } elsif (m/^--ignore-dirty$/s) {
2247 } elsif (m/^--no-quilt-fixup$/s) {
2250 } elsif (m/^--no-rm-on-error$/s) {
2254 badusage "unknown long option \`$_'";
2261 } elsif (s/^-L/-/) {
2264 } elsif (s/^-h/-/) {
2266 } elsif (s/^-D/-/) {
2268 open DEBUG, ">&STDERR" or die $!;
2271 } elsif (s/^-N/-/) {
2274 } elsif (s/^-v([^_]+|_)$//s) {
2276 $changes_since_version = $1;
2279 push @changesopts, $_;
2281 } elsif (s/^-c(.*=.*)//s) {
2283 push @git, '-c', $1;
2284 } elsif (s/^-d(.*)//s) {
2287 } elsif (s/^-C(.*)//s) {
2290 if ($changesfile =~ s#^(.*)/##) {
2291 $buildproductsdir = $1;
2293 } elsif (s/^-k(.*)//s) {
2295 } elsif (s/^-wn//s) {
2297 $cleanmode = 'none';
2298 } elsif (s/^-wg//s) {
2301 } elsif (s/^-wd//s) {
2303 $cleanmode = 'dpkg-source';
2305 badusage "unknown short option \`$_'";
2312 if ($ENV{$fakeeditorenv}) {
2313 quilt_fixup_editor();
2317 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2318 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2319 if $dryrun_level == 1;
2321 print STDERR $helpmsg or die $!;
2324 my $cmd = shift @ARGV;
2327 my $fn = ${*::}{"cmd_$cmd"};
2328 $fn or badusage "unknown operation $cmd";