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 $isuite = 'unstable';
43 our $dryrun_level = 0;
45 our $buildproductsdir = '..';
50 our $existing_package = 'dpkg';
51 our $cleanmode = 'dpkg-source';
52 our $changes_since_version;
53 our $we_are_responder;
54 our $initiator_tempdir;
56 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
58 our $suite_re = '[-+.0-9a-z]+';
61 our (@dget) = qw(dget);
62 our (@curl) = qw(curl -f);
63 our (@dput) = qw(dput);
64 our (@debsign) = qw(debsign);
66 our (@sbuild) = qw(sbuild -A);
68 our (@dgit) = qw(dgit);
69 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
70 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
71 our (@dpkggenchanges) = qw(dpkg-genchanges);
72 our (@mergechanges) = qw(mergechanges -f);
73 our (@changesopts) = ('');
75 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
78 'debsign' => \@debsign,
83 'dpkg-source' => \@dpkgsource,
84 'dpkg-buildpackage' => \@dpkgbuildpackage,
85 'dpkg-genchanges' => \@dpkggenchanges,
86 'ch' => \@changesopts,
87 'mergechanges' => \@mergechanges);
89 our %opts_opt_cmdonly = ('gpg' => 1);
94 open DEBUG, ">/dev/null" or die $!;
98 our $remotename = 'dgit';
99 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
100 our $branchprefix = 'dgit';
103 sub lbranch () { return "$branchprefix/$csuite"; }
104 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
105 sub lref () { return "refs/heads/".lbranch(); }
106 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
107 sub rrref () { return "refs/$branchprefix/$csuite"; }
122 return "${package}_".(stripepoch $vsn).".dsc";
126 our $debugprefix = '';
131 foreach my $f (@end) {
133 warn "$us: cleanup: $@" if length $@;
137 our @signames = split / /, $Config{sig_name};
139 sub waitstatusmsg () {
141 return "terminated, reporting successful completion";
142 } elsif (!($? & 255)) {
143 return "failed with error exit status ".WEXITSTATUS($?);
144 } elsif (WIFSIGNALED($?)) {
145 my $signum=WTERMSIG($?);
146 return "died due to fatal signal ".
147 ($signames[$signum] // "number $signum").
148 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
150 return "failed with unknown wait status ".$?;
154 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
157 die $us.($we_are_responder ? " (build host)" : "").": @_\n";
160 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
162 sub no_such_package () {
163 print STDERR "$us: package $package does not exist in suite $isuite\n";
169 return "+".rrref().":".lrref();
174 printdebug "CD $newdir\n";
175 chdir $newdir or die "chdir: $newdir: $!";
178 #---------- remote protocol support, common ----------
180 # remote push initiator/responder protocol:
181 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
183 # > file parsed-changelog
184 # [indicates that output of dpkg-parsechangelog follows]
185 # > data-block NBYTES
186 # > [NBYTES bytes of data (no newline)]
187 # [maybe some more blocks]
199 # [indicates that signed tag is wanted]
200 # < data-block NBYTES
201 # < [NBYTES bytes of data (no newline)]
202 # [maybe some more blocks]
206 # > want signed-dsc-changes
207 # < data-block NBYTES [transfer of signed dsc]
209 # < data-block NBYTES [transfer of signed changes]
217 sub i_child_report () {
218 # Sees if our child has died, and reap it if so. Returns a string
219 # describing how it died if it failed, or undef otherwise.
220 return undef unless $i_child_pid;
221 my $got = waitpid $i_child_pid, WNOHANG;
222 return undef if $got <= 0;
223 die unless $got == $i_child_pid;
224 $i_child_pid = undef;
225 return undef unless $?;
226 return "build host child ".waitstatusmsg();
231 fail "connection lost: $!" if $fh->error;
232 fail "protocol violation; $m not expected";
235 sub badproto_badread ($$) {
237 fail "connection lost: $!" if $!;
238 my $report = i_child_report();
239 fail $report if defined $report;
240 badproto $fh, "eof (reading $wh)";
243 sub protocol_expect (&$) {
244 my ($match, $fh) = @_;
247 defined && chomp or badproto_badread $fh, "protocol message";
255 badproto $fh, "\`$_'";
258 sub protocol_send_file ($$) {
259 my ($fh, $ourfn) = @_;
260 open PF, "<", $ourfn or die "$ourfn: $!";
263 my $got = read PF, $d, 65536;
264 die "$ourfn: $!" unless defined $got;
266 print $fh "data-block ".length($d)."\n" or die $!;
267 print $fh $d or die $!;
269 PF->error and die "$ourfn $!";
270 print $fh "data-end\n" or die $!;
274 sub protocol_read_bytes ($$) {
275 my ($fh, $nbytes) = @_;
276 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
278 my $got = read $fh, $d, $nbytes;
279 $got==$nbytes or badproto_badread $fh, "data block";
283 sub protocol_receive_file ($$) {
284 my ($fh, $ourfn) = @_;
285 printdebug "() $ourfn\n";
286 open PF, ">", $ourfn or die "$ourfn: $!";
288 my ($y,$l) = protocol_expect {
289 m/^data-block (.*)$/ ? (1,$1) :
290 m/^data-end$/ ? (0,) :
294 my $d = protocol_read_bytes $fh, $l;
295 print PF $d or die $!;
300 #---------- remote protocol support, responder ----------
302 sub responder_send_command ($) {
304 return unless $we_are_responder;
305 # called even without $we_are_responder
306 printdebug ">> $command\n";
307 print PO $command, "\n" or die $!;
310 sub responder_send_file ($$) {
311 my ($keyword, $ourfn) = @_;
312 return unless $we_are_responder;
313 printdebug "]] $keyword $ourfn\n";
314 responder_send_command "file $keyword";
315 protocol_send_file \*PO, $ourfn;
318 sub responder_receive_files ($@) {
319 my ($keyword, @ourfns) = @_;
320 die unless $we_are_responder;
321 printdebug "[[ $keyword @ourfns\n";
322 responder_send_command "want $keyword";
323 foreach my $fn (@ourfns) {
324 protocol_receive_file \*PI, $fn;
327 protocol_expect { m/^files-end$/ } \*PI;
330 #---------- remote protocol support, initiator ----------
332 sub initiator_expect (&) {
334 protocol_expect { &$match } \*RO;
337 #---------- end remote code ----------
340 if ($we_are_responder) {
342 responder_send_command "progress ".length($m) or die $!;
343 print PO $m or die $!;
353 $ua = LWP::UserAgent->new();
357 progress "downloading $what...";
358 my $r = $ua->get(@_) or die $!;
359 return undef if $r->code == 404;
360 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
361 return $r->decoded_content(charset => 'none');
364 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
371 if (m{[^-=_./0-9a-z]}i) {
378 return join ' ', @out;
383 my $intro = shift @_;
384 print $fh $intro," " or die $!;
385 print $fh shellquote @_ or die $!;
386 print $fh "\n" or die $!;
390 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
392 fail "failed to fork/exec: $!";
394 fail "subprocess ".waitstatusmsg();
396 fail "subprocess produced invalid output";
401 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
403 failedcmd @_ if system @_;
406 sub act_local () { return $dryrun_level <= 1; }
407 sub act_scary () { return !$dryrun_level; }
410 if (!$dryrun_level) {
411 progress "dgit ok: @_";
413 progress "would be ok: @_ (but dry run only)";
417 sub cmdoutput_errok {
418 die Dumper(\@_)." ?" if grep { !defined } @_;
419 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
420 open P, "-|", @_ or die $!;
423 { local $/ = undef; $d = <P>; }
425 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
428 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
433 my $d = cmdoutput_errok @_;
434 defined $d or failedcmd @_;
439 printcmd(\*STDERR,$debugprefix."#",@_);
442 sub runcmd_ordryrun {
450 sub runcmd_ordryrun_local {
459 my ($first_shell, @cmd) = @_;
460 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
463 our $helpmsg = <<END;
465 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
466 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
467 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
468 dgit [dgit-opts] push [dgit-opts] [suite]
469 dgit [dgit-opts] rpush build-host:build-dir ...
470 important dgit options:
471 -k<keyid> sign tag and package with <keyid> instead of default
472 --dry-run -n do not change anything, but go through the motions
473 --damp-run -L like --dry-run but make local changes, without signing
474 --new -N allow introducing a new package
475 --debug -D increase debug level
476 -c<name>=<value> set git config option (used directly by dgit too)
479 our $later_warning_msg = <<END;
480 Perhaps the upload is stuck in incoming. Using the version from git.
484 print STDERR "$us: @_\n", $helpmsg or die $!;
489 @ARGV or badusage "too few arguments";
490 return scalar shift @ARGV;
494 print $helpmsg or die $!;
498 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
500 our %defcfg = ('dgit.default.distro' => 'debian',
501 'dgit.default.username' => '',
502 'dgit.default.archive-query-default-component' => 'main',
503 'dgit.default.ssh' => 'ssh',
504 'dgit-distro.debian.git-host' => 'git.debian.org',
505 'dgit-distro.debian.git-proto' => 'git+ssh://',
506 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
507 'dgit-distro.debian.git-check' => 'ssh-cmd',
508 'dgit-distro.debian.git-create' => 'ssh-cmd',
509 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
510 'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
511 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
512 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
513 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
514 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
515 'dgit-distro.ubuntu.git-check' => 'false',
516 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
517 'dgit-distro.test-dummy.ssh' => "$td/ssh",
518 'dgit-distro.test-dummy.username' => "alice",
519 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
520 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
521 'dgit-distro.test-dummy.git-url' => "$td/git",
522 'dgit-distro.test-dummy.git-host' => "git",
523 'dgit-distro.test-dummy.git-path' => "$td/git",
524 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
525 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
526 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
531 return undef if $c =~ /RETURN-UNDEF/;
532 my @cmd = (@git, qw(config --), $c);
535 local ($debug) = $debug-1;
536 $v = cmdoutput_errok @cmd;
543 my $dv = $defcfg{$c};
544 return $dv if defined $dv;
546 badcfg "need value for one of: @_\n".
547 "$us: distro or suite appears not to be (properly) supported";
550 sub access_basedistro () {
551 if (defined $idistro) {
552 return cfg("dgit-distro.basedistro.distro",
553 "dgit-suite.$isuite.distro",
554 'RETURN-UNDEF') // $idistro;
556 return cfg("dgit-suite.$isuite.distro",
557 "dgit.default.distro");
561 sub access_quirk () {
562 # returns (quirk name, distro to use instead, quirk-specific info)
563 my $basedistro = access_basedistro();
564 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
566 if (defined $backports_quirk) {
567 my $re = $backports_quirk;
568 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
570 $re =~ s/\%/([-0-9a-z_]+)/
571 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
572 if ($isuite =~ m/^$re$/) {
573 return ('backports',"$basedistro-backports",$1);
576 return ('none',$basedistro);
579 sub access_distro () {
580 return (access_quirk())[1];
585 my $basedistro = access_basedistro();
586 my $distro = $idistro || access_distro();
587 my $value = cfg(map {
588 ("dgit-distro.$distro.$_",
589 "dgit-distro.$basedistro.$_",
595 sub string_to_ssh ($) {
597 if ($spec =~ m/\s/) {
598 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
604 sub access_cfg_ssh () {
605 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
606 if (!defined $gitssh) {
609 return string_to_ssh $gitssh;
613 sub access_someuserhost ($) {
615 my $user = access_cfg("$some-user",'username');
616 my $host = access_cfg("$some-host");
617 return length($user) ? "$user\@$host" : $host;
620 sub access_gituserhost () {
621 return access_someuserhost('git');
624 sub access_giturl () {
625 my $url = access_cfg('git-url','RETURN-UNDEF');
628 access_cfg('git-proto').
629 access_gituserhost().
630 access_cfg('git-path');
632 return "$url/$package.git";
635 sub parsecontrolfh ($$;$) {
636 my ($fh, $desc, $allowsigned) = @_;
637 our $dpkgcontrolhash_noissigned;
640 my %opts = ('name' => $desc);
641 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
642 print STDERR Dumper(\%opts);
643 $c = Dpkg::Control::Hash->new(%opts);
644 $c->parse($fh,$desc) or die "parsing of $desc failed";
645 last if $allowsigned;
646 last if $dpkgcontrolhash_noissigned;
647 my $issigned= $c->get_option('is_pgp_signed');
648 if (!defined $issigned) {
649 $dpkgcontrolhash_noissigned= 1;
650 seek $fh, 0,0 or die "seek $desc: $!";
651 } elsif ($issigned) {
652 fail "control file $desc is (already) PGP-signed. ".
653 " Note that dgit push needs to modify the .dsc and then".
654 " do the signature itself";
663 my ($file, $desc) = @_;
664 my $fh = new IO::Handle;
665 open $fh, '<', $file or die "$file: $!";
666 my $c = parsecontrolfh($fh,$desc);
667 $fh->error and die $!;
673 my ($dctrl,$field) = @_;
674 my $v = $dctrl->{$field};
675 return $v if defined $v;
676 fail "missing field $field in ".$v->get_option('name');
680 my $c = Dpkg::Control::Hash->new();
681 my $p = new IO::Handle;
682 my @cmd = (qw(dpkg-parsechangelog), @_);
683 open $p, '-|', @cmd or die $!;
685 $?=0; $!=0; close $p or failedcmd @cmd;
689 sub git_get_ref ($) {
691 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
693 $?==256 or fail "git show-ref failed (status $?)";
694 printdebug "ref $refname= [show-ref exited 1]\n";
697 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
698 printdebug "ref $refname=$1\n";
701 printdebug "ref $refname= [no match]\n";
708 defined $d or fail "getcwd failed: $!";
714 sub archive_query ($) {
716 my $query = access_cfg('archive-query','RETURN-UNDEF');
717 if (!defined $query) {
718 my $distro = access_basedistro();
719 if ($distro eq 'debian') {
721 access_someuserhost('sshpsql').':'.
722 access_cfg('sshpsql-dbname');
724 $query = "madison:$distro";
727 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
730 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
733 sub pool_dsc_subpath ($$) {
734 my ($vsn,$component) = @_; # $package is implict arg
735 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
736 return "/pool/$component/$prefix/$package/".dscfn($vsn);
739 sub archive_query_madison ($$) {
740 my ($proto,$data) = @_;
741 die unless $proto eq 'madison';
742 $rmad{$package} ||= cmdoutput
743 qw(rmadison -asource),"-s$isuite","-u$data",$package;
744 my $rmad = $rmad{$package};
745 return madison_parse($rmad);
748 sub madison_parse ($) {
751 foreach my $l (split /\n/, $rmad) {
752 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
753 \s*( [^ \t|]+ )\s* \|
754 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
755 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
756 $1 eq $package or die "$rmad $package ?";
763 $component = access_cfg('archive-query-default-component');
765 $5 eq 'source' or die "$rmad ?";
766 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
768 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
771 sub canonicalise_suite_madison ($$) {
772 # madison canonicalises for us
773 my @r = archive_query_madison($_[0],$_[1]);
775 "unable to canonicalise suite using package $package".
776 " which does not appear to exist in suite $isuite;".
777 " --existing-package may help";
782 my ($data,$sql) = @_;
783 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
784 my ($userhost,$dbname) = ($`,$'); #';
786 my @cmd = (access_cfg_ssh, $userhost,
787 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
788 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
789 open P, "-|", @cmd or die $!;
792 printdebug("$debugprefix>|$_|\n");
795 $!=0; $?=0; close P or failedcmd @cmd;
797 my $nrows = pop @rows;
798 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
799 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
800 @rows = map { [ split /\|/, $_ ] } @rows;
801 my $ncols = scalar @{ shift @rows };
802 die if grep { scalar @$_ != $ncols } @rows;
806 sub sql_injection_check {
807 foreach (@_) { die "$_ $& ?" if m/[']/; }
810 sub archive_query_sshpsql ($$) {
811 my ($proto,$data) = @_;
812 sql_injection_check $isuite, $package;
813 my @rows = sshpsql($data, <<END);
814 SELECT source.version, component.name, files.filename, files.sha256sum
816 JOIN src_associations ON source.id = src_associations.source
817 JOIN suite ON suite.id = src_associations.suite
818 JOIN dsc_files ON dsc_files.source = source.id
819 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
820 JOIN component ON component.id = files_archive_map.component_id
821 JOIN files ON files.id = dsc_files.file
822 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
823 AND source.source='$package'
824 AND files.filename LIKE '%.dsc';
826 @rows = sort { -version_compare_string($a->[0],$b->[0]) } @rows;
827 my $digester = Digest::SHA->new(256);
829 my ($vsn,$component,$filename,$sha256sum) = @$_;
830 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
835 sub canonicalise_suite_sshpsql ($$) {
836 my ($proto,$data) = @_;
837 sql_injection_check $isuite;
838 my @rows = sshpsql($data, <<END);
839 SELECT suite.codename
840 FROM suite where suite_name='$isuite' or codename='$isuite';
842 @rows = map { $_->[0] } @rows;
843 fail "unknown suite $isuite" unless @rows;
844 die "ambiguous $isuite: @rows ?" if @rows>1;
848 sub canonicalise_suite_dummycat ($$) {
849 my ($proto,$data) = @_;
850 my $dpath = "$data/suite.$isuite";
851 if (!open C, "<", $dpath) {
852 $!==ENOENT or die "$dpath: $!";
853 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
857 chomp or die "$dpath: $!";
859 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
863 sub archive_query_dummycat ($$) {
864 my ($proto,$data) = @_;
865 canonicalise_suite();
866 my $dpath = "$data/package.$csuite.$package";
867 if (!open C, "<", $dpath) {
868 $!==ENOENT or die "$dpath: $!";
869 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
877 printdebug "dummycat query $csuite $package $dpath | $_\n";
878 my @row = split /\s+/, $_;
879 @row==2 or die "$dpath: $_ ?";
882 C->error and die "$dpath: $!";
884 return sort { -version_compare_string($a->[0],$b->[0]); } @rows;
887 sub canonicalise_suite () {
888 return if defined $csuite;
889 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
890 $csuite = archive_query('canonicalise_suite');
891 if ($isuite ne $csuite) {
892 progress "canonical suite name for $isuite is $csuite";
896 sub get_archive_dsc () {
897 canonicalise_suite();
898 my @vsns = archive_query('archive_query');
899 foreach my $vinfo (@vsns) {
900 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
901 $dscurl = access_cfg('mirror').$subpath;
902 $dscdata = url_get($dscurl);
904 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
909 $digester->add($dscdata);
910 my $got = $digester->hexdigest();
912 fail "$dscurl has hash $got but".
913 " archive told us to expect $digest";
915 my $dscfh = new IO::File \$dscdata, '<' or die $!;
916 printdebug Dumper($dscdata) if $debug>1;
917 $dsc = parsecontrolfh($dscfh,$dscurl,1);
918 printdebug Dumper($dsc) if $debug>1;
919 my $fmt = getfield $dsc, 'Format';
920 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
921 $dsc_checked = !!$digester;
927 sub check_for_git () {
929 my $how = access_cfg('git-check');
930 if ($how eq 'ssh-cmd') {
932 (access_cfg_ssh, access_gituserhost(),
933 " set -e; cd ".access_cfg('git-path').";".
934 " if test -d $package.git; then echo 1; else echo 0; fi");
935 my $r= cmdoutput @cmd;
936 failedcmd @cmd unless $r =~ m/^[01]$/;
938 } elsif ($how eq 'true') {
940 } elsif ($how eq 'false') {
943 badcfg "unknown git-check \`$how'";
947 sub create_remote_git_repo () {
948 my $how = access_cfg('git-create');
949 if ($how eq 'ssh-cmd') {
951 (access_cfg_ssh, access_gituserhost(),
952 "set -e; cd ".access_cfg('git-path').";".
953 " cp -a _template $package.git");
954 } elsif ($how eq 'true') {
957 badcfg "unknown git-create \`$how'";
961 our ($dsc_hash,$lastpush_hash);
963 our $ud = '.git/dgit/unpack';
971 sub mktree_in_ud_from_only_subdir () {
972 # changes into the subdir
975 $dirs[0] =~ m#^([^/]+)/\.$# or die;
978 fail "source package contains .git directory" if stat '.git';
979 die $! unless $!==&ENOENT;
980 runcmd qw(git init -q);
981 rmtree('.git/objects');
982 symlink '../../../../objects','.git/objects' or die $!;
983 runcmd @git, qw(add -Af);
984 my $tree = cmdoutput @git, qw(write-tree);
985 $tree =~ m/^\w+$/ or die "$tree ?";
989 sub dsc_files_info () {
990 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
991 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
992 ['Files', 'Digest::MD5', 'new()']) {
993 my ($fname, $module, $method) = @$csumi;
994 my $field = $dsc->{$fname};
995 next unless defined $field;
996 eval "use $module; 1;" or die $@;
998 foreach (split /\n/, $field) {
1000 m/^(\w+) (\d+) (\S+)$/ or
1001 fail "could not parse .dsc $fname line \`$_'";
1002 my $digester = eval "$module"."->$method;" or die $@;
1007 Digester => $digester,
1012 fail "missing any supported Checksums-* or Files field in ".
1013 $dsc->get_option('name');
1017 map { $_->{Filename} } dsc_files_info();
1020 sub is_orig_file ($) {
1022 m/\.orig(?:-\w+)?\.tar\.\w+$/;
1025 sub make_commit ($) {
1027 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1030 sub clogp_authline ($) {
1032 my $author = getfield $clogp, 'Maintainer';
1033 $author =~ s#,.*##ms;
1034 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1035 my $authline = "$author $date";
1036 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1037 fail "unexpected commit author line format \`$authline'".
1038 " (was generated from changelog Maintainer field)";
1042 sub generate_commit_from_dsc () {
1046 foreach my $fi (dsc_files_info()) {
1047 my $f = $fi->{Filename};
1048 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1050 link "../../../$f", $f
1054 complete_file_from_dsc('.', $fi);
1056 if (is_orig_file($f)) {
1057 link $f, "../../../../$f"
1063 my $dscfn = "$package.dsc";
1065 open D, ">", $dscfn or die "$dscfn: $!";
1066 print D $dscdata or die "$dscfn: $!";
1067 close D or die "$dscfn: $!";
1068 my @cmd = qw(dpkg-source);
1069 push @cmd, '--no-check' if $dsc_checked;
1070 push @cmd, qw(-x --), $dscfn;
1073 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1074 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1075 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1076 my $authline = clogp_authline $clogp;
1077 my $changes = getfield $clogp, 'Changes';
1078 open C, ">../commit.tmp" or die $!;
1079 print C <<END or die $!;
1086 # imported from the archive
1089 my $outputhash = make_commit qw(../commit.tmp);
1090 my $cversion = getfield $clogp, 'Version';
1091 progress "synthesised git commit from .dsc $cversion";
1092 if ($lastpush_hash) {
1093 runcmd @git, qw(reset --hard), $lastpush_hash;
1094 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1095 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1096 my $oversion = getfield $oldclogp, 'Version';
1098 version_compare_string($oversion, $cversion);
1100 # git upload/ is earlier vsn than archive, use archive
1101 open C, ">../commit2.tmp" or die $!;
1102 print C <<END or die $!;
1104 parent $lastpush_hash
1109 Record $package ($cversion) in archive suite $csuite
1111 $outputhash = make_commit qw(../commit2.tmp);
1112 } elsif ($vcmp > 0) {
1113 print STDERR <<END or die $!;
1115 Version actually in archive: $cversion (older)
1116 Last allegedly pushed/uploaded: $oversion (newer or same)
1119 $outputhash = $lastpush_hash;
1121 $outputhash = $lastpush_hash;
1124 changedir '../../../..';
1125 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1126 'DGIT_ARCHIVE', $outputhash;
1127 cmdoutput @git, qw(log -n2), $outputhash;
1128 # ... gives git a chance to complain if our commit is malformed
1133 sub complete_file_from_dsc ($$) {
1134 our ($dstdir, $fi) = @_;
1135 # Ensures that we have, in $dir, the file $fi, with the correct
1136 # contents. (Downloading it from alongside $dscurl if necessary.)
1138 my $f = $fi->{Filename};
1139 my $tf = "$dstdir/$f";
1143 progress "using existing $f";
1145 die "$tf $!" unless $!==&ENOENT;
1148 $furl =~ s{/[^/]+$}{};
1150 die "$f ?" unless $f =~ m/^${package}_/;
1151 die "$f ?" if $f =~ m#/#;
1152 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1153 next if !act_local();
1157 open F, "<", "$tf" or die "$tf: $!";
1158 $fi->{Digester}->reset();
1159 $fi->{Digester}->addfile(*F);
1160 F->error and die $!;
1161 my $got = $fi->{Digester}->hexdigest();
1162 $got eq $fi->{Hash} or
1163 fail "file $f has hash $got but .dsc".
1164 " demands hash $fi->{Hash} ".
1165 ($downloaded ? "(got wrong file from archive!)"
1166 : "(perhaps you should delete this file?)");
1169 sub ensure_we_have_orig () {
1170 foreach my $fi (dsc_files_info()) {
1171 my $f = $fi->{Filename};
1172 next unless is_orig_file($f);
1173 complete_file_from_dsc('..', $fi);
1178 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1181 sub is_fast_fwd ($$) {
1182 my ($ancestor,$child) = @_;
1183 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1184 my $mb = cmdoutput_errok @cmd;
1186 return rev_parse($mb) eq rev_parse($ancestor);
1188 $?==256 or failedcmd @cmd;
1193 sub git_fetch_us () {
1194 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1197 sub fetch_from_archive () {
1198 # ensures that lrref() is what is actually in the archive,
1199 # one way or another
1203 foreach my $field (@ourdscfield) {
1204 $dsc_hash = $dsc->{$field};
1205 last if defined $dsc_hash;
1207 if (defined $dsc_hash) {
1208 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1210 progress "last upload to archive specified git hash";
1212 progress "last upload to archive has NO git hash";
1215 progress "no version available from the archive";
1218 $lastpush_hash = git_get_ref(lrref());
1219 printdebug "previous reference hash=$lastpush_hash\n";
1221 if (defined $dsc_hash) {
1222 fail "missing remote git history even though dsc has hash -".
1223 " could not find ref ".lrref().
1224 " (should have been fetched from ".access_giturl()."#".rrref().")"
1225 unless $lastpush_hash;
1227 ensure_we_have_orig();
1228 if ($dsc_hash eq $lastpush_hash) {
1229 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1230 print STDERR <<END or die $!;
1232 Git commit in archive is behind the last version allegedly pushed/uploaded.
1233 Commit referred to by archive: $dsc_hash
1234 Last allegedly pushed/uploaded: $lastpush_hash
1237 $hash = $lastpush_hash;
1239 fail "archive's .dsc refers to ".$dsc_hash.
1240 " but this is an ancestor of ".$lastpush_hash;
1243 $hash = generate_commit_from_dsc();
1244 } elsif ($lastpush_hash) {
1245 # only in git, not in the archive yet
1246 $hash = $lastpush_hash;
1247 print STDERR <<END or die $!;
1249 Package not found in the archive, but has allegedly been pushed using dgit.
1253 printdebug "nothing found!\n";
1254 if (defined $skew_warning_vsn) {
1255 print STDERR <<END or die $!;
1257 Warning: relevant archive skew detected.
1258 Archive allegedly contains $skew_warning_vsn
1259 But we were not able to obtain any version from the archive or git.
1265 printdebug "current hash=$hash\n";
1266 if ($lastpush_hash) {
1267 fail "not fast forward on last upload branch!".
1268 " (archive's version left in DGIT_ARCHIVE)"
1269 unless is_fast_fwd($lastpush_hash, $hash);
1271 if (defined $skew_warning_vsn) {
1273 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1274 my $clogf = ".git/dgit/changelog.tmp";
1275 runcmd shell_cmd "exec >$clogf",
1276 @git, qw(cat-file blob), "$hash:debian/changelog";
1277 my $gotclogp = parsechangelog("-l$clogf");
1278 my $got_vsn = getfield $gotclogp, 'Version';
1279 printdebug "SKEW CHECK GOT $got_vsn\n";
1280 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
1281 print STDERR <<END or die $!;
1283 Warning: archive skew detected. Using the available version:
1284 Archive allegedly contains $skew_warning_vsn
1285 We were able to obtain only $got_vsn
1290 if ($lastpush_hash ne $hash) {
1291 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1295 dryrun_report @upd_cmd;
1303 canonicalise_suite();
1304 badusage "dry run makes no sense with clone" unless act_local();
1305 mkdir $dstdir or die "$dstdir $!";
1307 runcmd @git, qw(init -q);
1308 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1309 open H, "> .git/HEAD" or die $!;
1310 print H "ref: ".lref()."\n" or die $!;
1312 runcmd @git, qw(remote add), 'origin', access_giturl();
1313 if (check_for_git()) {
1314 progress "fetching existing git history";
1316 runcmd_ordryrun_local @git, qw(fetch origin);
1318 progress "starting new git history";
1320 fetch_from_archive() or no_such_package;
1321 my $vcsgiturl = $dsc->{'Vcs-Git'};
1322 if (length $vcsgiturl) {
1323 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1325 runcmd @git, qw(reset --hard), lrref();
1326 printdone "ready for work in $dstdir";
1330 if (check_for_git()) {
1333 fetch_from_archive() or no_such_package();
1334 printdone "fetched into ".lrref();
1339 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1341 printdone "fetched to ".lrref()." and merged into HEAD";
1344 sub check_not_dirty () {
1345 return if $ignoredirty;
1346 my @cmd = (@git, qw(diff --quiet HEAD));
1347 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1348 $!=0; $?=0; system @cmd;
1349 return if !$! && !$?;
1350 if (!$! && $?==256) {
1351 fail "working tree is dirty (does not match HEAD)";
1357 sub commit_quilty_patch () {
1358 my $output = cmdoutput @git, qw(status --porcelain);
1360 foreach my $l (split /\n/, $output) {
1361 next unless $l =~ m/\S/;
1362 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1367 progress "nothing quilty to commit, ok.";
1370 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1371 my $m = "Commit Debian 3.0 (quilt) metadata";
1373 runcmd_ordryrun_local @git, qw(commit -m), $m;
1378 return 0 unless $format eq '3.0 (quilt)';
1379 progress "Format \`$format', urgh";
1381 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1387 sub push_parse_changelog ($) {
1390 my $clogp = Dpkg::Control::Hash->new();
1391 $clogp->load($clogpfn) or die;
1393 $package = getfield $clogp, 'Source';
1394 my $cversion = getfield $clogp, 'Version';
1395 my $tag = debiantag($cversion);
1396 runcmd @git, qw(check-ref-format), $tag;
1398 my $dscfn = dscfn($cversion);
1400 return ($clogp, $cversion, $tag, $dscfn);
1403 sub push_parse_dsc ($$$) {
1404 my ($dscfn,$dscfnwhat, $cversion) = @_;
1405 $dsc = parsecontrol($dscfn,$dscfnwhat);
1406 my $dversion = getfield $dsc, 'Version';
1407 my $dscpackage = getfield $dsc, 'Source';
1408 ($dscpackage eq $package && $dversion eq $cversion) or
1409 fail "$dscfn is for $dscpackage $dversion".
1410 " but debian/changelog is for $package $cversion";
1413 sub push_mktag ($$$$$$$) {
1414 my ($head,$clogp,$tag,
1416 $changesfile,$changesfilewhat,
1419 $dsc->{$ourdscfield[0]} = $head;
1420 $dsc->save("$dscfn.tmp") or die $!;
1422 my $changes = parsecontrol($changesfile,$changesfilewhat);
1423 foreach my $field (qw(Source Distribution Version)) {
1424 $changes->{$field} eq $clogp->{$field} or
1425 fail "changes field $field \`$changes->{$field}'".
1426 " does not match changelog \`$clogp->{$field}'";
1429 my $cversion = getfield $clogp, 'Version';
1430 my $clogsuite = getfield $clogp, 'Distribution';
1432 # We make the git tag by hand because (a) that makes it easier
1433 # to control the "tagger" (b) we can do remote signing
1434 my $authline = clogp_authline $clogp;
1435 open TO, '>', $tfn->('.tmp') or die $!;
1436 print TO <<END or die $!;
1442 $package release $cversion for $clogsuite ($csuite) [dgit]
1446 my $tagobjfn = $tfn->('.tmp');
1448 if (!defined $keyid) {
1449 $keyid = access_cfg('keyid','RETURN-UNDEF');
1451 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1452 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1453 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1454 push @sign_cmd, $tfn->('.tmp');
1455 runcmd_ordryrun @sign_cmd;
1457 $tagobjfn = $tfn->('.signed.tmp');
1458 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1459 $tfn->('.tmp'), $tfn->('.tmp.asc');
1466 sub sign_changes ($) {
1467 my ($changesfile) = @_;
1469 my @debsign_cmd = @debsign;
1470 push @debsign_cmd, "-k$keyid" if defined $keyid;
1471 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1472 push @debsign_cmd, $changesfile;
1473 runcmd_ordryrun @debsign_cmd;
1478 printdebug "actually entering push\n";
1481 access_giturl(); # check that success is vaguely likely
1483 my $clogpfn = ".git/dgit/changelog.822.tmp";
1484 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1486 responder_send_file('parsed-changelog', $clogpfn);
1488 my ($clogp, $cversion, $tag, $dscfn) =
1489 push_parse_changelog("$clogpfn");
1491 my $dscpath = "$buildproductsdir/$dscfn";
1493 fail "looked for .dsc $dscfn, but $!;".
1494 " maybe you forgot to build";
1496 responder_send_file('dsc', $dscpath);
1498 push_parse_dsc($dscpath, $dscfn, $cversion);
1500 my $format = getfield $dsc, 'Format';
1501 printdebug "format $format\n";
1502 if (madformat($format)) {
1503 commit_quilty_patch();
1507 progress "checking that $dscfn corresponds to HEAD";
1508 runcmd qw(dpkg-source -x --),
1509 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1510 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1511 changedir '../../../..';
1512 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1513 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1514 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1516 my $r = system @diffcmd;
1519 fail "$dscfn specifies a different tree to your HEAD commit;".
1520 " perhaps you forgot to build".
1521 ($diffopt eq '--exit-code' ? "" :
1522 " (run with -D to see full diff output)");
1528 #do fast forward check and maybe fake merge
1529 # if (!is_fast_fwd(mainbranch
1530 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1531 # map { lref($_).":".rref($_) }
1533 my $head = rev_parse('HEAD');
1534 if (!$changesfile) {
1535 my $multi = "$buildproductsdir/".
1536 "${package}_".(stripepoch $cversion)."_multi.changes";
1537 if (stat "$multi") {
1538 $changesfile = $multi;
1540 $!==&ENOENT or die "$multi: $!";
1541 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1542 my @cs = glob "$buildproductsdir/$pat";
1543 fail "failed to find unique changes file".
1544 " (looked for $pat in $buildproductsdir, or $multi);".
1545 " perhaps you need to use dgit -C"
1547 ($changesfile) = @cs;
1550 $changesfile = "$buildproductsdir/$changesfile";
1553 responder_send_file('changes',$changesfile);
1554 responder_send_command("param head $head");
1555 responder_send_command("param csuite $csuite");
1557 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1560 if ($we_are_responder) {
1561 $tagobjfn = $tfn->('.signed.tmp');
1562 responder_receive_files('signed-tag', $tagobjfn);
1565 push_mktag($head,$clogp,$tag,
1567 $changesfile,$changesfile,
1571 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1572 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1573 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1574 runcmd_ordryrun @git, qw(tag -v --), $tag;
1576 if (!check_for_git()) {
1577 create_remote_git_repo();
1579 runcmd_ordryrun @git, qw(push),access_giturl(),
1580 "HEAD:".rrref(), "refs/tags/$tag";
1581 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1583 if ($we_are_responder) {
1584 my $dryrunsuffix = act_local() ? "" : ".tmp";
1585 responder_receive_files('signed-dsc-changes',
1586 "$dscpath$dryrunsuffix",
1587 "$changesfile$dryrunsuffix");
1590 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1592 progress "[new .dsc left in $dscpath.tmp]";
1594 sign_changes $changesfile;
1597 my $host = access_cfg('upload-host','RETURN-UNDEF');
1598 my @hostarg = defined($host) ? ($host,) : ();
1599 runcmd_ordryrun @dput, @hostarg, $changesfile;
1600 printdone "pushed and uploaded $cversion";
1602 responder_send_command("complete");
1608 badusage "-p is not allowed with clone; specify as argument instead"
1609 if defined $package;
1612 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1613 ($package,$isuite) = @ARGV;
1614 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1615 ($package,$dstdir) = @ARGV;
1616 } elsif (@ARGV==3) {
1617 ($package,$isuite,$dstdir) = @ARGV;
1619 badusage "incorrect arguments to dgit clone";
1621 $dstdir ||= "$package";
1624 fail "$dstdir already exists";
1625 } elsif ($! != &ENOENT) {
1630 if ($rmonerror && !$dryrun_level) {
1631 $cwd_remove= getcwd();
1633 return unless defined $cwd_remove;
1634 if (!chdir "$cwd_remove") {
1635 return if $!==&ENOENT;
1636 die "chdir $cwd_remove: $!";
1638 rmtree($dstdir) or die "remove $dstdir: $!\n";
1643 $cwd_remove = undef;
1646 sub branchsuite () {
1647 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1648 if ($branch =~ m#$lbranch_re#o) {
1655 sub fetchpullargs () {
1656 if (!defined $package) {
1657 my $sourcep = parsecontrol('debian/control','debian/control');
1658 $package = getfield $sourcep, 'Source';
1661 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1663 my $clogp = parsechangelog();
1664 $isuite = getfield $clogp, 'Distribution';
1666 canonicalise_suite();
1667 progress "fetching from suite $csuite";
1668 } elsif (@ARGV==1) {
1670 canonicalise_suite();
1672 badusage "incorrect arguments to dgit fetch or dgit pull";
1690 badusage "-p is not allowed with dgit push" if defined $package;
1692 my $clogp = parsechangelog();
1693 $package = getfield $clogp, 'Source';
1696 } elsif (@ARGV==1) {
1697 ($specsuite) = (@ARGV);
1699 badusage "incorrect arguments to dgit push";
1701 $isuite = getfield $clogp, 'Distribution';
1703 local ($package) = $existing_package; # this is a hack
1704 canonicalise_suite();
1706 if (defined $specsuite && $specsuite ne $isuite) {
1707 canonicalise_suite();
1708 $csuite eq $specsuite or
1709 fail "dgit push: changelog specifies $isuite ($csuite)".
1710 " but command line specifies $specsuite";
1712 if (check_for_git()) {
1715 if (fetch_from_archive()) {
1716 is_fast_fwd(lrref(), 'HEAD') or
1717 fail "dgit push: HEAD is not a descendant".
1718 " of the archive's version.\n".
1719 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1722 fail "package appears to be new in this suite;".
1723 " if this is intentional, use --new";
1728 #---------- remote commands' implementation ----------
1730 sub cmd_remote_push_responder {
1731 my ($nrargs) = shift @ARGV;
1732 my (@rargs) = @ARGV[0..$nrargs-1];
1733 @ARGV = @ARGV[$nrargs..$#ARGV];
1737 $we_are_responder = 1;
1739 open PI, "<&STDIN" or die $!;
1740 open STDIN, "/dev/null" or die $!;
1741 open PO, ">&STDOUT" or die $!;
1743 open STDOUT, ">&STDERR" or die $!;
1746 responder_send_command("dgit-remote-push-ready");
1758 printdebug "(killing remote child $i_child_pid)\n";
1759 kill 15, $i_child_pid;
1761 if (defined $i_tmp && !defined $initiator_tempdir) {
1763 eval { rmtree $i_tmp; };
1767 END { i_cleanup(); }
1770 my ($base,$selector,@args) = @_;
1771 $selector =~ s/\-/_/g;
1772 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1778 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1788 push @rdgit, @ropts;
1789 push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1791 my @cmd = (@ssh, $host, shellquote @rdgit);
1792 printcmd \*DEBUG,$debugprefix."+",@cmd;
1794 if (defined $initiator_tempdir) {
1795 rmtree $initiator_tempdir;
1796 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1797 $i_tmp = $initiator_tempdir;
1801 $i_child_pid = open2(\*RO, \*RI, @cmd);
1803 initiator_expect { m/^dgit-remote-push-ready/ };
1805 my ($icmd,$iargs) = initiator_expect {
1806 m/^(\S+)(?: (.*))?$/;
1809 i_method "i_resp", $icmd, $iargs;
1813 sub i_resp_progress ($) {
1815 my $msg = protocol_read_bytes \*RO, $rhs;
1819 sub i_resp_complete {
1820 my $pid = $i_child_pid;
1821 $i_child_pid = undef; # prevents killing some other process with same pid
1822 printdebug "waiting for build host child $pid...\n";
1823 my $got = waitpid $pid, 0;
1824 die $! unless $got == $pid;
1825 die "build host child failed $?" if $?;
1828 printdebug "all done\n";
1832 sub i_resp_file ($) {
1834 my $localname = i_method "i_localname", $keyword;
1835 my $localpath = "$i_tmp/$localname";
1836 stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1837 protocol_receive_file \*RO, $localpath;
1838 i_method "i_file", $keyword;
1843 sub i_resp_param ($) {
1844 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1850 sub i_resp_want ($) {
1852 die "$keyword ?" if $i_wanted{$keyword}++;
1853 my @localpaths = i_method "i_want", $keyword;
1854 printdebug "[[ $keyword @localpaths\n";
1855 foreach my $localpath (@localpaths) {
1856 protocol_send_file \*RI, $localpath;
1858 print RI "files-end\n" or die $!;
1861 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1863 sub i_localname_parsed_changelog {
1864 return "remote-changelog.822";
1866 sub i_file_parsed_changelog {
1867 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1868 push_parse_changelog "$i_tmp/remote-changelog.822";
1869 die if $i_dscfn =~ m#/|^\W#;
1872 sub i_localname_dsc {
1873 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1878 sub i_localname_changes {
1879 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1880 $i_changesfn = $i_dscfn;
1881 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1882 return $i_changesfn;
1884 sub i_file_changes { }
1886 sub i_want_signed_tag {
1887 printdebug Dumper(\%i_param, $i_dscfn);
1888 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1889 && defined $i_param{'csuite'}
1890 or badproto \*RO, "premature desire for signed-tag";
1891 my $head = $i_param{'head'};
1892 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1894 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1896 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1899 push_mktag $head, $i_clogp, $i_tag,
1901 $i_changesfn, 'remote changes',
1902 sub { "tag$_[0]"; };
1907 sub i_want_signed_dsc_changes {
1908 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1909 sign_changes $i_changesfn;
1910 return ($i_dscfn, $i_changesfn);
1913 #---------- building etc. ----------
1919 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1921 sub build_maybe_quilt_fixup () {
1922 if (!open F, "debian/source/format") {
1923 die $! unless $!==&ENOENT;
1927 F->error and die $!;
1929 return unless madformat($_);
1932 my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1933 my $problems = cmdoutput @cmd;
1934 if (length $problems) {
1935 print STDERR "problematic files:\n";
1936 print STDERR " $_\n" foreach split /\n/, $problems;
1937 fail "Cannot do quilt fixup in tree containing ignored files. ".
1938 "Perhaps your package's clean target is broken, in which".
1939 " case -wg (which says to use git-clean -xdf) may help.";
1942 my $clogp = parsechangelog();
1943 my $version = getfield $clogp, 'Version';
1944 my $author = getfield $clogp, 'Maintainer';
1945 my $headref = rev_parse('HEAD');
1948 my $patchname = "auto-$version-$headref-$time";
1949 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1951 my $descfn = ".git/dgit/quilt-description.tmp";
1952 open O, '>', $descfn or die "$descfn: $!";
1954 $msg =~ s/^\s+$/ ./mg;
1955 print O <<END or die $!;
1956 Description: Automatically generated patch ($clogp->{Version})
1957 Last (up to) $ncommits git changes, FYI:
1967 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1968 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1969 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1970 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1973 if (!open P, '>>', ".pc/applied-patches") {
1974 $!==&ENOENT or die $!;
1979 commit_quilty_patch();
1982 sub quilt_fixup_editor () {
1983 my $descfn = $ENV{$fakeeditorenv};
1984 my $editing = $ARGV[$#ARGV];
1985 open I1, '<', $descfn or die "$descfn: $!";
1986 open I2, '<', $editing or die "$editing: $!";
1987 unlink $editing or die "$editing: $!";
1988 open O, '>', $editing or die "$editing: $!";
1989 while (<I1>) { print O or die $!; } I1->error and die $!;
1992 $copying ||= m/^\-\-\- /;
1993 next unless $copying;
1996 I2->error and die $!;
2002 if ($cleanmode eq 'dpkg-source') {
2003 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2004 } elsif ($cleanmode eq 'git') {
2005 runcmd_ordryrun_local @git, qw(clean -xdf);
2006 } elsif ($cleanmode eq 'none') {
2013 badusage "clean takes no additional arguments" if @ARGV;
2018 badusage "-p is not allowed when building" if defined $package;
2021 my $clogp = parsechangelog();
2022 $isuite = getfield $clogp, 'Distribution';
2023 $package = getfield $clogp, 'Source';
2024 $version = getfield $clogp, 'Version';
2025 build_maybe_quilt_fixup();
2028 sub changesopts () {
2029 my @opts =@changesopts[1..$#changesopts];
2030 if (!defined $changes_since_version) {
2031 my @vsns = archive_query('archive_query');
2032 my @quirk = access_quirk();
2033 if ($quirk[0] eq 'backports') {
2034 local $isuite = $quirk[2];
2036 canonicalise_suite();
2037 push @vsns, archive_query('archive_query');
2040 @vsns = map { $_->[0] } @vsns;
2041 @vsns = sort { -version_compare_string($a, $b) } @vsns;
2042 $changes_since_version = $vsns[0];
2043 progress "changelog will contain changes since $vsns[0]";
2045 $changes_since_version = '_';
2046 progress "package seems new, not specifying -v<version>";
2049 if ($changes_since_version ne '_') {
2050 unshift @opts, "-v$changes_since_version";
2057 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2058 printdone "build successful\n";
2064 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2065 "--git-builder=@dpkgbuildpackage");
2066 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2067 canonicalise_suite();
2068 push @cmd, "--git-debian-branch=".lbranch();
2070 push @cmd, changesopts();
2071 runcmd_ordryrun_local @cmd, @ARGV;
2072 printdone "build successful\n";
2077 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2078 $dscfn = dscfn($version);
2079 if ($cleanmode eq 'dpkg-source') {
2080 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2083 my $pwd = must_getcwd();
2084 my $leafdir = basename $pwd;
2086 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2088 runcmd_ordryrun_local qw(sh -ec),
2089 'exec >$1; shift; exec "$@"','x',
2090 "../$sourcechanges",
2091 @dpkggenchanges, qw(-S), changesopts();
2095 sub cmd_build_source {
2096 badusage "build-source takes no additional arguments" if @ARGV;
2098 printdone "source built, results in $dscfn and $sourcechanges";
2104 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2106 stat $dscfn or fail "$dscfn (in parent directory): $!";
2107 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
2108 foreach my $cf (glob $pat) {
2109 next if $cf eq $sourcechanges;
2110 unlink $cf or fail "remove $cf: $!";
2113 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2114 my @changesfiles = glob $pat;
2115 @changesfiles = sort {
2116 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2119 fail "wrong number of different changes files (@changesfiles)"
2120 unless @changesfiles;
2121 runcmd_ordryrun_local @mergechanges, @changesfiles;
2122 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2124 stat $multichanges or fail "$multichanges: $!";
2126 printdone "build successful, results in $multichanges\n" or die $!;
2129 sub cmd_quilt_fixup {
2130 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2131 my $clogp = parsechangelog();
2132 $version = getfield $clogp, 'Version';
2133 build_maybe_quilt_fixup();
2136 #---------- argument parsing and main program ----------
2139 print "dgit version $our_version\n" or die $!;
2146 if (defined $ENV{'DGIT_SSH'}) {
2147 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2148 } elsif (defined $ENV{'GIT_SSH'}) {
2149 @ssh = ($ENV{'GIT_SSH'});
2153 last unless $ARGV[0] =~ m/^-/;
2157 if (m/^--dry-run$/) {
2160 } elsif (m/^--damp-run$/) {
2163 } elsif (m/^--no-sign$/) {
2166 } elsif (m/^--help$/) {
2168 } elsif (m/^--version$/) {
2170 } elsif (m/^--new$/) {
2173 } elsif (m/^--since-version=([^_]+|_)$/) {
2175 $changes_since_version = $1;
2176 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2177 ($om = $opts_opt_map{$1}) &&
2181 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2182 !$opts_opt_cmdonly{$1} &&
2183 ($om = $opts_opt_map{$1})) {
2186 } elsif (m/^--existing-package=(.*)/s) {
2188 $existing_package = $1;
2189 } elsif (m/^--initiator-tempdir=(.*)/s) {
2190 $initiator_tempdir = $1;
2191 $initiator_tempdir =~ m#^/# or
2192 badusage "--initiator-tempdir must be used specify an".
2193 " absolute, not relative, directory."
2194 } elsif (m/^--distro=(.*)/s) {
2197 } elsif (m/^--build-products-dir=(.*)/s) {
2199 $buildproductsdir = $1;
2200 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2203 } elsif (m/^--clean=(.*)$/s) {
2204 badusage "unknown cleaning mode \`$1'";
2205 } elsif (m/^--ignore-dirty$/s) {
2208 } elsif (m/^--no-quilt-fixup$/s) {
2211 } elsif (m/^--no-rm-on-error$/s) {
2215 badusage "unknown long option \`$_'";
2222 } elsif (s/^-L/-/) {
2225 } elsif (s/^-h/-/) {
2227 } elsif (s/^-D/-/) {
2229 open DEBUG, ">&STDERR" or die $!;
2232 } elsif (s/^-N/-/) {
2235 } elsif (s/^-v([^_]+|_)$//s) {
2237 $changes_since_version = $1;
2240 push @changesopts, $_;
2242 } elsif (s/^-c(.*=.*)//s) {
2244 push @git, '-c', $1;
2245 } elsif (s/^-d(.*)//s) {
2248 } elsif (s/^-C(.*)//s) {
2251 if ($changesfile =~ s#^(.*)/##) {
2252 $buildproductsdir = $1;
2254 } elsif (s/^-k(.*)//s) {
2256 } elsif (s/^-wn//s) {
2258 $cleanmode = 'none';
2259 } elsif (s/^-wg//s) {
2262 } elsif (s/^-wd//s) {
2264 $cleanmode = 'dpkg-source';
2266 badusage "unknown short option \`$_'";
2273 if ($ENV{$fakeeditorenv}) {
2274 quilt_fixup_editor();
2278 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2279 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2280 if $dryrun_level == 1;
2282 print STDERR $helpmsg or die $!;
2285 my $cmd = shift @ARGV;
2288 my $fn = ${*::}{"cmd_$cmd"};
2289 $fn or badusage "unknown operation $cmd";