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 fail "connection lost: $!" if $fh->error;
218 fail "protocol violation; $m not expected";
221 sub protocol_expect (&$) {
222 my ($match, $fh) = @_;
225 defined && chomp or badproto $fh, "eof";
233 badproto $fh, "\`$_'";
236 sub protocol_send_file ($$) {
237 my ($fh, $ourfn) = @_;
238 open PF, "<", $ourfn or die "$ourfn: $!";
241 my $got = read PF, $d, 65536;
242 die "$ourfn: $!" unless defined $got;
244 print $fh "data-block ".length($d)."\n" or die $!;
245 print $fh $d or die $!;
247 PF->error and die "$ourfn $!";
248 print $fh "data-end\n" or die $!;
252 sub protocol_read_bytes ($$) {
253 my ($fh, $nbytes) = @_;
254 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
256 my $got = read $fh, $d, $nbytes;
257 $got==$nbytes or badproto $fh, "eof during data block";
261 sub protocol_receive_file ($$) {
262 my ($fh, $ourfn) = @_;
263 printdebug "() $ourfn\n";
264 open PF, ">", $ourfn or die "$ourfn: $!";
266 my ($y,$l) = protocol_expect {
267 m/^data-block (.*)$/ ? (1,$1) :
268 m/^data-end$/ ? (0,) :
272 my $d = protocol_read_bytes $fh, $l;
273 print PF $d or die $!;
278 #---------- remote protocol support, responder ----------
280 sub responder_send_command ($) {
282 return unless $we_are_responder;
283 # called even without $we_are_responder
284 printdebug ">> $command\n";
285 print PO $command, "\n" or die $!;
288 sub responder_send_file ($$) {
289 my ($keyword, $ourfn) = @_;
290 return unless $we_are_responder;
291 printdebug "]] $keyword $ourfn\n";
292 responder_send_command "file $keyword";
293 protocol_send_file \*PO, $ourfn;
296 sub responder_receive_files ($@) {
297 my ($keyword, @ourfns) = @_;
298 die unless $we_are_responder;
299 printdebug "[[ $keyword @ourfns\n";
300 responder_send_command "want $keyword";
301 foreach my $fn (@ourfns) {
302 protocol_receive_file \*PI, $fn;
305 protocol_expect { m/^files-end$/ } \*PI;
308 #---------- remote protocol support, initiator ----------
310 sub initiator_expect (&) {
312 protocol_expect { &$match } \*RO;
315 #---------- end remote code ----------
318 if ($we_are_responder) {
320 responder_send_command "progress ".length($m) or die $!;
321 print PO $m or die $!;
331 $ua = LWP::UserAgent->new();
335 progress "downloading $what...";
336 my $r = $ua->get(@_) or die $!;
337 return undef if $r->code == 404;
338 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
339 return $r->decoded_content(charset => 'none');
342 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
349 if (m{[^-=_./0-9a-z]}i) {
356 return join ' ', @out;
361 my $intro = shift @_;
362 print $fh $intro," " or die $!;
363 print $fh shellquote @_ or die $!;
364 print $fh "\n" or die $!;
368 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
370 fail "failed to fork/exec: $!";
372 fail "subprocess ".waitstatusmsg();
374 fail "subprocess produced invalid output";
379 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
381 failedcmd @_ if system @_;
384 sub act_local () { return $dryrun_level <= 1; }
385 sub act_scary () { return !$dryrun_level; }
388 if (!$dryrun_level) {
389 progress "dgit ok: @_";
391 progress "would be ok: @_ (but dry run only)";
395 sub cmdoutput_errok {
396 die Dumper(\@_)." ?" if grep { !defined } @_;
397 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
398 open P, "-|", @_ or die $!;
401 { local $/ = undef; $d = <P>; }
403 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
406 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
411 my $d = cmdoutput_errok @_;
412 defined $d or failedcmd @_;
417 printcmd(\*STDERR,$debugprefix."#",@_);
420 sub runcmd_ordryrun {
428 sub runcmd_ordryrun_local {
437 my ($first_shell, @cmd) = @_;
438 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
441 our $helpmsg = <<END;
443 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
444 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
445 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
446 dgit [dgit-opts] push [dgit-opts] [suite]
447 dgit [dgit-opts] rpush build-host:build-dir ...
448 important dgit options:
449 -k<keyid> sign tag and package with <keyid> instead of default
450 --dry-run -n do not change anything, but go through the motions
451 --damp-run -L like --dry-run but make local changes, without signing
452 --new -N allow introducing a new package
453 --debug -D increase debug level
454 -c<name>=<value> set git config option (used directly by dgit too)
457 our $later_warning_msg = <<END;
458 Perhaps the upload is stuck in incoming. Using the version from git.
462 print STDERR "$us: @_\n", $helpmsg or die $!;
467 @ARGV or badusage "too few arguments";
468 return scalar shift @ARGV;
472 print $helpmsg or die $!;
476 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
478 our %defcfg = ('dgit.default.distro' => 'debian',
479 'dgit.default.username' => '',
480 'dgit.default.archive-query-default-component' => 'main',
481 'dgit.default.ssh' => 'ssh',
482 'dgit-distro.debian.git-host' => 'git.debian.org',
483 'dgit-distro.debian.git-proto' => 'git+ssh://',
484 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
485 'dgit-distro.debian.git-check' => 'ssh-cmd',
486 'dgit-distro.debian.git-create' => 'ssh-cmd',
487 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
488 'dgit-distro.debian.sshpsql-dbname' => 'service=projectb',
489 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
490 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
491 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
492 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
493 'dgit-distro.ubuntu.git-check' => 'false',
494 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
495 'dgit-distro.test-dummy.ssh' => "$td/ssh",
496 'dgit-distro.test-dummy.username' => "alice",
497 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
498 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
499 'dgit-distro.test-dummy.git-url' => "$td/git",
500 'dgit-distro.test-dummy.git-host' => "git",
501 'dgit-distro.test-dummy.git-path' => "$td/git",
502 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
503 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
504 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
509 return undef if $c =~ /RETURN-UNDEF/;
510 my @cmd = (@git, qw(config --), $c);
513 local ($debug) = $debug-1;
514 $v = cmdoutput_errok @cmd;
521 my $dv = $defcfg{$c};
522 return $dv if defined $dv;
524 badcfg "need value for one of: @_\n".
525 "$us: distro or suite appears not to be (properly) supported";
528 sub access_basedistro () {
529 if (defined $idistro) {
530 return cfg("dgit-distro.basedistro.distro",
531 "dgit-suite.$isuite.distro",
532 'RETURN-UNDEF') // $idistro;
534 return cfg("dgit-suite.$isuite.distro",
535 "dgit.default.distro");
539 sub access_quirk () {
540 # returns (quirk name, distro to use instead, quirk-specific info)
541 my $basedistro = access_basedistro();
542 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
544 if (defined $backports_quirk) {
545 my $re = $backports_quirk;
546 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
548 $re =~ s/\%/([-0-9a-z_]+)/
549 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
550 if ($isuite =~ m/^$re$/) {
551 return ('backports',"$basedistro-backports",$1);
554 return ('none',$basedistro);
557 sub access_distro () {
558 return (access_quirk())[1];
563 my $basedistro = access_basedistro();
564 my $distro = $idistro || access_distro();
565 my $value = cfg(map {
566 ("dgit-distro.$distro.$_",
567 "dgit-distro.$basedistro.$_",
573 sub string_to_ssh ($) {
575 if ($spec =~ m/\s/) {
576 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
582 sub access_cfg_ssh () {
583 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
584 if (!defined $gitssh) {
587 return string_to_ssh $gitssh;
591 sub access_someuserhost ($) {
593 my $user = access_cfg("$some-user",'username');
594 my $host = access_cfg("$some-host");
595 return length($user) ? "$user\@$host" : $host;
598 sub access_gituserhost () {
599 return access_someuserhost('git');
602 sub access_giturl () {
603 my $url = access_cfg('git-url','RETURN-UNDEF');
606 access_cfg('git-proto').
607 access_gituserhost().
608 access_cfg('git-path');
610 return "$url/$package.git";
613 sub parsecontrolfh ($$;$) {
614 my ($fh, $desc, $allowsigned) = @_;
615 our $dpkgcontrolhash_noissigned;
618 my %opts = ('name' => $desc);
619 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
620 print STDERR Dumper(\%opts);
621 $c = Dpkg::Control::Hash->new(%opts);
622 $c->parse($fh,$desc) or die "parsing of $desc failed";
623 last if $allowsigned;
624 last if $dpkgcontrolhash_noissigned;
625 my $issigned= $c->get_option('is_pgp_signed');
626 if (!defined $issigned) {
627 $dpkgcontrolhash_noissigned= 1;
628 seek $fh, 0,0 or die "seek $desc: $!";
629 } elsif ($issigned) {
630 fail "control file $desc is (already) PGP-signed. ".
631 " Note that dgit push needs to modify the .dsc and then".
632 " do the signature itself";
641 my ($file, $desc) = @_;
642 my $fh = new IO::Handle;
643 open $fh, '<', $file or die "$file: $!";
644 my $c = parsecontrolfh($fh,$desc);
645 $fh->error and die $!;
651 my ($dctrl,$field) = @_;
652 my $v = $dctrl->{$field};
653 return $v if defined $v;
654 fail "missing field $field in ".$v->get_option('name');
658 my $c = Dpkg::Control::Hash->new();
659 my $p = new IO::Handle;
660 my @cmd = (qw(dpkg-parsechangelog), @_);
661 open $p, '-|', @cmd or die $!;
663 $?=0; $!=0; close $p or failedcmd @cmd;
667 sub git_get_ref ($) {
669 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
671 $?==256 or fail "git show-ref failed (status $?)";
672 printdebug "ref $refname= [show-ref exited 1]\n";
675 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
676 printdebug "ref $refname=$1\n";
679 printdebug "ref $refname= [no match]\n";
686 defined $d or fail "getcwd failed: $!";
692 sub archive_query ($) {
694 my $query = access_cfg('archive-query','RETURN-UNDEF');
695 if (!defined $query) {
696 my $distro = access_basedistro();
697 if ($distro eq 'debian') {
699 access_someuserhost('sshpsql').':'.
700 access_cfg('sshpsql-dbname');
702 $query = "madison:$distro";
705 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
708 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
711 sub pool_dsc_subpath ($$) {
712 my ($vsn,$component) = @_; # $package is implict arg
713 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
714 return "/pool/$component/$prefix/$package/".dscfn($vsn);
717 sub archive_query_madison ($$) {
718 my ($proto,$data) = @_;
719 die unless $proto eq 'madison';
720 $rmad{$package} ||= cmdoutput
721 qw(rmadison -asource),"-s$isuite","-u$data",$package;
722 my $rmad = $rmad{$package};
723 return madison_parse($rmad);
726 sub madison_parse ($) {
729 foreach my $l (split /\n/, $rmad) {
730 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
731 \s*( [^ \t|]+ )\s* \|
732 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
733 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
734 $1 eq $package or die "$rmad $package ?";
741 $component = access_cfg('archive-query-default-component');
743 $5 eq 'source' or die "$rmad ?";
744 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
746 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
749 sub canonicalise_suite_madison ($$) {
750 # madison canonicalises for us
751 my @r = archive_query_madison($_[0],$_[1]);
753 "unable to canonicalise suite using package $package".
754 " which does not appear to exist in suite $isuite;".
755 " --existing-package may help";
760 my ($data,$sql) = @_;
761 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
762 my ($userhost,$dbname) = ($`,$'); #';
764 my @cmd = (access_cfg_ssh, $userhost,
765 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
766 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
767 open P, "-|", @cmd or die $!;
770 printdebug("$debugprefix>|$_|\n");
773 $!=0; $?=0; close P or failedcmd @cmd;
775 my $nrows = pop @rows;
776 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
777 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
778 @rows = map { [ split /\|/, $_ ] } @rows;
779 my $ncols = scalar @{ shift @rows };
780 die if grep { scalar @$_ != $ncols } @rows;
784 sub sql_injection_check {
785 foreach (@_) { die "$_ $& ?" if m/[']/; }
788 sub archive_query_sshpsql ($$) {
789 my ($proto,$data) = @_;
790 sql_injection_check $isuite, $package;
791 my @rows = sshpsql($data, <<END);
792 SELECT source.version, component.name, files.filename, files.sha256sum
794 JOIN src_associations ON source.id = src_associations.source
795 JOIN suite ON suite.id = src_associations.suite
796 JOIN dsc_files ON dsc_files.source = source.id
797 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
798 JOIN component ON component.id = files_archive_map.component_id
799 JOIN files ON files.id = dsc_files.file
800 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
801 AND source.source='$package'
802 AND files.filename LIKE '%.dsc';
804 @rows = sort { -version_compare_string($a->[0],$b->[0]) } @rows;
805 my $digester = Digest::SHA->new(256);
807 my ($vsn,$component,$filename,$sha256sum) = @$_;
808 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
813 sub canonicalise_suite_sshpsql ($$) {
814 my ($proto,$data) = @_;
815 sql_injection_check $isuite;
816 my @rows = sshpsql($data, <<END);
817 SELECT suite.codename
818 FROM suite where suite_name='$isuite' or codename='$isuite';
820 @rows = map { $_->[0] } @rows;
821 fail "unknown suite $isuite" unless @rows;
822 die "ambiguous $isuite: @rows ?" if @rows>1;
826 sub canonicalise_suite_dummycat ($$) {
827 my ($proto,$data) = @_;
828 my $dpath = "$data/suite.$isuite";
829 if (!open C, "<", $dpath) {
830 $!==ENOENT or die "$dpath: $!";
831 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
835 chomp or die "$dpath: $!";
837 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
841 sub archive_query_dummycat ($$) {
842 my ($proto,$data) = @_;
843 canonicalise_suite();
844 my $dpath = "$data/package.$csuite.$package";
845 if (!open C, "<", $dpath) {
846 $!==ENOENT or die "$dpath: $!";
847 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
855 printdebug "dummycat query $csuite $package $dpath | $_\n";
856 my @row = split /\s+/, $_;
857 @row==2 or die "$dpath: $_ ?";
860 C->error and die "$dpath: $!";
862 return sort { -version_compare_string($a->[0],$b->[0]); } @rows;
865 sub canonicalise_suite () {
866 return if defined $csuite;
867 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
868 $csuite = archive_query('canonicalise_suite');
869 if ($isuite ne $csuite) {
870 progress "canonical suite name for $isuite is $csuite";
874 sub get_archive_dsc () {
875 canonicalise_suite();
876 my @vsns = archive_query('archive_query');
877 foreach my $vinfo (@vsns) {
878 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
879 $dscurl = access_cfg('mirror').$subpath;
880 $dscdata = url_get($dscurl);
882 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
887 $digester->add($dscdata);
888 my $got = $digester->hexdigest();
890 fail "$dscurl has hash $got but".
891 " archive told us to expect $digest";
893 my $dscfh = new IO::File \$dscdata, '<' or die $!;
894 printdebug Dumper($dscdata) if $debug>1;
895 $dsc = parsecontrolfh($dscfh,$dscurl,1);
896 printdebug Dumper($dsc) if $debug>1;
897 my $fmt = getfield $dsc, 'Format';
898 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
899 $dsc_checked = !!$digester;
905 sub check_for_git () {
907 my $how = access_cfg('git-check');
908 if ($how eq 'ssh-cmd') {
910 (access_cfg_ssh, access_gituserhost(),
911 " set -e; cd ".access_cfg('git-path').";".
912 " if test -d $package.git; then echo 1; else echo 0; fi");
913 my $r= cmdoutput @cmd;
914 failedcmd @cmd unless $r =~ m/^[01]$/;
916 } elsif ($how eq 'true') {
918 } elsif ($how eq 'false') {
921 badcfg "unknown git-check \`$how'";
925 sub create_remote_git_repo () {
926 my $how = access_cfg('git-create');
927 if ($how eq 'ssh-cmd') {
929 (access_cfg_ssh, access_gituserhost(),
930 "set -e; cd ".access_cfg('git-path').";".
931 " cp -a _template $package.git");
932 } elsif ($how eq 'true') {
935 badcfg "unknown git-create \`$how'";
939 our ($dsc_hash,$lastpush_hash);
941 our $ud = '.git/dgit/unpack';
949 sub mktree_in_ud_from_only_subdir () {
950 # changes into the subdir
953 $dirs[0] =~ m#^([^/]+)/\.$# or die;
956 fail "source package contains .git directory" if stat '.git';
957 die $! unless $!==&ENOENT;
958 runcmd qw(git init -q);
959 rmtree('.git/objects');
960 symlink '../../../../objects','.git/objects' or die $!;
961 runcmd @git, qw(add -Af);
962 my $tree = cmdoutput @git, qw(write-tree);
963 $tree =~ m/^\w+$/ or die "$tree ?";
967 sub dsc_files_info () {
968 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
969 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
970 ['Files', 'Digest::MD5', 'new()']) {
971 my ($fname, $module, $method) = @$csumi;
972 my $field = $dsc->{$fname};
973 next unless defined $field;
974 eval "use $module; 1;" or die $@;
976 foreach (split /\n/, $field) {
978 m/^(\w+) (\d+) (\S+)$/ or
979 fail "could not parse .dsc $fname line \`$_'";
980 my $digester = eval "$module"."->$method;" or die $@;
985 Digester => $digester,
990 fail "missing any supported Checksums-* or Files field in ".
991 $dsc->get_option('name');
995 map { $_->{Filename} } dsc_files_info();
998 sub is_orig_file ($) {
1000 m/\.orig(?:-\w+)?\.tar\.\w+$/;
1003 sub make_commit ($) {
1005 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1008 sub clogp_authline ($) {
1010 my $author = getfield $clogp, 'Maintainer';
1011 $author =~ s#,.*##ms;
1012 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1013 my $authline = "$author $date";
1014 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1015 fail "unexpected commit author line format \`$authline'".
1016 " (was generated from changelog Maintainer field)";
1020 sub generate_commit_from_dsc () {
1024 foreach my $fi (dsc_files_info()) {
1025 my $f = $fi->{Filename};
1026 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1028 link "../../../$f", $f
1032 complete_file_from_dsc('.', $fi);
1034 if (is_orig_file($f)) {
1035 link $f, "../../../../$f"
1041 my $dscfn = "$package.dsc";
1043 open D, ">", $dscfn or die "$dscfn: $!";
1044 print D $dscdata or die "$dscfn: $!";
1045 close D or die "$dscfn: $!";
1046 my @cmd = qw(dpkg-source);
1047 push @cmd, '--no-check' if $dsc_checked;
1048 push @cmd, qw(-x --), $dscfn;
1051 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1052 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1053 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1054 my $authline = clogp_authline $clogp;
1055 my $changes = getfield $clogp, 'Changes';
1056 open C, ">../commit.tmp" or die $!;
1057 print C <<END or die $!;
1064 # imported from the archive
1067 my $outputhash = make_commit qw(../commit.tmp);
1068 my $cversion = getfield $clogp, 'Version';
1069 progress "synthesised git commit from .dsc $cversion";
1070 if ($lastpush_hash) {
1071 runcmd @git, qw(reset --hard), $lastpush_hash;
1072 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1073 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1074 my $oversion = getfield $oldclogp, 'Version';
1076 version_compare_string($oversion, $cversion);
1078 # git upload/ is earlier vsn than archive, use archive
1079 open C, ">../commit2.tmp" or die $!;
1080 print C <<END or die $!;
1082 parent $lastpush_hash
1087 Record $package ($cversion) in archive suite $csuite
1089 $outputhash = make_commit qw(../commit2.tmp);
1090 } elsif ($vcmp > 0) {
1091 print STDERR <<END or die $!;
1093 Version actually in archive: $cversion (older)
1094 Last allegedly pushed/uploaded: $oversion (newer or same)
1097 $outputhash = $lastpush_hash;
1099 $outputhash = $lastpush_hash;
1102 changedir '../../../..';
1103 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1104 'DGIT_ARCHIVE', $outputhash;
1105 cmdoutput @git, qw(log -n2), $outputhash;
1106 # ... gives git a chance to complain if our commit is malformed
1111 sub complete_file_from_dsc ($$) {
1112 our ($dstdir, $fi) = @_;
1113 # Ensures that we have, in $dir, the file $fi, with the correct
1114 # contents. (Downloading it from alongside $dscurl if necessary.)
1116 my $f = $fi->{Filename};
1117 my $tf = "$dstdir/$f";
1121 progress "using existing $f";
1123 die "$tf $!" unless $!==&ENOENT;
1126 $furl =~ s{/[^/]+$}{};
1128 die "$f ?" unless $f =~ m/^${package}_/;
1129 die "$f ?" if $f =~ m#/#;
1130 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1131 next if !act_local();
1135 open F, "<", "$tf" or die "$tf: $!";
1136 $fi->{Digester}->reset();
1137 $fi->{Digester}->addfile(*F);
1138 F->error and die $!;
1139 my $got = $fi->{Digester}->hexdigest();
1140 $got eq $fi->{Hash} or
1141 fail "file $f has hash $got but .dsc".
1142 " demands hash $fi->{Hash} ".
1143 ($downloaded ? "(got wrong file from archive!)"
1144 : "(perhaps you should delete this file?)");
1147 sub ensure_we_have_orig () {
1148 foreach my $fi (dsc_files_info()) {
1149 my $f = $fi->{Filename};
1150 next unless is_orig_file($f);
1151 complete_file_from_dsc('..', $fi);
1156 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1159 sub is_fast_fwd ($$) {
1160 my ($ancestor,$child) = @_;
1161 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1162 my $mb = cmdoutput_errok @cmd;
1164 return rev_parse($mb) eq rev_parse($ancestor);
1166 $?==256 or failedcmd @cmd;
1171 sub git_fetch_us () {
1172 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1175 sub fetch_from_archive () {
1176 # ensures that lrref() is what is actually in the archive,
1177 # one way or another
1181 foreach my $field (@ourdscfield) {
1182 $dsc_hash = $dsc->{$field};
1183 last if defined $dsc_hash;
1185 if (defined $dsc_hash) {
1186 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1188 progress "last upload to archive specified git hash";
1190 progress "last upload to archive has NO git hash";
1193 progress "no version available from the archive";
1196 $lastpush_hash = git_get_ref(lrref());
1197 printdebug "previous reference hash=$lastpush_hash\n";
1199 if (defined $dsc_hash) {
1200 fail "missing remote git history even though dsc has hash -".
1201 " could not find ref ".lrref().
1202 " (should have been fetched from ".access_giturl()."#".rrref().")"
1203 unless $lastpush_hash;
1205 ensure_we_have_orig();
1206 if ($dsc_hash eq $lastpush_hash) {
1207 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1208 print STDERR <<END or die $!;
1210 Git commit in archive is behind the last version allegedly pushed/uploaded.
1211 Commit referred to by archive: $dsc_hash
1212 Last allegedly pushed/uploaded: $lastpush_hash
1215 $hash = $lastpush_hash;
1217 fail "archive's .dsc refers to ".$dsc_hash.
1218 " but this is an ancestor of ".$lastpush_hash;
1221 $hash = generate_commit_from_dsc();
1222 } elsif ($lastpush_hash) {
1223 # only in git, not in the archive yet
1224 $hash = $lastpush_hash;
1225 print STDERR <<END or die $!;
1227 Package not found in the archive, but has allegedly been pushed using dgit.
1231 printdebug "nothing found!\n";
1232 if (defined $skew_warning_vsn) {
1233 print STDERR <<END or die $!;
1235 Warning: relevant archive skew detected.
1236 Archive allegedly contains $skew_warning_vsn
1237 But we were not able to obtain any version from the archive or git.
1243 printdebug "current hash=$hash\n";
1244 if ($lastpush_hash) {
1245 fail "not fast forward on last upload branch!".
1246 " (archive's version left in DGIT_ARCHIVE)"
1247 unless is_fast_fwd($lastpush_hash, $hash);
1249 if (defined $skew_warning_vsn) {
1251 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1252 my $clogf = ".git/dgit/changelog.tmp";
1253 runcmd shell_cmd "exec >$clogf",
1254 @git, qw(cat-file blob), "$hash:debian/changelog";
1255 my $gotclogp = parsechangelog("-l$clogf");
1256 my $got_vsn = getfield $gotclogp, 'Version';
1257 printdebug "SKEW CHECK GOT $got_vsn\n";
1258 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
1259 print STDERR <<END or die $!;
1261 Warning: archive skew detected. Using the available version:
1262 Archive allegedly contains $skew_warning_vsn
1263 We were able to obtain only $got_vsn
1268 if ($lastpush_hash ne $hash) {
1269 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1273 dryrun_report @upd_cmd;
1281 canonicalise_suite();
1282 badusage "dry run makes no sense with clone" unless act_local();
1283 mkdir $dstdir or die "$dstdir $!";
1285 runcmd @git, qw(init -q);
1286 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1287 open H, "> .git/HEAD" or die $!;
1288 print H "ref: ".lref()."\n" or die $!;
1290 runcmd @git, qw(remote add), 'origin', access_giturl();
1291 if (check_for_git()) {
1292 progress "fetching existing git history";
1294 runcmd_ordryrun_local @git, qw(fetch origin);
1296 progress "starting new git history";
1298 fetch_from_archive() or no_such_package;
1299 my $vcsgiturl = $dsc->{'Vcs-Git'};
1300 if (length $vcsgiturl) {
1301 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1303 runcmd @git, qw(reset --hard), lrref();
1304 printdone "ready for work in $dstdir";
1308 if (check_for_git()) {
1311 fetch_from_archive() or no_such_package();
1312 printdone "fetched into ".lrref();
1317 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1319 printdone "fetched to ".lrref()." and merged into HEAD";
1322 sub check_not_dirty () {
1323 return if $ignoredirty;
1324 my @cmd = (@git, qw(diff --quiet HEAD));
1325 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1326 $!=0; $?=0; system @cmd;
1327 return if !$! && !$?;
1328 if (!$! && $?==256) {
1329 fail "working tree is dirty (does not match HEAD)";
1335 sub commit_quilty_patch () {
1336 my $output = cmdoutput @git, qw(status --porcelain);
1338 foreach my $l (split /\n/, $output) {
1339 next unless $l =~ m/\S/;
1340 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1345 progress "nothing quilty to commit, ok.";
1348 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1349 my $m = "Commit Debian 3.0 (quilt) metadata";
1351 runcmd_ordryrun_local @git, qw(commit -m), $m;
1356 return 0 unless $format eq '3.0 (quilt)';
1357 progress "Format \`$format', urgh";
1359 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1365 sub push_parse_changelog ($) {
1368 my $clogp = Dpkg::Control::Hash->new();
1369 $clogp->load($clogpfn) or die;
1371 $package = getfield $clogp, 'Source';
1372 my $cversion = getfield $clogp, 'Version';
1373 my $tag = debiantag($cversion);
1374 runcmd @git, qw(check-ref-format), $tag;
1376 my $dscfn = dscfn($cversion);
1378 return ($clogp, $cversion, $tag, $dscfn);
1381 sub push_parse_dsc ($$$) {
1382 my ($dscfn,$dscfnwhat, $cversion) = @_;
1383 $dsc = parsecontrol($dscfn,$dscfnwhat);
1384 my $dversion = getfield $dsc, 'Version';
1385 my $dscpackage = getfield $dsc, 'Source';
1386 ($dscpackage eq $package && $dversion eq $cversion) or
1387 fail "$dscfn is for $dscpackage $dversion".
1388 " but debian/changelog is for $package $cversion";
1391 sub push_mktag ($$$$$$$) {
1392 my ($head,$clogp,$tag,
1394 $changesfile,$changesfilewhat,
1397 $dsc->{$ourdscfield[0]} = $head;
1398 $dsc->save("$dscfn.tmp") or die $!;
1400 my $changes = parsecontrol($changesfile,$changesfilewhat);
1401 foreach my $field (qw(Source Distribution Version)) {
1402 $changes->{$field} eq $clogp->{$field} or
1403 fail "changes field $field \`$changes->{$field}'".
1404 " does not match changelog \`$clogp->{$field}'";
1407 my $cversion = getfield $clogp, 'Version';
1408 my $clogsuite = getfield $clogp, 'Distribution';
1410 # We make the git tag by hand because (a) that makes it easier
1411 # to control the "tagger" (b) we can do remote signing
1412 my $authline = clogp_authline $clogp;
1413 open TO, '>', $tfn->('.tmp') or die $!;
1414 print TO <<END or die $!;
1420 $package release $cversion for $clogsuite ($csuite) [dgit]
1424 my $tagobjfn = $tfn->('.tmp');
1426 if (!defined $keyid) {
1427 $keyid = access_cfg('keyid','RETURN-UNDEF');
1429 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1430 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1431 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1432 push @sign_cmd, $tfn->('.tmp');
1433 runcmd_ordryrun @sign_cmd;
1435 $tagobjfn = $tfn->('.signed.tmp');
1436 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1437 $tfn->('.tmp'), $tfn->('.tmp.asc');
1444 sub sign_changes ($) {
1445 my ($changesfile) = @_;
1447 my @debsign_cmd = @debsign;
1448 push @debsign_cmd, "-k$keyid" if defined $keyid;
1449 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1450 push @debsign_cmd, $changesfile;
1451 runcmd_ordryrun @debsign_cmd;
1456 printdebug "actually entering push\n";
1459 access_giturl(); # check that success is vaguely likely
1461 my $clogpfn = ".git/dgit/changelog.822.tmp";
1462 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1464 responder_send_file('parsed-changelog', $clogpfn);
1466 my ($clogp, $cversion, $tag, $dscfn) =
1467 push_parse_changelog("$clogpfn");
1469 my $dscpath = "$buildproductsdir/$dscfn";
1471 fail "looked for .dsc $dscfn, but $!;".
1472 " maybe you forgot to build";
1474 responder_send_file('dsc', $dscpath);
1476 push_parse_dsc($dscpath, $dscfn, $cversion);
1478 my $format = getfield $dsc, 'Format';
1479 printdebug "format $format\n";
1480 if (madformat($format)) {
1481 commit_quilty_patch();
1485 progress "checking that $dscfn corresponds to HEAD";
1486 runcmd qw(dpkg-source -x --),
1487 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1488 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1489 changedir '../../../..';
1490 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1491 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1492 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1494 my $r = system @diffcmd;
1497 fail "$dscfn specifies a different tree to your HEAD commit;".
1498 " perhaps you forgot to build".
1499 ($diffopt eq '--exit-code' ? "" :
1500 " (run with -D to see full diff output)");
1506 #do fast forward check and maybe fake merge
1507 # if (!is_fast_fwd(mainbranch
1508 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1509 # map { lref($_).":".rref($_) }
1511 my $head = rev_parse('HEAD');
1512 if (!$changesfile) {
1513 my $multi = "$buildproductsdir/".
1514 "${package}_".(stripepoch $cversion)."_multi.changes";
1515 if (stat "$multi") {
1516 $changesfile = $multi;
1518 $!==&ENOENT or die "$multi: $!";
1519 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1520 my @cs = glob "$buildproductsdir/$pat";
1521 fail "failed to find unique changes file".
1522 " (looked for $pat in $buildproductsdir, or $multi);".
1523 " perhaps you need to use dgit -C"
1525 ($changesfile) = @cs;
1528 $changesfile = "$buildproductsdir/$changesfile";
1531 responder_send_file('changes',$changesfile);
1532 responder_send_command("param head $head");
1533 responder_send_command("param csuite $csuite");
1535 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1538 if ($we_are_responder) {
1539 $tagobjfn = $tfn->('.signed.tmp');
1540 responder_receive_files('signed-tag', $tagobjfn);
1543 push_mktag($head,$clogp,$tag,
1545 $changesfile,$changesfile,
1549 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1550 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1551 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1552 runcmd_ordryrun @git, qw(tag -v --), $tag;
1554 if (!check_for_git()) {
1555 create_remote_git_repo();
1557 runcmd_ordryrun @git, qw(push),access_giturl(),
1558 "HEAD:".rrref(), "refs/tags/$tag";
1559 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1561 if ($we_are_responder) {
1562 my $dryrunsuffix = act_local() ? "" : ".tmp";
1563 responder_receive_files('signed-dsc-changes',
1564 "$dscpath$dryrunsuffix",
1565 "$changesfile$dryrunsuffix");
1568 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1570 progress "[new .dsc left in $dscpath.tmp]";
1572 sign_changes $changesfile;
1575 my $host = access_cfg('upload-host','RETURN-UNDEF');
1576 my @hostarg = defined($host) ? ($host,) : ();
1577 runcmd_ordryrun @dput, @hostarg, $changesfile;
1578 printdone "pushed and uploaded $cversion";
1580 responder_send_command("complete");
1586 badusage "-p is not allowed with clone; specify as argument instead"
1587 if defined $package;
1590 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1591 ($package,$isuite) = @ARGV;
1592 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1593 ($package,$dstdir) = @ARGV;
1594 } elsif (@ARGV==3) {
1595 ($package,$isuite,$dstdir) = @ARGV;
1597 badusage "incorrect arguments to dgit clone";
1599 $dstdir ||= "$package";
1602 fail "$dstdir already exists";
1603 } elsif ($! != &ENOENT) {
1608 if ($rmonerror && !$dryrun_level) {
1609 $cwd_remove= getcwd();
1611 return unless defined $cwd_remove;
1612 if (!chdir "$cwd_remove") {
1613 return if $!==&ENOENT;
1614 die "chdir $cwd_remove: $!";
1616 rmtree($dstdir) or die "remove $dstdir: $!\n";
1621 $cwd_remove = undef;
1624 sub branchsuite () {
1625 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1626 if ($branch =~ m#$lbranch_re#o) {
1633 sub fetchpullargs () {
1634 if (!defined $package) {
1635 my $sourcep = parsecontrol('debian/control','debian/control');
1636 $package = getfield $sourcep, 'Source';
1639 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1641 my $clogp = parsechangelog();
1642 $isuite = getfield $clogp, 'Distribution';
1644 canonicalise_suite();
1645 progress "fetching from suite $csuite";
1646 } elsif (@ARGV==1) {
1648 canonicalise_suite();
1650 badusage "incorrect arguments to dgit fetch or dgit pull";
1668 badusage "-p is not allowed with dgit push" if defined $package;
1670 my $clogp = parsechangelog();
1671 $package = getfield $clogp, 'Source';
1674 } elsif (@ARGV==1) {
1675 ($specsuite) = (@ARGV);
1677 badusage "incorrect arguments to dgit push";
1679 $isuite = getfield $clogp, 'Distribution';
1681 local ($package) = $existing_package; # this is a hack
1682 canonicalise_suite();
1684 if (defined $specsuite && $specsuite ne $isuite) {
1685 canonicalise_suite();
1686 $csuite eq $specsuite or
1687 fail "dgit push: changelog specifies $isuite ($csuite)".
1688 " but command line specifies $specsuite";
1690 if (check_for_git()) {
1693 if (fetch_from_archive()) {
1694 is_fast_fwd(lrref(), 'HEAD') or
1695 fail "dgit push: HEAD is not a descendant".
1696 " of the archive's version.\n".
1697 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1700 fail "package appears to be new in this suite;".
1701 " if this is intentional, use --new";
1706 #---------- remote commands' implementation ----------
1708 sub cmd_remote_push_responder {
1709 my ($nrargs) = shift @ARGV;
1710 my (@rargs) = @ARGV[0..$nrargs-1];
1711 @ARGV = @ARGV[$nrargs..$#ARGV];
1715 $we_are_responder = 1;
1717 open PI, "<&STDIN" or die $!;
1718 open STDIN, "/dev/null" or die $!;
1719 open PO, ">&STDOUT" or die $!;
1721 open STDOUT, ">&STDERR" or die $!;
1724 responder_send_command("dgit-remote-push-ready");
1736 printdebug "(killing remote child $i_child_pid)\n";
1737 kill 15, $i_child_pid;
1739 if (defined $i_tmp && !defined $initiator_tempdir) {
1741 eval { rmtree $i_tmp; };
1745 END { i_cleanup(); }
1748 my ($base,$selector,@args) = @_;
1749 $selector =~ s/\-/_/g;
1750 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1756 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1766 push @rdgit, @ropts;
1767 push @rdgit, qw(remote-push-responder), (scalar @rargs), @rargs;
1769 my @cmd = (@ssh, $host, shellquote @rdgit);
1770 printcmd \*DEBUG,$debugprefix."+",@cmd;
1772 if (defined $initiator_tempdir) {
1773 rmtree $initiator_tempdir;
1774 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1775 $i_tmp = $initiator_tempdir;
1779 $i_child_pid = open2(\*RO, \*RI, @cmd);
1781 initiator_expect { m/^dgit-remote-push-ready/ };
1783 my ($icmd,$iargs) = initiator_expect {
1784 m/^(\S+)(?: (.*))?$/;
1787 i_method "i_resp", $icmd, $iargs;
1791 sub i_resp_progress ($) {
1793 my $msg = protocol_read_bytes \*RO, $rhs;
1797 sub i_resp_complete {
1798 my $pid = $i_child_pid;
1799 $i_child_pid = undef; # prevents killing some other process with same pid
1800 printdebug "waiting for remote child $pid...\n";
1801 my $got = waitpid $pid, 0;
1802 die $! unless $got == $pid;
1803 die "remote child failed $?" if $?;
1806 printdebug "all done\n";
1810 sub i_resp_file ($) {
1812 my $localname = i_method "i_localname", $keyword;
1813 my $localpath = "$i_tmp/$localname";
1814 stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1815 protocol_receive_file \*RO, $localpath;
1816 i_method "i_file", $keyword;
1821 sub i_resp_param ($) {
1822 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1828 sub i_resp_want ($) {
1830 die "$keyword ?" if $i_wanted{$keyword}++;
1831 my @localpaths = i_method "i_want", $keyword;
1832 printdebug "[[ $keyword @localpaths\n";
1833 foreach my $localpath (@localpaths) {
1834 protocol_send_file \*RI, $localpath;
1836 print RI "files-end\n" or die $!;
1839 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1841 sub i_localname_parsed_changelog {
1842 return "remote-changelog.822";
1844 sub i_file_parsed_changelog {
1845 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1846 push_parse_changelog "$i_tmp/remote-changelog.822";
1847 die if $i_dscfn =~ m#/|^\W#;
1850 sub i_localname_dsc {
1851 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1856 sub i_localname_changes {
1857 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1858 $i_changesfn = $i_dscfn;
1859 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1860 return $i_changesfn;
1862 sub i_file_changes { }
1864 sub i_want_signed_tag {
1865 printdebug Dumper(\%i_param, $i_dscfn);
1866 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1867 && defined $i_param{'csuite'}
1868 or badproto \*RO, "premature desire for signed-tag";
1869 my $head = $i_param{'head'};
1870 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1872 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1874 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1877 push_mktag $head, $i_clogp, $i_tag,
1879 $i_changesfn, 'remote changes',
1880 sub { "tag$_[0]"; };
1885 sub i_want_signed_dsc_changes {
1886 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1887 sign_changes $i_changesfn;
1888 return ($i_dscfn, $i_changesfn);
1891 #---------- building etc. ----------
1897 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1899 sub build_maybe_quilt_fixup () {
1900 if (!open F, "debian/source/format") {
1901 die $! unless $!==&ENOENT;
1905 F->error and die $!;
1907 return unless madformat($_);
1910 my @cmd = (@git, qw(ls-files --exclude-standard -iodm));
1911 my $problems = cmdoutput @cmd;
1912 if (length $problems) {
1913 print STDERR "problematic files:\n";
1914 print STDERR " $_\n" foreach split /\n/, $problems;
1915 fail "Cannot do quilt fixup in tree containing ignored files. ".
1916 "Perhaps your package's clean target is broken, in which".
1917 " case -wg (which says to use git-clean -xdf) may help.";
1920 my $clogp = parsechangelog();
1921 my $version = getfield $clogp, 'Version';
1922 my $author = getfield $clogp, 'Maintainer';
1923 my $headref = rev_parse('HEAD');
1926 my $patchname = "auto-$version-$headref-$time";
1927 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1929 my $descfn = ".git/dgit/quilt-description.tmp";
1930 open O, '>', $descfn or die "$descfn: $!";
1932 $msg =~ s/^\s+$/ ./mg;
1933 print O <<END or die $!;
1934 Description: Automatically generated patch ($clogp->{Version})
1935 Last (up to) $ncommits git changes, FYI:
1945 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1946 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1947 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1948 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
1951 if (!open P, '>>', ".pc/applied-patches") {
1952 $!==&ENOENT or die $!;
1957 commit_quilty_patch();
1960 sub quilt_fixup_editor () {
1961 my $descfn = $ENV{$fakeeditorenv};
1962 my $editing = $ARGV[$#ARGV];
1963 open I1, '<', $descfn or die "$descfn: $!";
1964 open I2, '<', $editing or die "$editing: $!";
1965 unlink $editing or die "$editing: $!";
1966 open O, '>', $editing or die "$editing: $!";
1967 while (<I1>) { print O or die $!; } I1->error and die $!;
1970 $copying ||= m/^\-\-\- /;
1971 next unless $copying;
1974 I2->error and die $!;
1980 if ($cleanmode eq 'dpkg-source') {
1981 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
1982 } elsif ($cleanmode eq 'git') {
1983 runcmd_ordryrun_local @git, qw(clean -xdf);
1984 } elsif ($cleanmode eq 'none') {
1991 badusage "clean takes no additional arguments" if @ARGV;
1996 badusage "-p is not allowed when building" if defined $package;
1999 my $clogp = parsechangelog();
2000 $isuite = getfield $clogp, 'Distribution';
2001 $package = getfield $clogp, 'Source';
2002 $version = getfield $clogp, 'Version';
2003 build_maybe_quilt_fixup();
2006 sub changesopts () {
2007 my @opts =@changesopts[1..$#changesopts];
2008 if (!defined $changes_since_version) {
2009 my @vsns = archive_query('archive_query');
2010 my @quirk = access_quirk();
2011 if ($quirk[0] eq 'backports') {
2012 local $isuite = $quirk[2];
2014 canonicalise_suite();
2015 push @vsns, archive_query('archive_query');
2018 @vsns = map { $_->[0] } @vsns;
2019 @vsns = sort { -version_compare_string($a, $b) } @vsns;
2020 $changes_since_version = $vsns[0];
2021 progress "changelog will contain changes since $vsns[0]";
2023 $changes_since_version = '_';
2024 progress "package seems new, not specifying -v<version>";
2027 if ($changes_since_version ne '_') {
2028 unshift @opts, "-v$changes_since_version";
2035 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2036 printdone "build successful\n";
2042 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2043 "--git-builder=@dpkgbuildpackage");
2044 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2045 canonicalise_suite();
2046 push @cmd, "--git-debian-branch=".lbranch();
2048 push @cmd, changesopts();
2049 runcmd_ordryrun_local @cmd, @ARGV;
2050 printdone "build successful\n";
2055 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2056 $dscfn = dscfn($version);
2057 if ($cleanmode eq 'dpkg-source') {
2058 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2061 my $pwd = must_getcwd();
2062 my $leafdir = basename $pwd;
2064 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2066 runcmd_ordryrun_local qw(sh -ec),
2067 'exec >$1; shift; exec "$@"','x',
2068 "../$sourcechanges",
2069 @dpkggenchanges, qw(-S), changesopts();
2073 sub cmd_build_source {
2074 badusage "build-source takes no additional arguments" if @ARGV;
2076 printdone "source built, results in $dscfn and $sourcechanges";
2082 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2084 stat $dscfn or fail "$dscfn (in parent directory): $!";
2085 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
2086 foreach my $cf (glob $pat) {
2087 next if $cf eq $sourcechanges;
2088 unlink $cf or fail "remove $cf: $!";
2091 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2092 my @changesfiles = glob $pat;
2093 @changesfiles = sort {
2094 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2097 fail "wrong number of different changes files (@changesfiles)"
2098 unless @changesfiles;
2099 runcmd_ordryrun_local @mergechanges, @changesfiles;
2100 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2102 stat $multichanges or fail "$multichanges: $!";
2104 printdone "build successful, results in $multichanges\n" or die $!;
2107 sub cmd_quilt_fixup {
2108 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2109 my $clogp = parsechangelog();
2110 $version = getfield $clogp, 'Version';
2111 build_maybe_quilt_fixup();
2114 #---------- argument parsing and main program ----------
2117 print "dgit version $our_version\n" or die $!;
2124 if (defined $ENV{'DGIT_SSH'}) {
2125 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2126 } elsif (defined $ENV{'GIT_SSH'}) {
2127 @ssh = ($ENV{'GIT_SSH'});
2131 last unless $ARGV[0] =~ m/^-/;
2135 if (m/^--dry-run$/) {
2138 } elsif (m/^--damp-run$/) {
2141 } elsif (m/^--no-sign$/) {
2144 } elsif (m/^--help$/) {
2146 } elsif (m/^--version$/) {
2148 } elsif (m/^--new$/) {
2151 } elsif (m/^--since-version=([^_]+|_)$/) {
2153 $changes_since_version = $1;
2154 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2155 ($om = $opts_opt_map{$1}) &&
2159 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2160 !$opts_opt_cmdonly{$1} &&
2161 ($om = $opts_opt_map{$1})) {
2164 } elsif (m/^--existing-package=(.*)/s) {
2166 $existing_package = $1;
2167 } elsif (m/^--initiator-tempdir=(.*)/s) {
2168 $initiator_tempdir = $1;
2169 $initiator_tempdir =~ m#^/# or
2170 badusage "--initiator-tempdir must be used specify an".
2171 " absolute, not relative, directory."
2172 } elsif (m/^--distro=(.*)/s) {
2175 } elsif (m/^--build-products-dir=(.*)/s) {
2177 $buildproductsdir = $1;
2178 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2181 } elsif (m/^--clean=(.*)$/s) {
2182 badusage "unknown cleaning mode \`$1'";
2183 } elsif (m/^--ignore-dirty$/s) {
2186 } elsif (m/^--no-quilt-fixup$/s) {
2189 } elsif (m/^--no-rm-on-error$/s) {
2193 badusage "unknown long option \`$_'";
2200 } elsif (s/^-L/-/) {
2203 } elsif (s/^-h/-/) {
2205 } elsif (s/^-D/-/) {
2207 open DEBUG, ">&STDERR" or die $!;
2210 } elsif (s/^-N/-/) {
2213 } elsif (s/^-v([^_]+|_)$//s) {
2215 $changes_since_version = $1;
2218 push @changesopts, $_;
2220 } elsif (s/^-c(.*=.*)//s) {
2222 push @git, '-c', $1;
2223 } elsif (s/^-d(.*)//s) {
2226 } elsif (s/^-C(.*)//s) {
2229 if ($changesfile =~ s#^(.*)/##) {
2230 $buildproductsdir = $1;
2232 } elsif (s/^-k(.*)//s) {
2234 } elsif (s/^-wn//s) {
2236 $cleanmode = 'none';
2237 } elsif (s/^-wg//s) {
2240 } elsif (s/^-wd//s) {
2242 $cleanmode = 'dpkg-source';
2244 badusage "unknown short option \`$_'";
2251 if ($ENV{$fakeeditorenv}) {
2252 quilt_fixup_editor();
2256 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2257 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2258 if $dryrun_level == 1;
2260 print STDERR $helpmsg or die $!;
2263 my $cmd = shift @ARGV;
2266 my $fn = ${*::}{"cmd_$cmd"};
2267 $fn or badusage "unknown operation $cmd";