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).".dsc";
128 our $debugprefix = '';
133 foreach my $f (@end) {
135 warn "$us: cleanup: $@" if length $@;
139 our @signames = split / /, $Config{sig_name};
141 sub waitstatusmsg () {
143 return "terminated, reporting successful completion";
144 } elsif (!($? & 255)) {
145 return "failed with error exit status ".WEXITSTATUS($?);
146 } elsif (WIFSIGNALED($?)) {
147 my $signum=WTERMSIG($?);
148 return "died due to fatal signal ".
149 ($signames[$signum] // "number $signum").
150 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
152 return "failed with unknown wait status ".$?;
156 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
159 die $us.($we_are_responder ? " (build host)" : "").": @_\n";
162 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
164 sub no_such_package () {
165 print STDERR "$us: package $package does not exist in suite $isuite\n";
171 return "+".rrref().":".lrref();
176 printdebug "CD $newdir\n";
177 chdir $newdir or die "chdir: $newdir: $!";
180 sub stat_exists ($) {
183 return 0 if $!==&ENOENT;
187 #---------- remote protocol support, common ----------
189 # remote push initiator/responder protocol:
190 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
192 # > file parsed-changelog
193 # [indicates that output of dpkg-parsechangelog follows]
194 # > data-block NBYTES
195 # > [NBYTES bytes of data (no newline)]
196 # [maybe some more blocks]
208 # [indicates that signed tag is wanted]
209 # < data-block NBYTES
210 # < [NBYTES bytes of data (no newline)]
211 # [maybe some more blocks]
215 # > want signed-dsc-changes
216 # < data-block NBYTES [transfer of signed dsc]
218 # < data-block NBYTES [transfer of signed changes]
226 sub i_child_report () {
227 # Sees if our child has died, and reap it if so. Returns a string
228 # describing how it died if it failed, or undef otherwise.
229 return undef unless $i_child_pid;
230 my $got = waitpid $i_child_pid, WNOHANG;
231 return undef if $got <= 0;
232 die unless $got == $i_child_pid;
233 $i_child_pid = undef;
234 return undef unless $?;
235 return "build host child ".waitstatusmsg();
240 fail "connection lost: $!" if $fh->error;
241 fail "protocol violation; $m not expected";
244 sub badproto_badread ($$) {
246 fail "connection lost: $!" if $!;
247 my $report = i_child_report();
248 fail $report if defined $report;
249 badproto $fh, "eof (reading $wh)";
252 sub protocol_expect (&$) {
253 my ($match, $fh) = @_;
256 defined && chomp or badproto_badread $fh, "protocol message";
264 badproto $fh, "\`$_'";
267 sub protocol_send_file ($$) {
268 my ($fh, $ourfn) = @_;
269 open PF, "<", $ourfn or die "$ourfn: $!";
272 my $got = read PF, $d, 65536;
273 die "$ourfn: $!" unless defined $got;
275 print $fh "data-block ".length($d)."\n" or die $!;
276 print $fh $d or die $!;
278 PF->error and die "$ourfn $!";
279 print $fh "data-end\n" or die $!;
283 sub protocol_read_bytes ($$) {
284 my ($fh, $nbytes) = @_;
285 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
287 my $got = read $fh, $d, $nbytes;
288 $got==$nbytes or badproto_badread $fh, "data block";
292 sub protocol_receive_file ($$) {
293 my ($fh, $ourfn) = @_;
294 printdebug "() $ourfn\n";
295 open PF, ">", $ourfn or die "$ourfn: $!";
297 my ($y,$l) = protocol_expect {
298 m/^data-block (.*)$/ ? (1,$1) :
299 m/^data-end$/ ? (0,) :
303 my $d = protocol_read_bytes $fh, $l;
304 print PF $d or die $!;
309 #---------- remote protocol support, responder ----------
311 sub responder_send_command ($) {
313 return unless $we_are_responder;
314 # called even without $we_are_responder
315 printdebug ">> $command\n";
316 print PO $command, "\n" or die $!;
319 sub responder_send_file ($$) {
320 my ($keyword, $ourfn) = @_;
321 return unless $we_are_responder;
322 printdebug "]] $keyword $ourfn\n";
323 responder_send_command "file $keyword";
324 protocol_send_file \*PO, $ourfn;
327 sub responder_receive_files ($@) {
328 my ($keyword, @ourfns) = @_;
329 die unless $we_are_responder;
330 printdebug "[[ $keyword @ourfns\n";
331 responder_send_command "want $keyword";
332 foreach my $fn (@ourfns) {
333 protocol_receive_file \*PI, $fn;
336 protocol_expect { m/^files-end$/ } \*PI;
339 #---------- remote protocol support, initiator ----------
341 sub initiator_expect (&) {
343 protocol_expect { &$match } \*RO;
346 #---------- end remote code ----------
349 if ($we_are_responder) {
351 responder_send_command "progress ".length($m) or die $!;
352 print PO $m or die $!;
362 $ua = LWP::UserAgent->new();
366 progress "downloading $what...";
367 my $r = $ua->get(@_) or die $!;
368 return undef if $r->code == 404;
369 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
370 return $r->decoded_content(charset => 'none');
373 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
380 if (m{[^-=_./0-9a-z]}i) {
387 return join ' ', @out;
392 my $intro = shift @_;
393 print $fh $intro," " or die $!;
394 print $fh shellquote @_ or die $!;
395 print $fh "\n" or die $!;
399 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
401 fail "failed to fork/exec: $!";
403 fail "subprocess ".waitstatusmsg();
405 fail "subprocess produced invalid output";
410 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
412 failedcmd @_ if system @_;
415 sub act_local () { return $dryrun_level <= 1; }
416 sub act_scary () { return !$dryrun_level; }
419 if (!$dryrun_level) {
420 progress "dgit ok: @_";
422 progress "would be ok: @_ (but dry run only)";
426 sub cmdoutput_errok {
427 die Dumper(\@_)." ?" if grep { !defined } @_;
428 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
429 open P, "-|", @_ or die $!;
432 { local $/ = undef; $d = <P>; }
434 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
437 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
442 my $d = cmdoutput_errok @_;
443 defined $d or failedcmd @_;
448 printcmd(\*STDERR,$debugprefix."#",@_);
451 sub runcmd_ordryrun {
459 sub runcmd_ordryrun_local {
468 my ($first_shell, @cmd) = @_;
469 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
472 our $helpmsg = <<END;
474 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
475 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
476 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
477 dgit [dgit-opts] push [dgit-opts] [suite]
478 dgit [dgit-opts] rpush build-host:build-dir ...
479 important dgit options:
480 -k<keyid> sign tag and package with <keyid> instead of default
481 --dry-run -n do not change anything, but go through the motions
482 --damp-run -L like --dry-run but make local changes, without signing
483 --new -N allow introducing a new package
484 --debug -D increase debug level
485 -c<name>=<value> set git config option (used directly by dgit too)
488 our $later_warning_msg = <<END;
489 Perhaps the upload is stuck in incoming. Using the version from git.
493 print STDERR "$us: @_\n", $helpmsg or die $!;
498 @ARGV or badusage "too few arguments";
499 return scalar shift @ARGV;
503 print $helpmsg or die $!;
507 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
509 our %defcfg = ('dgit.default.distro' => 'debian',
510 'dgit.default.username' => '',
511 'dgit.default.archive-query-default-component' => 'main',
512 'dgit.default.ssh' => 'ssh',
513 'dgit-distro.debian.git-host' => 'git.debian.org',
514 'dgit-distro.debian.git-proto' => 'git+ssh://',
515 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
516 'dgit-distro.debian.git-check' => 'ssh-cmd',
517 'dgit-distro.debian.git-create' => 'ssh-cmd',
518 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
519 'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
520 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
521 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
522 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
523 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
524 'dgit-distro.ubuntu.git-check' => 'false',
525 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
526 'dgit-distro.test-dummy.ssh' => "$td/ssh",
527 'dgit-distro.test-dummy.username' => "alice",
528 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
529 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
530 'dgit-distro.test-dummy.git-url' => "$td/git",
531 'dgit-distro.test-dummy.git-host' => "git",
532 'dgit-distro.test-dummy.git-path' => "$td/git",
533 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
534 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
535 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
540 return undef if $c =~ /RETURN-UNDEF/;
541 my @cmd = (@git, qw(config --), $c);
544 local ($debug) = $debug-1;
545 $v = cmdoutput_errok @cmd;
552 my $dv = $defcfg{$c};
553 return $dv if defined $dv;
555 badcfg "need value for one of: @_\n".
556 "$us: distro or suite appears not to be (properly) supported";
559 sub access_basedistro () {
560 if (defined $idistro) {
561 return cfg("dgit-distro.basedistro.distro",
562 "dgit-suite.$isuite.distro",
563 'RETURN-UNDEF') // $idistro;
565 return cfg("dgit-suite.$isuite.distro",
566 "dgit.default.distro");
570 sub access_quirk () {
571 # returns (quirk name, distro to use instead, quirk-specific info)
572 my $basedistro = access_basedistro();
573 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
575 if (defined $backports_quirk) {
576 my $re = $backports_quirk;
577 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
579 $re =~ s/\%/([-0-9a-z_]+)/
580 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
581 if ($isuite =~ m/^$re$/) {
582 return ('backports',"$basedistro-backports",$1);
585 return ('none',$basedistro);
588 sub access_distro () {
589 return (access_quirk())[1];
594 my $basedistro = access_basedistro();
595 my $distro = $idistro || access_distro();
596 my $value = cfg(map {
597 ("dgit-distro.$distro.$_",
598 "dgit-distro.$basedistro.$_",
604 sub string_to_ssh ($) {
606 if ($spec =~ m/\s/) {
607 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
613 sub access_cfg_ssh () {
614 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
615 if (!defined $gitssh) {
618 return string_to_ssh $gitssh;
622 sub access_someuserhost ($) {
624 my $user = access_cfg("$some-user",'username');
625 my $host = access_cfg("$some-host");
626 return length($user) ? "$user\@$host" : $host;
629 sub access_gituserhost () {
630 return access_someuserhost('git');
633 sub access_giturl () {
634 my $url = access_cfg('git-url','RETURN-UNDEF');
637 access_cfg('git-proto').
638 access_gituserhost().
639 access_cfg('git-path');
641 return "$url/$package.git";
644 sub parsecontrolfh ($$;$) {
645 my ($fh, $desc, $allowsigned) = @_;
646 our $dpkgcontrolhash_noissigned;
649 my %opts = ('name' => $desc);
650 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
651 $c = Dpkg::Control::Hash->new(%opts);
652 $c->parse($fh,$desc) or die "parsing of $desc failed";
653 last if $allowsigned;
654 last if $dpkgcontrolhash_noissigned;
655 my $issigned= $c->get_option('is_pgp_signed');
656 if (!defined $issigned) {
657 $dpkgcontrolhash_noissigned= 1;
658 seek $fh, 0,0 or die "seek $desc: $!";
659 } elsif ($issigned) {
660 fail "control file $desc is (already) PGP-signed. ".
661 " Note that dgit push needs to modify the .dsc and then".
662 " do the signature itself";
671 my ($file, $desc) = @_;
672 my $fh = new IO::Handle;
673 open $fh, '<', $file or die "$file: $!";
674 my $c = parsecontrolfh($fh,$desc);
675 $fh->error and die $!;
681 my ($dctrl,$field) = @_;
682 my $v = $dctrl->{$field};
683 return $v if defined $v;
684 fail "missing field $field in ".$v->get_option('name');
688 my $c = Dpkg::Control::Hash->new();
689 my $p = new IO::Handle;
690 my @cmd = (qw(dpkg-parsechangelog), @_);
691 open $p, '-|', @cmd or die $!;
693 $?=0; $!=0; close $p or failedcmd @cmd;
697 sub git_get_ref ($) {
699 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
701 $?==256 or fail "git show-ref failed (status $?)";
702 printdebug "ref $refname= [show-ref exited 1]\n";
705 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
706 printdebug "ref $refname=$1\n";
709 printdebug "ref $refname= [no match]\n";
716 defined $d or fail "getcwd failed: $!";
722 sub archive_query ($) {
724 my $query = access_cfg('archive-query','RETURN-UNDEF');
725 if (!defined $query) {
726 my $distro = access_basedistro();
727 if ($distro eq 'debian') {
729 access_someuserhost('sshpsql').':'.
730 access_cfg('sshpsql-dbname');
732 $query = "madison:$distro";
735 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
738 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
741 sub pool_dsc_subpath ($$) {
742 my ($vsn,$component) = @_; # $package is implict arg
743 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
744 return "/pool/$component/$prefix/$package/".dscfn($vsn);
747 sub archive_query_madison ($$) {
748 my ($proto,$data) = @_;
749 die unless $proto eq 'madison';
750 $rmad{$package} ||= cmdoutput
751 qw(rmadison -asource),"-s$isuite","-u$data",$package;
752 my $rmad = $rmad{$package};
753 return madison_parse($rmad);
756 sub madison_parse ($) {
759 foreach my $l (split /\n/, $rmad) {
760 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
761 \s*( [^ \t|]+ )\s* \|
762 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
763 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
764 $1 eq $package or die "$rmad $package ?";
771 $component = access_cfg('archive-query-default-component');
773 $5 eq 'source' or die "$rmad ?";
774 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
776 return sort { -version_compare($a->[0],$b->[0]); } @out;
779 sub canonicalise_suite_madison ($$) {
780 # madison canonicalises for us
781 my @r = archive_query_madison($_[0],$_[1]);
783 "unable to canonicalise suite using package $package".
784 " which does not appear to exist in suite $isuite;".
785 " --existing-package may help";
790 my ($data,$sql) = @_;
791 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
792 my ($userhost,$dbname) = ($`,$'); #';
794 my @cmd = (access_cfg_ssh, $userhost,
795 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
796 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
797 open P, "-|", @cmd or die $!;
800 printdebug("$debugprefix>|$_|\n");
803 $!=0; $?=0; close P or failedcmd @cmd;
805 my $nrows = pop @rows;
806 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
807 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
808 @rows = map { [ split /\|/, $_ ] } @rows;
809 my $ncols = scalar @{ shift @rows };
810 die if grep { scalar @$_ != $ncols } @rows;
814 sub sql_injection_check {
815 foreach (@_) { die "$_ $& ?" if m/[']/; }
818 sub archive_query_sshpsql ($$) {
819 my ($proto,$data) = @_;
820 sql_injection_check $isuite, $package;
821 my @rows = sshpsql($data, <<END);
822 SELECT source.version, component.name, files.filename, files.sha256sum
824 JOIN src_associations ON source.id = src_associations.source
825 JOIN suite ON suite.id = src_associations.suite
826 JOIN dsc_files ON dsc_files.source = source.id
827 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
828 JOIN component ON component.id = files_archive_map.component_id
829 JOIN files ON files.id = dsc_files.file
830 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
831 AND source.source='$package'
832 AND files.filename LIKE '%.dsc';
834 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
835 my $digester = Digest::SHA->new(256);
837 my ($vsn,$component,$filename,$sha256sum) = @$_;
838 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
843 sub canonicalise_suite_sshpsql ($$) {
844 my ($proto,$data) = @_;
845 sql_injection_check $isuite;
846 my @rows = sshpsql($data, <<END);
847 SELECT suite.codename
848 FROM suite where suite_name='$isuite' or codename='$isuite';
850 @rows = map { $_->[0] } @rows;
851 fail "unknown suite $isuite" unless @rows;
852 die "ambiguous $isuite: @rows ?" if @rows>1;
856 sub canonicalise_suite_dummycat ($$) {
857 my ($proto,$data) = @_;
858 my $dpath = "$data/suite.$isuite";
859 if (!open C, "<", $dpath) {
860 $!==ENOENT or die "$dpath: $!";
861 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
865 chomp or die "$dpath: $!";
867 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
871 sub archive_query_dummycat ($$) {
872 my ($proto,$data) = @_;
873 canonicalise_suite();
874 my $dpath = "$data/package.$csuite.$package";
875 if (!open C, "<", $dpath) {
876 $!==ENOENT or die "$dpath: $!";
877 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
885 printdebug "dummycat query $csuite $package $dpath | $_\n";
886 my @row = split /\s+/, $_;
887 @row==2 or die "$dpath: $_ ?";
890 C->error and die "$dpath: $!";
892 return sort { -version_compare($a->[0],$b->[0]); } @rows;
895 sub canonicalise_suite () {
896 return if defined $csuite;
897 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
898 $csuite = archive_query('canonicalise_suite');
899 if ($isuite ne $csuite) {
900 progress "canonical suite name for $isuite is $csuite";
904 sub get_archive_dsc () {
905 canonicalise_suite();
906 my @vsns = archive_query('archive_query');
907 foreach my $vinfo (@vsns) {
908 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
909 $dscurl = access_cfg('mirror').$subpath;
910 $dscdata = url_get($dscurl);
912 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
917 $digester->add($dscdata);
918 my $got = $digester->hexdigest();
920 fail "$dscurl has hash $got but".
921 " archive told us to expect $digest";
923 my $dscfh = new IO::File \$dscdata, '<' or die $!;
924 printdebug Dumper($dscdata) if $debug>1;
925 $dsc = parsecontrolfh($dscfh,$dscurl,1);
926 printdebug Dumper($dsc) if $debug>1;
927 my $fmt = getfield $dsc, 'Format';
928 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
929 $dsc_checked = !!$digester;
935 sub check_for_git () {
937 my $how = access_cfg('git-check');
938 if ($how eq 'ssh-cmd') {
940 (access_cfg_ssh, access_gituserhost(),
941 " set -e; cd ".access_cfg('git-path').";".
942 " if test -d $package.git; then echo 1; else echo 0; fi");
943 my $r= cmdoutput @cmd;
944 failedcmd @cmd unless $r =~ m/^[01]$/;
946 } elsif ($how eq 'true') {
948 } elsif ($how eq 'false') {
951 badcfg "unknown git-check \`$how'";
955 sub create_remote_git_repo () {
956 my $how = access_cfg('git-create');
957 if ($how eq 'ssh-cmd') {
959 (access_cfg_ssh, access_gituserhost(),
960 "set -e; cd ".access_cfg('git-path').";".
961 " cp -a _template $package.git");
962 } elsif ($how eq 'true') {
965 badcfg "unknown git-create \`$how'";
969 our ($dsc_hash,$lastpush_hash);
971 our $ud = '.git/dgit/unpack';
979 sub mktree_in_ud_here () {
980 runcmd qw(git init -q);
981 rmtree('.git/objects');
982 symlink '../../../../objects','.git/objects' or die $!;
985 sub mktree_in_ud_from_only_subdir () {
986 # changes into the subdir
989 $dirs[0] =~ m#^([^/]+)/\.$# or die;
992 fail "source package contains .git directory" if stat_exists '.git';
994 runcmd @git, qw(add -Af);
995 my $tree = cmdoutput @git, qw(write-tree);
996 $tree =~ m/^\w+$/ or die "$tree ?";
1000 sub dsc_files_info () {
1001 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1002 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1003 ['Files', 'Digest::MD5', 'new()']) {
1004 my ($fname, $module, $method) = @$csumi;
1005 my $field = $dsc->{$fname};
1006 next unless defined $field;
1007 eval "use $module; 1;" or die $@;
1009 foreach (split /\n/, $field) {
1011 m/^(\w+) (\d+) (\S+)$/ or
1012 fail "could not parse .dsc $fname line \`$_'";
1013 my $digester = eval "$module"."->$method;" or die $@;
1018 Digester => $digester,
1023 fail "missing any supported Checksums-* or Files field in ".
1024 $dsc->get_option('name');
1028 map { $_->{Filename} } dsc_files_info();
1031 sub is_orig_file ($;$) {
1034 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1035 defined $base or return 1;
1039 sub make_commit ($) {
1041 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1044 sub clogp_authline ($) {
1046 my $author = getfield $clogp, 'Maintainer';
1047 $author =~ s#,.*##ms;
1048 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1049 my $authline = "$author $date";
1050 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1051 fail "unexpected commit author line format \`$authline'".
1052 " (was generated from changelog Maintainer field)";
1056 sub generate_commit_from_dsc () {
1060 foreach my $fi (dsc_files_info()) {
1061 my $f = $fi->{Filename};
1062 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1064 link "../../../$f", $f
1068 complete_file_from_dsc('.', $fi);
1070 if (is_orig_file($f)) {
1071 link $f, "../../../../$f"
1077 my $dscfn = "$package.dsc";
1079 open D, ">", $dscfn or die "$dscfn: $!";
1080 print D $dscdata or die "$dscfn: $!";
1081 close D or die "$dscfn: $!";
1082 my @cmd = qw(dpkg-source);
1083 push @cmd, '--no-check' if $dsc_checked;
1084 push @cmd, qw(-x --), $dscfn;
1087 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1088 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1089 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1090 my $authline = clogp_authline $clogp;
1091 my $changes = getfield $clogp, 'Changes';
1092 open C, ">../commit.tmp" or die $!;
1093 print C <<END or die $!;
1100 # imported from the archive
1103 my $outputhash = make_commit qw(../commit.tmp);
1104 my $cversion = getfield $clogp, 'Version';
1105 progress "synthesised git commit from .dsc $cversion";
1106 if ($lastpush_hash) {
1107 runcmd @git, qw(reset --hard), $lastpush_hash;
1108 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1109 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1110 my $oversion = getfield $oldclogp, 'Version';
1112 version_compare($oversion, $cversion);
1114 # git upload/ is earlier vsn than archive, use archive
1115 open C, ">../commit2.tmp" or die $!;
1116 print C <<END or die $!;
1118 parent $lastpush_hash
1123 Record $package ($cversion) in archive suite $csuite
1125 $outputhash = make_commit qw(../commit2.tmp);
1126 } elsif ($vcmp > 0) {
1127 print STDERR <<END or die $!;
1129 Version actually in archive: $cversion (older)
1130 Last allegedly pushed/uploaded: $oversion (newer or same)
1133 $outputhash = $lastpush_hash;
1135 $outputhash = $lastpush_hash;
1138 changedir '../../../..';
1139 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1140 'DGIT_ARCHIVE', $outputhash;
1141 cmdoutput @git, qw(log -n2), $outputhash;
1142 # ... gives git a chance to complain if our commit is malformed
1147 sub complete_file_from_dsc ($$) {
1148 our ($dstdir, $fi) = @_;
1149 # Ensures that we have, in $dir, the file $fi, with the correct
1150 # contents. (Downloading it from alongside $dscurl if necessary.)
1152 my $f = $fi->{Filename};
1153 my $tf = "$dstdir/$f";
1156 if (stat_exists $tf) {
1157 progress "using existing $f";
1160 $furl =~ s{/[^/]+$}{};
1162 die "$f ?" unless $f =~ m/^${package}_/;
1163 die "$f ?" if $f =~ m#/#;
1164 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1165 next if !act_local();
1169 open F, "<", "$tf" or die "$tf: $!";
1170 $fi->{Digester}->reset();
1171 $fi->{Digester}->addfile(*F);
1172 F->error and die $!;
1173 my $got = $fi->{Digester}->hexdigest();
1174 $got eq $fi->{Hash} or
1175 fail "file $f has hash $got but .dsc".
1176 " demands hash $fi->{Hash} ".
1177 ($downloaded ? "(got wrong file from archive!)"
1178 : "(perhaps you should delete this file?)");
1181 sub ensure_we_have_orig () {
1182 foreach my $fi (dsc_files_info()) {
1183 my $f = $fi->{Filename};
1184 next unless is_orig_file($f);
1185 complete_file_from_dsc('..', $fi);
1190 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1193 sub is_fast_fwd ($$) {
1194 my ($ancestor,$child) = @_;
1195 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1196 my $mb = cmdoutput_errok @cmd;
1198 return rev_parse($mb) eq rev_parse($ancestor);
1200 $?==256 or failedcmd @cmd;
1205 sub git_fetch_us () {
1206 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1209 sub fetch_from_archive () {
1210 # ensures that lrref() is what is actually in the archive,
1211 # one way or another
1215 foreach my $field (@ourdscfield) {
1216 $dsc_hash = $dsc->{$field};
1217 last if defined $dsc_hash;
1219 if (defined $dsc_hash) {
1220 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1222 progress "last upload to archive specified git hash";
1224 progress "last upload to archive has NO git hash";
1227 progress "no version available from the archive";
1230 $lastpush_hash = git_get_ref(lrref());
1231 printdebug "previous reference hash=$lastpush_hash\n";
1233 if (defined $dsc_hash) {
1234 fail "missing remote git history even though dsc has hash -".
1235 " could not find ref ".lrref().
1236 " (should have been fetched from ".access_giturl()."#".rrref().")"
1237 unless $lastpush_hash;
1239 ensure_we_have_orig();
1240 if ($dsc_hash eq $lastpush_hash) {
1241 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1242 print STDERR <<END or die $!;
1244 Git commit in archive is behind the last version allegedly pushed/uploaded.
1245 Commit referred to by archive: $dsc_hash
1246 Last allegedly pushed/uploaded: $lastpush_hash
1249 $hash = $lastpush_hash;
1251 fail "archive's .dsc refers to ".$dsc_hash.
1252 " but this is an ancestor of ".$lastpush_hash;
1255 $hash = generate_commit_from_dsc();
1256 } elsif ($lastpush_hash) {
1257 # only in git, not in the archive yet
1258 $hash = $lastpush_hash;
1259 print STDERR <<END or die $!;
1261 Package not found in the archive, but has allegedly been pushed using dgit.
1265 printdebug "nothing found!\n";
1266 if (defined $skew_warning_vsn) {
1267 print STDERR <<END or die $!;
1269 Warning: relevant archive skew detected.
1270 Archive allegedly contains $skew_warning_vsn
1271 But we were not able to obtain any version from the archive or git.
1277 printdebug "current hash=$hash\n";
1278 if ($lastpush_hash) {
1279 fail "not fast forward on last upload branch!".
1280 " (archive's version left in DGIT_ARCHIVE)"
1281 unless is_fast_fwd($lastpush_hash, $hash);
1283 if (defined $skew_warning_vsn) {
1285 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1286 my $clogf = ".git/dgit/changelog.tmp";
1287 runcmd shell_cmd "exec >$clogf",
1288 @git, qw(cat-file blob), "$hash:debian/changelog";
1289 my $gotclogp = parsechangelog("-l$clogf");
1290 my $got_vsn = getfield $gotclogp, 'Version';
1291 printdebug "SKEW CHECK GOT $got_vsn\n";
1292 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1293 print STDERR <<END or die $!;
1295 Warning: archive skew detected. Using the available version:
1296 Archive allegedly contains $skew_warning_vsn
1297 We were able to obtain only $got_vsn
1302 if ($lastpush_hash ne $hash) {
1303 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1307 dryrun_report @upd_cmd;
1315 canonicalise_suite();
1316 badusage "dry run makes no sense with clone" unless act_local();
1317 mkdir $dstdir or die "$dstdir $!";
1319 runcmd @git, qw(init -q);
1320 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1321 open H, "> .git/HEAD" or die $!;
1322 print H "ref: ".lref()."\n" or die $!;
1324 runcmd @git, qw(remote add), 'origin', access_giturl();
1325 if (check_for_git()) {
1326 progress "fetching existing git history";
1328 runcmd_ordryrun_local @git, qw(fetch origin);
1330 progress "starting new git history";
1332 fetch_from_archive() or no_such_package;
1333 my $vcsgiturl = $dsc->{'Vcs-Git'};
1334 if (length $vcsgiturl) {
1335 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1337 runcmd @git, qw(reset --hard), lrref();
1338 printdone "ready for work in $dstdir";
1342 if (check_for_git()) {
1345 fetch_from_archive() or no_such_package();
1346 printdone "fetched into ".lrref();
1351 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1353 printdone "fetched to ".lrref()." and merged into HEAD";
1356 sub check_not_dirty () {
1357 return if $ignoredirty;
1358 my @cmd = (@git, qw(diff --quiet HEAD));
1359 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1360 $!=0; $?=0; system @cmd;
1361 return if !$! && !$?;
1362 if (!$! && $?==256) {
1363 fail "working tree is dirty (does not match HEAD)";
1369 sub commit_quilty_patch () {
1370 my $output = cmdoutput @git, qw(status --porcelain);
1372 foreach my $l (split /\n/, $output) {
1373 next unless $l =~ m/\S/;
1374 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1379 progress "nothing quilty to commit, ok.";
1382 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1383 my $m = "Commit Debian 3.0 (quilt) metadata";
1385 runcmd_ordryrun_local @git, qw(commit -m), $m;
1390 return 0 unless $format eq '3.0 (quilt)';
1391 progress "Format \`$format', urgh";
1393 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1399 sub push_parse_changelog ($) {
1402 my $clogp = Dpkg::Control::Hash->new();
1403 $clogp->load($clogpfn) or die;
1405 $package = getfield $clogp, 'Source';
1406 my $cversion = getfield $clogp, 'Version';
1407 my $tag = debiantag($cversion);
1408 runcmd @git, qw(check-ref-format), $tag;
1410 my $dscfn = dscfn($cversion);
1412 return ($clogp, $cversion, $tag, $dscfn);
1415 sub push_parse_dsc ($$$) {
1416 my ($dscfn,$dscfnwhat, $cversion) = @_;
1417 $dsc = parsecontrol($dscfn,$dscfnwhat);
1418 my $dversion = getfield $dsc, 'Version';
1419 my $dscpackage = getfield $dsc, 'Source';
1420 ($dscpackage eq $package && $dversion eq $cversion) or
1421 fail "$dscfn is for $dscpackage $dversion".
1422 " but debian/changelog is for $package $cversion";
1425 sub push_mktag ($$$$$$$) {
1426 my ($head,$clogp,$tag,
1428 $changesfile,$changesfilewhat,
1431 $dsc->{$ourdscfield[0]} = $head;
1432 $dsc->save("$dscfn.tmp") or die $!;
1434 my $changes = parsecontrol($changesfile,$changesfilewhat);
1435 foreach my $field (qw(Source Distribution Version)) {
1436 $changes->{$field} eq $clogp->{$field} or
1437 fail "changes field $field \`$changes->{$field}'".
1438 " does not match changelog \`$clogp->{$field}'";
1441 my $cversion = getfield $clogp, 'Version';
1442 my $clogsuite = getfield $clogp, 'Distribution';
1444 # We make the git tag by hand because (a) that makes it easier
1445 # to control the "tagger" (b) we can do remote signing
1446 my $authline = clogp_authline $clogp;
1447 open TO, '>', $tfn->('.tmp') or die $!;
1448 print TO <<END or die $!;
1454 $package release $cversion for $clogsuite ($csuite) [dgit]
1458 my $tagobjfn = $tfn->('.tmp');
1460 if (!defined $keyid) {
1461 $keyid = access_cfg('keyid','RETURN-UNDEF');
1463 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1464 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1465 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1466 push @sign_cmd, $tfn->('.tmp');
1467 runcmd_ordryrun @sign_cmd;
1469 $tagobjfn = $tfn->('.signed.tmp');
1470 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1471 $tfn->('.tmp'), $tfn->('.tmp.asc');
1478 sub sign_changes ($) {
1479 my ($changesfile) = @_;
1481 my @debsign_cmd = @debsign;
1482 push @debsign_cmd, "-k$keyid" if defined $keyid;
1483 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1484 push @debsign_cmd, $changesfile;
1485 runcmd_ordryrun @debsign_cmd;
1490 printdebug "actually entering push\n";
1493 access_giturl(); # check that success is vaguely likely
1495 my $clogpfn = ".git/dgit/changelog.822.tmp";
1496 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1498 responder_send_file('parsed-changelog', $clogpfn);
1500 my ($clogp, $cversion, $tag, $dscfn) =
1501 push_parse_changelog("$clogpfn");
1503 my $dscpath = "$buildproductsdir/$dscfn";
1504 stat_exists $dscpath or
1505 fail "looked for .dsc $dscfn, but $!;".
1506 " maybe you forgot to build";
1508 responder_send_file('dsc', $dscpath);
1510 push_parse_dsc($dscpath, $dscfn, $cversion);
1512 my $format = getfield $dsc, 'Format';
1513 printdebug "format $format\n";
1514 if (madformat($format)) {
1515 commit_quilty_patch();
1519 progress "checking that $dscfn corresponds to HEAD";
1520 runcmd qw(dpkg-source -x --),
1521 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1522 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1523 changedir '../../../..';
1524 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1525 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1526 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1528 my $r = system @diffcmd;
1531 fail "$dscfn specifies a different tree to your HEAD commit;".
1532 " perhaps you forgot to build".
1533 ($diffopt eq '--exit-code' ? "" :
1534 " (run with -D to see full diff output)");
1540 #do fast forward check and maybe fake merge
1541 # if (!is_fast_fwd(mainbranch
1542 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1543 # map { lref($_).":".rref($_) }
1545 my $head = rev_parse('HEAD');
1546 if (!$changesfile) {
1547 my $multi = "$buildproductsdir/".
1548 "${package}_".(stripepoch $cversion)."_multi.changes";
1549 if (stat_exists "$multi") {
1550 $changesfile = $multi;
1552 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1553 my @cs = glob "$buildproductsdir/$pat";
1554 fail "failed to find unique changes file".
1555 " (looked for $pat in $buildproductsdir, or $multi);".
1556 " perhaps you need to use dgit -C"
1558 ($changesfile) = @cs;
1561 $changesfile = "$buildproductsdir/$changesfile";
1564 responder_send_file('changes',$changesfile);
1565 responder_send_command("param head $head");
1566 responder_send_command("param csuite $csuite");
1568 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1571 if ($we_are_responder) {
1572 $tagobjfn = $tfn->('.signed.tmp');
1573 responder_receive_files('signed-tag', $tagobjfn);
1576 push_mktag($head,$clogp,$tag,
1578 $changesfile,$changesfile,
1582 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1583 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1584 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1585 runcmd_ordryrun @git, qw(tag -v --), $tag;
1587 if (!check_for_git()) {
1588 create_remote_git_repo();
1590 runcmd_ordryrun @git, qw(push),access_giturl(),
1591 "HEAD:".rrref(), "refs/tags/$tag";
1592 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1594 if ($we_are_responder) {
1595 my $dryrunsuffix = act_local() ? "" : ".tmp";
1596 responder_receive_files('signed-dsc-changes',
1597 "$dscpath$dryrunsuffix",
1598 "$changesfile$dryrunsuffix");
1601 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1603 progress "[new .dsc left in $dscpath.tmp]";
1605 sign_changes $changesfile;
1608 my $host = access_cfg('upload-host','RETURN-UNDEF');
1609 my @hostarg = defined($host) ? ($host,) : ();
1610 runcmd_ordryrun @dput, @hostarg, $changesfile;
1611 printdone "pushed and uploaded $cversion";
1613 responder_send_command("complete");
1619 badusage "-p is not allowed with clone; specify as argument instead"
1620 if defined $package;
1623 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1624 ($package,$isuite) = @ARGV;
1625 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1626 ($package,$dstdir) = @ARGV;
1627 } elsif (@ARGV==3) {
1628 ($package,$isuite,$dstdir) = @ARGV;
1630 badusage "incorrect arguments to dgit clone";
1632 $dstdir ||= "$package";
1634 if (stat_exists $dstdir) {
1635 fail "$dstdir already exists";
1639 if ($rmonerror && !$dryrun_level) {
1640 $cwd_remove= getcwd();
1642 return unless defined $cwd_remove;
1643 if (!chdir "$cwd_remove") {
1644 return if $!==&ENOENT;
1645 die "chdir $cwd_remove: $!";
1647 rmtree($dstdir) or die "remove $dstdir: $!\n";
1652 $cwd_remove = undef;
1655 sub branchsuite () {
1656 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1657 if ($branch =~ m#$lbranch_re#o) {
1664 sub fetchpullargs () {
1665 if (!defined $package) {
1666 my $sourcep = parsecontrol('debian/control','debian/control');
1667 $package = getfield $sourcep, 'Source';
1670 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1672 my $clogp = parsechangelog();
1673 $isuite = getfield $clogp, 'Distribution';
1675 canonicalise_suite();
1676 progress "fetching from suite $csuite";
1677 } elsif (@ARGV==1) {
1679 canonicalise_suite();
1681 badusage "incorrect arguments to dgit fetch or dgit pull";
1699 badusage "-p is not allowed with dgit push" if defined $package;
1701 my $clogp = parsechangelog();
1702 $package = getfield $clogp, 'Source';
1705 } elsif (@ARGV==1) {
1706 ($specsuite) = (@ARGV);
1708 badusage "incorrect arguments to dgit push";
1710 $isuite = getfield $clogp, 'Distribution';
1712 local ($package) = $existing_package; # this is a hack
1713 canonicalise_suite();
1715 if (defined $specsuite && $specsuite ne $isuite) {
1716 canonicalise_suite();
1717 $csuite eq $specsuite or
1718 fail "dgit push: changelog specifies $isuite ($csuite)".
1719 " but command line specifies $specsuite";
1721 if (check_for_git()) {
1724 if (fetch_from_archive()) {
1725 is_fast_fwd(lrref(), 'HEAD') or
1726 fail "dgit push: HEAD is not a descendant".
1727 " of the archive's version.\n".
1728 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1731 fail "package appears to be new in this suite;".
1732 " if this is intentional, use --new";
1737 #---------- remote commands' implementation ----------
1739 sub cmd_remote_push_build_host {
1740 my ($nrargs) = shift @ARGV;
1741 my (@rargs) = @ARGV[0..$nrargs-1];
1742 @ARGV = @ARGV[$nrargs..$#ARGV];
1744 my ($dir,$vsnwant) = @rargs;
1745 # vsnwant is a comma-separated list; we report which we have
1746 # chosen in our ready response (so other end can tell if they
1749 $we_are_responder = 1;
1751 open PI, "<&STDIN" or die $!;
1752 open STDIN, "/dev/null" or die $!;
1753 open PO, ">&STDOUT" or die $!;
1755 open STDOUT, ">&STDERR" or die $!;
1759 fail "build host has dgit rpush protocol version".
1760 " $rpushprotovsn but invocation host has $vsnwant"
1761 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1763 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1769 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1770 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1771 # a good error message)
1777 my $report = i_child_report();
1778 if (defined $report) {
1779 printdebug "($report)\n";
1780 } elsif ($i_child_pid) {
1781 printdebug "(killing build host child $i_child_pid)\n";
1782 kill 15, $i_child_pid;
1784 if (defined $i_tmp && !defined $initiator_tempdir) {
1786 eval { rmtree $i_tmp; };
1790 END { i_cleanup(); }
1793 my ($base,$selector,@args) = @_;
1794 $selector =~ s/\-/_/g;
1795 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1801 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1808 my @rargs = ($dir,$rpushprotovsn);
1811 push @rdgit, @ropts;
1812 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1814 my @cmd = (@ssh, $host, shellquote @rdgit);
1815 printcmd \*DEBUG,$debugprefix."+",@cmd;
1817 if (defined $initiator_tempdir) {
1818 rmtree $initiator_tempdir;
1819 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1820 $i_tmp = $initiator_tempdir;
1824 $i_child_pid = open2(\*RO, \*RI, @cmd);
1826 initiator_expect { m/^dgit-remote-push-ready/ };
1828 my ($icmd,$iargs) = initiator_expect {
1829 m/^(\S+)(?: (.*))?$/;
1832 i_method "i_resp", $icmd, $iargs;
1836 sub i_resp_progress ($) {
1838 my $msg = protocol_read_bytes \*RO, $rhs;
1842 sub i_resp_complete {
1843 my $pid = $i_child_pid;
1844 $i_child_pid = undef; # prevents killing some other process with same pid
1845 printdebug "waiting for build host child $pid...\n";
1846 my $got = waitpid $pid, 0;
1847 die $! unless $got == $pid;
1848 die "build host child failed $?" if $?;
1851 printdebug "all done\n";
1855 sub i_resp_file ($) {
1857 my $localname = i_method "i_localname", $keyword;
1858 my $localpath = "$i_tmp/$localname";
1859 stat_exists $localpath and
1860 badproto \*RO, "file $keyword ($localpath) twice";
1861 protocol_receive_file \*RO, $localpath;
1862 i_method "i_file", $keyword;
1867 sub i_resp_param ($) {
1868 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1874 sub i_resp_want ($) {
1876 die "$keyword ?" if $i_wanted{$keyword}++;
1877 my @localpaths = i_method "i_want", $keyword;
1878 printdebug "[[ $keyword @localpaths\n";
1879 foreach my $localpath (@localpaths) {
1880 protocol_send_file \*RI, $localpath;
1882 print RI "files-end\n" or die $!;
1885 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1887 sub i_localname_parsed_changelog {
1888 return "remote-changelog.822";
1890 sub i_file_parsed_changelog {
1891 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1892 push_parse_changelog "$i_tmp/remote-changelog.822";
1893 die if $i_dscfn =~ m#/|^\W#;
1896 sub i_localname_dsc {
1897 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1902 sub i_localname_changes {
1903 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1904 $i_changesfn = $i_dscfn;
1905 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1906 return $i_changesfn;
1908 sub i_file_changes { }
1910 sub i_want_signed_tag {
1911 printdebug Dumper(\%i_param, $i_dscfn);
1912 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1913 && defined $i_param{'csuite'}
1914 or badproto \*RO, "premature desire for signed-tag";
1915 my $head = $i_param{'head'};
1916 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1918 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1920 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1923 push_mktag $head, $i_clogp, $i_tag,
1925 $i_changesfn, 'remote changes',
1926 sub { "tag$_[0]"; };
1931 sub i_want_signed_dsc_changes {
1932 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1933 sign_changes $i_changesfn;
1934 return ($i_dscfn, $i_changesfn);
1937 #---------- building etc. ----------
1943 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1945 sub build_maybe_quilt_fixup () {
1946 if (!open F, "debian/source/format") {
1947 die $! unless $!==&ENOENT;
1951 F->error and die $!;
1953 return unless madformat($_);
1956 my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1957 my $problems = cmdoutput @cmd;
1958 if (length $problems) {
1959 print STDERR "problematic files:\n";
1960 print STDERR " $_\n" foreach split /\n/, $problems;
1961 fail "Cannot do quilt fixup in tree containing ignored files. ".
1962 "Perhaps your package's clean target is broken, in which".
1963 " case -wg (which says to use git-clean -xdf) may help.";
1966 my $clogp = parsechangelog();
1967 my $version = getfield $clogp, 'Version';
1968 my $author = getfield $clogp, 'Maintainer';
1969 my $headref = rev_parse('HEAD');
1972 my $patchname = "auto-$version-$headref-$time";
1973 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1975 my $descfn = ".git/dgit/quilt-description.tmp";
1976 open O, '>', $descfn or die "$descfn: $!";
1978 $msg =~ s/^\s+$/ ./mg;
1979 print O <<END or die $!;
1980 Description: Automatically generated patch ($clogp->{Version})
1981 Last (up to) $ncommits git changes, FYI:
1991 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1992 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1993 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1994 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1997 if (!open P, '>>', ".pc/applied-patches") {
1998 $!==&ENOENT or die $!;
2003 commit_quilty_patch();
2006 sub quilt_fixup_editor () {
2007 my $descfn = $ENV{$fakeeditorenv};
2008 my $editing = $ARGV[$#ARGV];
2009 open I1, '<', $descfn or die "$descfn: $!";
2010 open I2, '<', $editing or die "$editing: $!";
2011 unlink $editing or die "$editing: $!";
2012 open O, '>', $editing or die "$editing: $!";
2013 while (<I1>) { print O or die $!; } I1->error and die $!;
2016 $copying ||= m/^\-\-\- /;
2017 next unless $copying;
2020 I2->error and die $!;
2026 if ($cleanmode eq 'dpkg-source') {
2027 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2028 } elsif ($cleanmode eq 'git') {
2029 runcmd_ordryrun_local @git, qw(clean -xdf);
2030 } elsif ($cleanmode eq 'none') {
2037 badusage "clean takes no additional arguments" if @ARGV;
2042 badusage "-p is not allowed when building" if defined $package;
2045 my $clogp = parsechangelog();
2046 $isuite = getfield $clogp, 'Distribution';
2047 $package = getfield $clogp, 'Source';
2048 $version = getfield $clogp, 'Version';
2049 build_maybe_quilt_fixup();
2052 sub changesopts () {
2053 my @opts =@changesopts[1..$#changesopts];
2054 if (!defined $changes_since_version) {
2055 my @vsns = archive_query('archive_query');
2056 my @quirk = access_quirk();
2057 if ($quirk[0] eq 'backports') {
2058 local $isuite = $quirk[2];
2060 canonicalise_suite();
2061 push @vsns, archive_query('archive_query');
2064 @vsns = map { $_->[0] } @vsns;
2065 @vsns = sort { -version_compare($a, $b) } @vsns;
2066 $changes_since_version = $vsns[0];
2067 progress "changelog will contain changes since $vsns[0]";
2069 $changes_since_version = '_';
2070 progress "package seems new, not specifying -v<version>";
2073 if ($changes_since_version ne '_') {
2074 unshift @opts, "-v$changes_since_version";
2081 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2082 printdone "build successful\n";
2088 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2089 "--git-builder=@dpkgbuildpackage");
2090 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2091 canonicalise_suite();
2092 push @cmd, "--git-debian-branch=".lbranch();
2094 push @cmd, changesopts();
2095 runcmd_ordryrun_local @cmd, @ARGV;
2096 printdone "build successful\n";
2101 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2102 $dscfn = dscfn($version);
2103 if ($cleanmode eq 'dpkg-source') {
2104 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2107 my $pwd = must_getcwd();
2108 my $leafdir = basename $pwd;
2110 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2112 runcmd_ordryrun_local qw(sh -ec),
2113 'exec >$1; shift; exec "$@"','x',
2114 "../$sourcechanges",
2115 @dpkggenchanges, qw(-S), changesopts();
2119 sub cmd_build_source {
2120 badusage "build-source takes no additional arguments" if @ARGV;
2122 printdone "source built, results in $dscfn and $sourcechanges";
2128 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2130 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2131 stat_exists $sourcechanges
2132 or fail "$sourcechanges (in parent directory): $!";
2133 foreach my $cf (glob $pat) {
2134 next if $cf eq $sourcechanges;
2135 unlink $cf or fail "remove $cf: $!";
2138 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2139 my @changesfiles = glob $pat;
2140 @changesfiles = sort {
2141 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2144 fail "wrong number of different changes files (@changesfiles)"
2145 unless @changesfiles;
2146 runcmd_ordryrun_local @mergechanges, @changesfiles;
2147 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2149 stat_exists $multichanges or fail "$multichanges: $!";
2151 printdone "build successful, results in $multichanges\n" or die $!;
2154 sub cmd_quilt_fixup {
2155 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2156 my $clogp = parsechangelog();
2157 $version = getfield $clogp, 'Version';
2158 build_maybe_quilt_fixup();
2161 #---------- argument parsing and main program ----------
2164 print "dgit version $our_version\n" or die $!;
2171 if (defined $ENV{'DGIT_SSH'}) {
2172 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2173 } elsif (defined $ENV{'GIT_SSH'}) {
2174 @ssh = ($ENV{'GIT_SSH'});
2178 last unless $ARGV[0] =~ m/^-/;
2182 if (m/^--dry-run$/) {
2185 } elsif (m/^--damp-run$/) {
2188 } elsif (m/^--no-sign$/) {
2191 } elsif (m/^--help$/) {
2193 } elsif (m/^--version$/) {
2195 } elsif (m/^--new$/) {
2198 } elsif (m/^--since-version=([^_]+|_)$/) {
2200 $changes_since_version = $1;
2201 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2202 ($om = $opts_opt_map{$1}) &&
2206 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2207 !$opts_opt_cmdonly{$1} &&
2208 ($om = $opts_opt_map{$1})) {
2211 } elsif (m/^--existing-package=(.*)/s) {
2213 $existing_package = $1;
2214 } elsif (m/^--initiator-tempdir=(.*)/s) {
2215 $initiator_tempdir = $1;
2216 $initiator_tempdir =~ m#^/# or
2217 badusage "--initiator-tempdir must be used specify an".
2218 " absolute, not relative, directory."
2219 } elsif (m/^--distro=(.*)/s) {
2222 } elsif (m/^--build-products-dir=(.*)/s) {
2224 $buildproductsdir = $1;
2225 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2228 } elsif (m/^--clean=(.*)$/s) {
2229 badusage "unknown cleaning mode \`$1'";
2230 } elsif (m/^--ignore-dirty$/s) {
2233 } elsif (m/^--no-quilt-fixup$/s) {
2236 } elsif (m/^--no-rm-on-error$/s) {
2240 badusage "unknown long option \`$_'";
2247 } elsif (s/^-L/-/) {
2250 } elsif (s/^-h/-/) {
2252 } elsif (s/^-D/-/) {
2254 open DEBUG, ">&STDERR" or die $!;
2257 } elsif (s/^-N/-/) {
2260 } elsif (s/^-v([^_]+|_)$//s) {
2262 $changes_since_version = $1;
2265 push @changesopts, $_;
2267 } elsif (s/^-c(.*=.*)//s) {
2269 push @git, '-c', $1;
2270 } elsif (s/^-d(.*)//s) {
2273 } elsif (s/^-C(.*)//s) {
2276 if ($changesfile =~ s#^(.*)/##) {
2277 $buildproductsdir = $1;
2279 } elsif (s/^-k(.*)//s) {
2281 } elsif (s/^-wn//s) {
2283 $cleanmode = 'none';
2284 } elsif (s/^-wg//s) {
2287 } elsif (s/^-wd//s) {
2289 $cleanmode = 'dpkg-source';
2291 badusage "unknown short option \`$_'";
2298 if ($ENV{$fakeeditorenv}) {
2299 quilt_fixup_editor();
2303 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2304 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2305 if $dryrun_level == 1;
2307 print STDERR $helpmsg or die $!;
2310 my $cmd = shift @ARGV;
2313 my $fn = ${*::}{"cmd_$cmd"};
2314 $fn or badusage "unknown operation $cmd";