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);
36 our $our_version = 'UNRELEASED'; ###substituted###
38 our $rpushprotovsn = 2;
40 our $isuite = 'unstable';
46 our $dryrun_level = 0;
48 our $buildproductsdir = '..';
53 our $existing_package = 'dpkg';
54 our $cleanmode = 'dpkg-source';
55 our $changes_since_version;
56 our $we_are_responder;
57 our $initiator_tempdir;
59 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
61 our $suite_re = '[-+.0-9a-z]+';
64 our (@dget) = qw(dget);
65 our (@curl) = qw(curl -f);
66 our (@dput) = qw(dput);
67 our (@debsign) = qw(debsign);
69 our (@sbuild) = qw(sbuild -A);
71 our (@dgit) = qw(dgit);
72 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
73 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
74 our (@dpkggenchanges) = qw(dpkg-genchanges);
75 our (@mergechanges) = qw(mergechanges -f);
76 our (@changesopts) = ('');
78 our %opts_opt_map = ('dget' => \@dget, # accept for compatibility
81 'debsign' => \@debsign,
86 'dpkg-source' => \@dpkgsource,
87 'dpkg-buildpackage' => \@dpkgbuildpackage,
88 'dpkg-genchanges' => \@dpkggenchanges,
89 'ch' => \@changesopts,
90 'mergechanges' => \@mergechanges);
92 our %opts_opt_cmdonly = ('gpg' => 1);
97 open DEBUG, ">/dev/null" or die $!;
101 our $remotename = 'dgit';
102 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
103 our $branchprefix = 'dgit';
106 sub lbranch () { return "$branchprefix/$csuite"; }
107 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
108 sub lref () { return "refs/heads/".lbranch(); }
109 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
110 sub rrref () { return "refs/$branchprefix/$csuite"; }
125 return "${package}_".(stripepoch $vsn).$sfx
130 return srcfn($vsn,".dsc");
134 our $debugprefix = '';
139 foreach my $f (@end) {
141 warn "$us: cleanup: $@" if length $@;
145 our @signames = split / /, $Config{sig_name};
147 sub waitstatusmsg () {
149 return "terminated, reporting successful completion";
150 } elsif (!($? & 255)) {
151 return "failed with error exit status ".WEXITSTATUS($?);
152 } elsif (WIFSIGNALED($?)) {
153 my $signum=WTERMSIG($?);
154 return "died due to fatal signal ".
155 ($signames[$signum] // "number $signum").
156 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
158 return "failed with unknown wait status ".$?;
162 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
165 die $us.($we_are_responder ? " (build host)" : "").": @_\n";
168 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
170 sub no_such_package () {
171 print STDERR "$us: package $package does not exist in suite $isuite\n";
177 return "+".rrref().":".lrref();
182 printdebug "CD $newdir\n";
183 chdir $newdir or die "chdir: $newdir: $!";
186 sub stat_exists ($) {
189 return 0 if $!==&ENOENT;
193 #---------- remote protocol support, common ----------
195 # remote push initiator/responder protocol:
196 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
198 # > file parsed-changelog
199 # [indicates that output of dpkg-parsechangelog follows]
200 # > data-block NBYTES
201 # > [NBYTES bytes of data (no newline)]
202 # [maybe some more blocks]
214 # [indicates that signed tag is wanted]
215 # < data-block NBYTES
216 # < [NBYTES bytes of data (no newline)]
217 # [maybe some more blocks]
221 # > want signed-dsc-changes
222 # < data-block NBYTES [transfer of signed dsc]
224 # < data-block NBYTES [transfer of signed changes]
232 sub i_child_report () {
233 # Sees if our child has died, and reap it if so. Returns a string
234 # describing how it died if it failed, or undef otherwise.
235 return undef unless $i_child_pid;
236 my $got = waitpid $i_child_pid, WNOHANG;
237 return undef if $got <= 0;
238 die unless $got == $i_child_pid;
239 $i_child_pid = undef;
240 return undef unless $?;
241 return "build host child ".waitstatusmsg();
246 fail "connection lost: $!" if $fh->error;
247 fail "protocol violation; $m not expected";
250 sub badproto_badread ($$) {
252 fail "connection lost: $!" if $!;
253 my $report = i_child_report();
254 fail $report if defined $report;
255 badproto $fh, "eof (reading $wh)";
258 sub protocol_expect (&$) {
259 my ($match, $fh) = @_;
262 defined && chomp or badproto_badread $fh, "protocol message";
270 badproto $fh, "\`$_'";
273 sub protocol_send_file ($$) {
274 my ($fh, $ourfn) = @_;
275 open PF, "<", $ourfn or die "$ourfn: $!";
278 my $got = read PF, $d, 65536;
279 die "$ourfn: $!" unless defined $got;
281 print $fh "data-block ".length($d)."\n" or die $!;
282 print $fh $d or die $!;
284 PF->error and die "$ourfn $!";
285 print $fh "data-end\n" or die $!;
289 sub protocol_read_bytes ($$) {
290 my ($fh, $nbytes) = @_;
291 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
293 my $got = read $fh, $d, $nbytes;
294 $got==$nbytes or badproto_badread $fh, "data block";
298 sub protocol_receive_file ($$) {
299 my ($fh, $ourfn) = @_;
300 printdebug "() $ourfn\n";
301 open PF, ">", $ourfn or die "$ourfn: $!";
303 my ($y,$l) = protocol_expect {
304 m/^data-block (.*)$/ ? (1,$1) :
305 m/^data-end$/ ? (0,) :
309 my $d = protocol_read_bytes $fh, $l;
310 print PF $d or die $!;
315 #---------- remote protocol support, responder ----------
317 sub responder_send_command ($) {
319 return unless $we_are_responder;
320 # called even without $we_are_responder
321 printdebug ">> $command\n";
322 print PO $command, "\n" or die $!;
325 sub responder_send_file ($$) {
326 my ($keyword, $ourfn) = @_;
327 return unless $we_are_responder;
328 printdebug "]] $keyword $ourfn\n";
329 responder_send_command "file $keyword";
330 protocol_send_file \*PO, $ourfn;
333 sub responder_receive_files ($@) {
334 my ($keyword, @ourfns) = @_;
335 die unless $we_are_responder;
336 printdebug "[[ $keyword @ourfns\n";
337 responder_send_command "want $keyword";
338 foreach my $fn (@ourfns) {
339 protocol_receive_file \*PI, $fn;
342 protocol_expect { m/^files-end$/ } \*PI;
345 #---------- remote protocol support, initiator ----------
347 sub initiator_expect (&) {
349 protocol_expect { &$match } \*RO;
352 #---------- end remote code ----------
355 if ($we_are_responder) {
357 responder_send_command "progress ".length($m) or die $!;
358 print PO $m or die $!;
368 $ua = LWP::UserAgent->new();
372 progress "downloading $what...";
373 my $r = $ua->get(@_) or die $!;
374 return undef if $r->code == 404;
375 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
376 return $r->decoded_content(charset => 'none');
379 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
386 if (m{[^-=_./0-9a-z]}i) {
393 return join ' ', @out;
398 my $intro = shift @_;
399 print $fh $intro," " or die $!;
400 print $fh shellquote @_ or die $!;
401 print $fh "\n" or die $!;
405 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
407 fail "failed to fork/exec: $!";
409 fail "subprocess ".waitstatusmsg();
411 fail "subprocess produced invalid output";
416 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
418 failedcmd @_ if system @_;
421 sub act_local () { return $dryrun_level <= 1; }
422 sub act_scary () { return !$dryrun_level; }
425 if (!$dryrun_level) {
426 progress "dgit ok: @_";
428 progress "would be ok: @_ (but dry run only)";
432 sub cmdoutput_errok {
433 die Dumper(\@_)." ?" if grep { !defined } @_;
434 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
435 open P, "-|", @_ or die $!;
438 { local $/ = undef; $d = <P>; }
440 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
443 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
448 my $d = cmdoutput_errok @_;
449 defined $d or failedcmd @_;
454 printcmd(\*STDERR,$debugprefix."#",@_);
457 sub runcmd_ordryrun {
465 sub runcmd_ordryrun_local {
474 my ($first_shell, @cmd) = @_;
475 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
478 our $helpmsg = <<END;
480 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
481 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
482 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
483 dgit [dgit-opts] push [dgit-opts] [suite]
484 dgit [dgit-opts] rpush build-host:build-dir ...
485 important dgit options:
486 -k<keyid> sign tag and package with <keyid> instead of default
487 --dry-run -n do not change anything, but go through the motions
488 --damp-run -L like --dry-run but make local changes, without signing
489 --new -N allow introducing a new package
490 --debug -D increase debug level
491 -c<name>=<value> set git config option (used directly by dgit too)
494 our $later_warning_msg = <<END;
495 Perhaps the upload is stuck in incoming. Using the version from git.
499 print STDERR "$us: @_\n", $helpmsg or die $!;
504 @ARGV or badusage "too few arguments";
505 return scalar shift @ARGV;
509 print $helpmsg or die $!;
513 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
515 our %defcfg = ('dgit.default.distro' => 'debian',
516 'dgit.default.username' => '',
517 'dgit.default.archive-query-default-component' => 'main',
518 'dgit.default.ssh' => 'ssh',
519 'dgit.default.archive-query' => 'madison:',
520 'dgit.default.sshpsql-dbname' => 'service=projectb',
521 'dgit-distro.debian.archive-query' => 'sshpsql:',
522 'dgit-distro.debian.git-host' => 'git.debian.org',
523 'dgit-distro.debian.git-proto' => 'git+ssh://',
524 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
525 'dgit-distro.debian.git-check' => 'ssh-cmd',
526 'dgit-distro.debian.git-create' => 'ssh-cmd',
527 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
528 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
529 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
530 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
531 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
532 'dgit-distro.ubuntu.git-check' => 'false',
533 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
534 'dgit-distro.test-dummy.ssh' => "$td/ssh",
535 'dgit-distro.test-dummy.username' => "alice",
536 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
537 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
538 'dgit-distro.test-dummy.git-url' => "$td/git",
539 'dgit-distro.test-dummy.git-host' => "git",
540 'dgit-distro.test-dummy.git-path' => "$td/git",
541 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
542 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
543 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
548 return undef if $c =~ /RETURN-UNDEF/;
549 my @cmd = (@git, qw(config --), $c);
552 local ($debug) = $debug-1;
553 $v = cmdoutput_errok @cmd;
560 my $dv = $defcfg{$c};
561 return $dv if defined $dv;
563 badcfg "need value for one of: @_\n".
564 "$us: distro or suite appears not to be (properly) supported";
567 sub access_basedistro () {
568 if (defined $idistro) {
571 return cfg("dgit-suite.$isuite.distro",
572 "dgit.default.distro");
576 sub access_quirk () {
577 # returns (quirk name, distro to use instead, quirk-specific info)
578 my $basedistro = access_basedistro();
579 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
581 if (defined $backports_quirk) {
582 my $re = $backports_quirk;
583 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
585 $re =~ s/\%/([-0-9a-z_]+)/
586 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
587 if ($isuite =~ m/^$re$/) {
588 return ('backports',"$basedistro-backports",$1);
591 return ('none',$basedistro);
594 sub access_distro () {
595 return (access_quirk())[1];
600 my $basedistro = access_basedistro();
601 my $distro = $idistro || access_distro();
602 my $value = cfg(map {
603 ("dgit-distro.$distro.$_",
604 "dgit-distro.$basedistro.$_",
610 sub string_to_ssh ($) {
612 if ($spec =~ m/\s/) {
613 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
619 sub access_cfg_ssh () {
620 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
621 if (!defined $gitssh) {
624 return string_to_ssh $gitssh;
628 sub access_someuserhost ($) {
630 my $user = access_cfg("$some-user",'username');
631 my $host = access_cfg("$some-host");
632 return length($user) ? "$user\@$host" : $host;
635 sub access_gituserhost () {
636 return access_someuserhost('git');
639 sub access_giturl (;$) {
641 my $url = access_cfg('git-url','RETURN-UNDEF');
643 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
644 return undef unless defined $proto;
647 access_gituserhost().
648 access_cfg('git-path');
650 return "$url/$package.git";
653 sub parsecontrolfh ($$;$) {
654 my ($fh, $desc, $allowsigned) = @_;
655 our $dpkgcontrolhash_noissigned;
658 my %opts = ('name' => $desc);
659 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
660 $c = Dpkg::Control::Hash->new(%opts);
661 $c->parse($fh,$desc) or die "parsing of $desc failed";
662 last if $allowsigned;
663 last if $dpkgcontrolhash_noissigned;
664 my $issigned= $c->get_option('is_pgp_signed');
665 if (!defined $issigned) {
666 $dpkgcontrolhash_noissigned= 1;
667 seek $fh, 0,0 or die "seek $desc: $!";
668 } elsif ($issigned) {
669 fail "control file $desc is (already) PGP-signed. ".
670 " Note that dgit push needs to modify the .dsc and then".
671 " do the signature itself";
680 my ($file, $desc) = @_;
681 my $fh = new IO::Handle;
682 open $fh, '<', $file or die "$file: $!";
683 my $c = parsecontrolfh($fh,$desc);
684 $fh->error and die $!;
690 my ($dctrl,$field) = @_;
691 my $v = $dctrl->{$field};
692 return $v if defined $v;
693 fail "missing field $field in ".$v->get_option('name');
697 my $c = Dpkg::Control::Hash->new();
698 my $p = new IO::Handle;
699 my @cmd = (qw(dpkg-parsechangelog), @_);
700 open $p, '-|', @cmd or die $!;
702 $?=0; $!=0; close $p or failedcmd @cmd;
706 sub git_get_ref ($) {
708 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
710 $?==256 or fail "git show-ref failed (status $?)";
711 printdebug "ref $refname= [show-ref exited 1]\n";
714 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
715 printdebug "ref $refname=$1\n";
718 printdebug "ref $refname= [no match]\n";
725 defined $d or fail "getcwd failed: $!";
731 sub archive_query ($) {
733 my $query = access_cfg('archive-query','RETURN-UNDEF');
734 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
737 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
740 sub pool_dsc_subpath ($$) {
741 my ($vsn,$component) = @_; # $package is implict arg
742 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
743 return "/pool/$component/$prefix/$package/".dscfn($vsn);
746 sub archive_query_madison {
747 return map { [ @$_[0..1] ] } madison_get_parse(@_);
750 sub madison_get_parse {
751 my ($proto,$data) = @_;
752 die unless $proto eq 'madison';
754 $data= access_cfg('madison-distro','RETURN-UNDEF');
755 $data //= access_basedistro();
757 $rmad{$proto,$data,$package} ||= cmdoutput
758 qw(rmadison -asource),"-s$isuite","-u$data",$package;
759 my $rmad = $rmad{$proto,$data,$package};
762 foreach my $l (split /\n/, $rmad) {
763 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
764 \s*( [^ \t|]+ )\s* \|
765 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
766 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
767 $1 eq $package or die "$rmad $package ?";
774 $component = access_cfg('archive-query-default-component');
776 $5 eq 'source' or die "$rmad ?";
777 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
779 return sort { -version_compare($a->[0],$b->[0]); } @out;
782 sub canonicalise_suite_madison {
783 # madison canonicalises for us
784 my @r = madison_get_parse(@_);
786 "unable to canonicalise suite using package $package".
787 " which does not appear to exist in suite $isuite;".
788 " --existing-package may help";
793 my ($data,$sql) = @_;
795 $data= access_someuserhost('sshpsql').':'.
796 access_cfg('sshpsql-dbname');
798 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
799 my ($userhost,$dbname) = ($`,$'); #';
801 my @cmd = (access_cfg_ssh, $userhost,
802 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
803 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
804 open P, "-|", @cmd or die $!;
807 printdebug("$debugprefix>|$_|\n");
810 $!=0; $?=0; close P or failedcmd @cmd;
812 my $nrows = pop @rows;
813 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
814 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
815 @rows = map { [ split /\|/, $_ ] } @rows;
816 my $ncols = scalar @{ shift @rows };
817 die if grep { scalar @$_ != $ncols } @rows;
821 sub sql_injection_check {
822 foreach (@_) { die "$_ $& ?" if m/[']/; }
825 sub archive_query_sshpsql ($$) {
826 my ($proto,$data) = @_;
827 sql_injection_check $isuite, $package;
828 my @rows = sshpsql($data, <<END);
829 SELECT source.version, component.name, files.filename, files.sha256sum
831 JOIN src_associations ON source.id = src_associations.source
832 JOIN suite ON suite.id = src_associations.suite
833 JOIN dsc_files ON dsc_files.source = source.id
834 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
835 JOIN component ON component.id = files_archive_map.component_id
836 JOIN files ON files.id = dsc_files.file
837 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
838 AND source.source='$package'
839 AND files.filename LIKE '%.dsc';
841 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
842 my $digester = Digest::SHA->new(256);
844 my ($vsn,$component,$filename,$sha256sum) = @$_;
845 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
850 sub canonicalise_suite_sshpsql ($$) {
851 my ($proto,$data) = @_;
852 sql_injection_check $isuite;
853 my @rows = sshpsql($data, <<END);
854 SELECT suite.codename
855 FROM suite where suite_name='$isuite' or codename='$isuite';
857 @rows = map { $_->[0] } @rows;
858 fail "unknown suite $isuite" unless @rows;
859 die "ambiguous $isuite: @rows ?" if @rows>1;
863 sub canonicalise_suite_dummycat ($$) {
864 my ($proto,$data) = @_;
865 my $dpath = "$data/suite.$isuite";
866 if (!open C, "<", $dpath) {
867 $!==ENOENT or die "$dpath: $!";
868 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
872 chomp or die "$dpath: $!";
874 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
878 sub archive_query_dummycat ($$) {
879 my ($proto,$data) = @_;
880 canonicalise_suite();
881 my $dpath = "$data/package.$csuite.$package";
882 if (!open C, "<", $dpath) {
883 $!==ENOENT or die "$dpath: $!";
884 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
892 printdebug "dummycat query $csuite $package $dpath | $_\n";
893 my @row = split /\s+/, $_;
894 @row==2 or die "$dpath: $_ ?";
897 C->error and die "$dpath: $!";
899 return sort { -version_compare($a->[0],$b->[0]); } @rows;
902 sub canonicalise_suite () {
903 return if defined $csuite;
904 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
905 $csuite = archive_query('canonicalise_suite');
906 if ($isuite ne $csuite) {
907 progress "canonical suite name for $isuite is $csuite";
911 sub get_archive_dsc () {
912 canonicalise_suite();
913 my @vsns = archive_query('archive_query');
914 foreach my $vinfo (@vsns) {
915 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
916 $dscurl = access_cfg('mirror').$subpath;
917 $dscdata = url_get($dscurl);
919 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
924 $digester->add($dscdata);
925 my $got = $digester->hexdigest();
927 fail "$dscurl has hash $got but".
928 " archive told us to expect $digest";
930 my $dscfh = new IO::File \$dscdata, '<' or die $!;
931 printdebug Dumper($dscdata) if $debug>1;
932 $dsc = parsecontrolfh($dscfh,$dscurl,1);
933 printdebug Dumper($dsc) if $debug>1;
934 my $fmt = getfield $dsc, 'Format';
935 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
936 $dsc_checked = !!$digester;
942 sub check_for_git () {
944 my $how = access_cfg('git-check');
945 if ($how eq 'ssh-cmd') {
947 (access_cfg_ssh, access_gituserhost(),
948 " set -e; cd ".access_cfg('git-path').";".
949 " if test -d $package.git; then echo 1; else echo 0; fi");
950 my $r= cmdoutput @cmd;
951 failedcmd @cmd unless $r =~ m/^[01]$/;
953 } elsif ($how eq 'true') {
955 } elsif ($how eq 'false') {
958 badcfg "unknown git-check \`$how'";
962 sub create_remote_git_repo () {
963 my $how = access_cfg('git-create');
964 if ($how eq 'ssh-cmd') {
966 (access_cfg_ssh, access_gituserhost(),
967 "set -e; cd ".access_cfg('git-path').";".
968 " cp -a _template $package.git");
969 } elsif ($how eq 'true') {
972 badcfg "unknown git-create \`$how'";
976 our ($dsc_hash,$lastpush_hash);
978 our $ud = '.git/dgit/unpack';
986 sub mktree_in_ud_here () {
987 runcmd qw(git init -q);
988 rmtree('.git/objects');
989 symlink '../../../../objects','.git/objects' or die $!;
992 sub mktree_in_ud_from_only_subdir () {
993 # changes into the subdir
996 $dirs[0] =~ m#^([^/]+)/\.$# or die;
999 fail "source package contains .git directory" if stat_exists '.git';
1000 mktree_in_ud_here();
1001 my $format=get_source_format();
1002 if (madformat($format)) {
1005 runcmd @git, qw(add -Af);
1006 my $tree = cmdoutput @git, qw(write-tree);
1007 $tree =~ m/^\w+$/ or die "$tree ?";
1008 return ($tree,$dir);
1011 sub dsc_files_info () {
1012 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1013 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1014 ['Files', 'Digest::MD5', 'new()']) {
1015 my ($fname, $module, $method) = @$csumi;
1016 my $field = $dsc->{$fname};
1017 next unless defined $field;
1018 eval "use $module; 1;" or die $@;
1020 foreach (split /\n/, $field) {
1022 m/^(\w+) (\d+) (\S+)$/ or
1023 fail "could not parse .dsc $fname line \`$_'";
1024 my $digester = eval "$module"."->$method;" or die $@;
1029 Digester => $digester,
1034 fail "missing any supported Checksums-* or Files field in ".
1035 $dsc->get_option('name');
1039 map { $_->{Filename} } dsc_files_info();
1042 sub is_orig_file ($;$) {
1045 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1046 defined $base or return 1;
1050 sub make_commit ($) {
1052 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1055 sub clogp_authline ($) {
1057 my $author = getfield $clogp, 'Maintainer';
1058 $author =~ s#,.*##ms;
1059 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1060 my $authline = "$author $date";
1061 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1062 fail "unexpected commit author line format \`$authline'".
1063 " (was generated from changelog Maintainer field)";
1067 sub generate_commit_from_dsc () {
1071 foreach my $fi (dsc_files_info()) {
1072 my $f = $fi->{Filename};
1073 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1075 link "../../../$f", $f
1079 complete_file_from_dsc('.', $fi);
1081 if (is_orig_file($f)) {
1082 link $f, "../../../../$f"
1088 my $dscfn = "$package.dsc";
1090 open D, ">", $dscfn or die "$dscfn: $!";
1091 print D $dscdata or die "$dscfn: $!";
1092 close D or die "$dscfn: $!";
1093 my @cmd = qw(dpkg-source);
1094 push @cmd, '--no-check' if $dsc_checked;
1095 push @cmd, qw(-x --), $dscfn;
1098 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1099 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1100 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1101 my $authline = clogp_authline $clogp;
1102 my $changes = getfield $clogp, 'Changes';
1103 open C, ">../commit.tmp" or die $!;
1104 print C <<END or die $!;
1111 # imported from the archive
1114 my $outputhash = make_commit qw(../commit.tmp);
1115 my $cversion = getfield $clogp, 'Version';
1116 progress "synthesised git commit from .dsc $cversion";
1117 if ($lastpush_hash) {
1118 runcmd @git, qw(reset --hard), $lastpush_hash;
1119 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1120 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1121 my $oversion = getfield $oldclogp, 'Version';
1123 version_compare($oversion, $cversion);
1125 # git upload/ is earlier vsn than archive, use archive
1126 open C, ">../commit2.tmp" or die $!;
1127 print C <<END or die $!;
1129 parent $lastpush_hash
1134 Record $package ($cversion) in archive suite $csuite
1136 $outputhash = make_commit qw(../commit2.tmp);
1137 } elsif ($vcmp > 0) {
1138 print STDERR <<END or die $!;
1140 Version actually in archive: $cversion (older)
1141 Last allegedly pushed/uploaded: $oversion (newer or same)
1144 $outputhash = $lastpush_hash;
1146 $outputhash = $lastpush_hash;
1149 changedir '../../../..';
1150 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1151 'DGIT_ARCHIVE', $outputhash;
1152 cmdoutput @git, qw(log -n2), $outputhash;
1153 # ... gives git a chance to complain if our commit is malformed
1158 sub complete_file_from_dsc ($$) {
1159 our ($dstdir, $fi) = @_;
1160 # Ensures that we have, in $dir, the file $fi, with the correct
1161 # contents. (Downloading it from alongside $dscurl if necessary.)
1163 my $f = $fi->{Filename};
1164 my $tf = "$dstdir/$f";
1167 if (stat_exists $tf) {
1168 progress "using existing $f";
1171 $furl =~ s{/[^/]+$}{};
1173 die "$f ?" unless $f =~ m/^${package}_/;
1174 die "$f ?" if $f =~ m#/#;
1175 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1176 next if !act_local();
1180 open F, "<", "$tf" or die "$tf: $!";
1181 $fi->{Digester}->reset();
1182 $fi->{Digester}->addfile(*F);
1183 F->error and die $!;
1184 my $got = $fi->{Digester}->hexdigest();
1185 $got eq $fi->{Hash} or
1186 fail "file $f has hash $got but .dsc".
1187 " demands hash $fi->{Hash} ".
1188 ($downloaded ? "(got wrong file from archive!)"
1189 : "(perhaps you should delete this file?)");
1192 sub ensure_we_have_orig () {
1193 foreach my $fi (dsc_files_info()) {
1194 my $f = $fi->{Filename};
1195 next unless is_orig_file($f);
1196 complete_file_from_dsc('..', $fi);
1201 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1204 sub is_fast_fwd ($$) {
1205 my ($ancestor,$child) = @_;
1206 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1207 my $mb = cmdoutput_errok @cmd;
1209 return rev_parse($mb) eq rev_parse($ancestor);
1211 $?==256 or failedcmd @cmd;
1216 sub git_fetch_us () {
1217 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1220 sub fetch_from_archive () {
1221 # ensures that lrref() is what is actually in the archive,
1222 # one way or another
1226 foreach my $field (@ourdscfield) {
1227 $dsc_hash = $dsc->{$field};
1228 last if defined $dsc_hash;
1230 if (defined $dsc_hash) {
1231 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1233 progress "last upload to archive specified git hash";
1235 progress "last upload to archive has NO git hash";
1238 progress "no version available from the archive";
1241 $lastpush_hash = git_get_ref(lrref());
1242 printdebug "previous reference hash=$lastpush_hash\n";
1244 if (defined $dsc_hash) {
1245 fail "missing remote git history even though dsc has hash -".
1246 " could not find ref ".lrref().
1247 " (should have been fetched from ".access_giturl()."#".rrref().")"
1248 unless $lastpush_hash;
1250 ensure_we_have_orig();
1251 if ($dsc_hash eq $lastpush_hash) {
1252 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1253 print STDERR <<END or die $!;
1255 Git commit in archive is behind the last version allegedly pushed/uploaded.
1256 Commit referred to by archive: $dsc_hash
1257 Last allegedly pushed/uploaded: $lastpush_hash
1260 $hash = $lastpush_hash;
1262 fail "archive's .dsc refers to ".$dsc_hash.
1263 " but this is an ancestor of ".$lastpush_hash;
1266 $hash = generate_commit_from_dsc();
1267 } elsif ($lastpush_hash) {
1268 # only in git, not in the archive yet
1269 $hash = $lastpush_hash;
1270 print STDERR <<END or die $!;
1272 Package not found in the archive, but has allegedly been pushed using dgit.
1276 printdebug "nothing found!\n";
1277 if (defined $skew_warning_vsn) {
1278 print STDERR <<END or die $!;
1280 Warning: relevant archive skew detected.
1281 Archive allegedly contains $skew_warning_vsn
1282 But we were not able to obtain any version from the archive or git.
1288 printdebug "current hash=$hash\n";
1289 if ($lastpush_hash) {
1290 fail "not fast forward on last upload branch!".
1291 " (archive's version left in DGIT_ARCHIVE)"
1292 unless is_fast_fwd($lastpush_hash, $hash);
1294 if (defined $skew_warning_vsn) {
1296 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1297 my $clogf = ".git/dgit/changelog.tmp";
1298 runcmd shell_cmd "exec >$clogf",
1299 @git, qw(cat-file blob), "$hash:debian/changelog";
1300 my $gotclogp = parsechangelog("-l$clogf");
1301 my $got_vsn = getfield $gotclogp, 'Version';
1302 printdebug "SKEW CHECK GOT $got_vsn\n";
1303 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1304 print STDERR <<END or die $!;
1306 Warning: archive skew detected. Using the available version:
1307 Archive allegedly contains $skew_warning_vsn
1308 We were able to obtain only $got_vsn
1313 if ($lastpush_hash ne $hash) {
1314 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1318 dryrun_report @upd_cmd;
1326 canonicalise_suite();
1327 badusage "dry run makes no sense with clone" unless act_local();
1328 mkdir $dstdir or die "$dstdir $!";
1330 runcmd @git, qw(init -q);
1331 my $giturl = access_giturl(1);
1332 if (defined $giturl) {
1333 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1334 open H, "> .git/HEAD" or die $!;
1335 print H "ref: ".lref()."\n" or die $!;
1337 runcmd @git, qw(remote add), 'origin', $giturl;
1339 if (check_for_git()) {
1340 progress "fetching existing git history";
1342 runcmd_ordryrun_local @git, qw(fetch origin);
1344 progress "starting new git history";
1346 fetch_from_archive() or no_such_package;
1347 my $vcsgiturl = $dsc->{'Vcs-Git'};
1348 if (length $vcsgiturl) {
1349 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1351 runcmd @git, qw(reset --hard), lrref();
1352 printdone "ready for work in $dstdir";
1356 if (check_for_git()) {
1359 fetch_from_archive() or no_such_package();
1360 printdone "fetched into ".lrref();
1365 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1367 printdone "fetched to ".lrref()." and merged into HEAD";
1370 sub check_not_dirty () {
1371 return if $ignoredirty;
1372 my @cmd = (@git, qw(diff --quiet HEAD));
1373 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1374 $!=0; $?=0; system @cmd;
1375 return if !$! && !$?;
1376 if (!$! && $?==256) {
1377 fail "working tree is dirty (does not match HEAD)";
1383 sub commit_admin ($) {
1386 runcmd_ordryrun_local @git, qw(commit -m), $m;
1389 sub commit_quilty_patch () {
1390 my $output = cmdoutput @git, qw(status --porcelain);
1392 foreach my $l (split /\n/, $output) {
1393 next unless $l =~ m/\S/;
1394 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1398 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1400 progress "nothing quilty to commit, ok.";
1403 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1404 commit_admin "Commit Debian 3.0 (quilt) metadata";
1407 sub get_source_format () {
1408 if (!open F, "debian/source/format") {
1409 die $! unless $!==&ENOENT;
1413 F->error and die $!;
1420 return 0 unless $format eq '3.0 (quilt)';
1422 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1425 progress "Format \`$format', checking/updating patch stack";
1429 sub push_parse_changelog ($) {
1432 my $clogp = Dpkg::Control::Hash->new();
1433 $clogp->load($clogpfn) or die;
1435 $package = getfield $clogp, 'Source';
1436 my $cversion = getfield $clogp, 'Version';
1437 my $tag = debiantag($cversion);
1438 runcmd @git, qw(check-ref-format), $tag;
1440 my $dscfn = dscfn($cversion);
1442 return ($clogp, $cversion, $tag, $dscfn);
1445 sub push_parse_dsc ($$$) {
1446 my ($dscfn,$dscfnwhat, $cversion) = @_;
1447 $dsc = parsecontrol($dscfn,$dscfnwhat);
1448 my $dversion = getfield $dsc, 'Version';
1449 my $dscpackage = getfield $dsc, 'Source';
1450 ($dscpackage eq $package && $dversion eq $cversion) or
1451 fail "$dscfn is for $dscpackage $dversion".
1452 " but debian/changelog is for $package $cversion";
1455 sub push_mktag ($$$$$$$) {
1456 my ($head,$clogp,$tag,
1458 $changesfile,$changesfilewhat,
1461 $dsc->{$ourdscfield[0]} = $head;
1462 $dsc->save("$dscfn.tmp") or die $!;
1464 my $changes = parsecontrol($changesfile,$changesfilewhat);
1465 foreach my $field (qw(Source Distribution Version)) {
1466 $changes->{$field} eq $clogp->{$field} or
1467 fail "changes field $field \`$changes->{$field}'".
1468 " does not match changelog \`$clogp->{$field}'";
1471 my $cversion = getfield $clogp, 'Version';
1472 my $clogsuite = getfield $clogp, 'Distribution';
1474 # We make the git tag by hand because (a) that makes it easier
1475 # to control the "tagger" (b) we can do remote signing
1476 my $authline = clogp_authline $clogp;
1477 open TO, '>', $tfn->('.tmp') or die $!;
1478 print TO <<END or die $!;
1484 $package release $cversion for $clogsuite ($csuite) [dgit]
1488 my $tagobjfn = $tfn->('.tmp');
1490 if (!defined $keyid) {
1491 $keyid = access_cfg('keyid','RETURN-UNDEF');
1493 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1494 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1495 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1496 push @sign_cmd, $tfn->('.tmp');
1497 runcmd_ordryrun @sign_cmd;
1499 $tagobjfn = $tfn->('.signed.tmp');
1500 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1501 $tfn->('.tmp'), $tfn->('.tmp.asc');
1508 sub sign_changes ($) {
1509 my ($changesfile) = @_;
1511 my @debsign_cmd = @debsign;
1512 push @debsign_cmd, "-k$keyid" if defined $keyid;
1513 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1514 push @debsign_cmd, $changesfile;
1515 runcmd_ordryrun @debsign_cmd;
1520 printdebug "actually entering push\n";
1523 access_giturl(); # check that success is vaguely likely
1525 my $clogpfn = ".git/dgit/changelog.822.tmp";
1526 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1528 responder_send_file('parsed-changelog', $clogpfn);
1530 my ($clogp, $cversion, $tag, $dscfn) =
1531 push_parse_changelog("$clogpfn");
1533 my $dscpath = "$buildproductsdir/$dscfn";
1534 stat_exists $dscpath or
1535 fail "looked for .dsc $dscfn, but $!;".
1536 " maybe you forgot to build";
1538 responder_send_file('dsc', $dscpath);
1540 push_parse_dsc($dscpath, $dscfn, $cversion);
1542 my $format = getfield $dsc, 'Format';
1543 printdebug "format $format\n";
1544 if (madformat($format)) {
1545 commit_quilty_patch();
1549 progress "checking that $dscfn corresponds to HEAD";
1550 runcmd qw(dpkg-source -x --),
1551 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1552 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1553 changedir '../../../..';
1554 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1555 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1556 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1558 my $r = system @diffcmd;
1561 fail "$dscfn specifies a different tree to your HEAD commit;".
1562 " perhaps you forgot to build".
1563 ($diffopt eq '--exit-code' ? "" :
1564 " (run with -D to see full diff output)");
1570 #do fast forward check and maybe fake merge
1571 # if (!is_fast_fwd(mainbranch
1572 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1573 # map { lref($_).":".rref($_) }
1575 my $head = rev_parse('HEAD');
1576 if (!$changesfile) {
1577 my $multi = "$buildproductsdir/".
1578 "${package}_".(stripepoch $cversion)."_multi.changes";
1579 if (stat_exists "$multi") {
1580 $changesfile = $multi;
1582 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1583 my @cs = glob "$buildproductsdir/$pat";
1584 fail "failed to find unique changes file".
1585 " (looked for $pat in $buildproductsdir, or $multi);".
1586 " perhaps you need to use dgit -C"
1588 ($changesfile) = @cs;
1591 $changesfile = "$buildproductsdir/$changesfile";
1594 responder_send_file('changes',$changesfile);
1595 responder_send_command("param head $head");
1596 responder_send_command("param csuite $csuite");
1598 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1601 if ($we_are_responder) {
1602 $tagobjfn = $tfn->('.signed.tmp');
1603 responder_receive_files('signed-tag', $tagobjfn);
1606 push_mktag($head,$clogp,$tag,
1608 $changesfile,$changesfile,
1612 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1613 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1614 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1615 runcmd_ordryrun @git, qw(tag -v --), $tag;
1617 if (!check_for_git()) {
1618 create_remote_git_repo();
1620 runcmd_ordryrun @git, qw(push),access_giturl(),
1621 "HEAD:".rrref(), "refs/tags/$tag";
1622 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1624 if ($we_are_responder) {
1625 my $dryrunsuffix = act_local() ? "" : ".tmp";
1626 responder_receive_files('signed-dsc-changes',
1627 "$dscpath$dryrunsuffix",
1628 "$changesfile$dryrunsuffix");
1631 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1633 progress "[new .dsc left in $dscpath.tmp]";
1635 sign_changes $changesfile;
1638 my $host = access_cfg('upload-host','RETURN-UNDEF');
1639 my @hostarg = defined($host) ? ($host,) : ();
1640 runcmd_ordryrun @dput, @hostarg, $changesfile;
1641 printdone "pushed and uploaded $cversion";
1643 responder_send_command("complete");
1649 badusage "-p is not allowed with clone; specify as argument instead"
1650 if defined $package;
1653 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1654 ($package,$isuite) = @ARGV;
1655 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1656 ($package,$dstdir) = @ARGV;
1657 } elsif (@ARGV==3) {
1658 ($package,$isuite,$dstdir) = @ARGV;
1660 badusage "incorrect arguments to dgit clone";
1662 $dstdir ||= "$package";
1664 if (stat_exists $dstdir) {
1665 fail "$dstdir already exists";
1669 if ($rmonerror && !$dryrun_level) {
1670 $cwd_remove= getcwd();
1672 return unless defined $cwd_remove;
1673 if (!chdir "$cwd_remove") {
1674 return if $!==&ENOENT;
1675 die "chdir $cwd_remove: $!";
1677 rmtree($dstdir) or die "remove $dstdir: $!\n";
1682 $cwd_remove = undef;
1685 sub branchsuite () {
1686 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1687 if ($branch =~ m#$lbranch_re#o) {
1694 sub fetchpullargs () {
1695 if (!defined $package) {
1696 my $sourcep = parsecontrol('debian/control','debian/control');
1697 $package = getfield $sourcep, 'Source';
1700 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1702 my $clogp = parsechangelog();
1703 $isuite = getfield $clogp, 'Distribution';
1705 canonicalise_suite();
1706 progress "fetching from suite $csuite";
1707 } elsif (@ARGV==1) {
1709 canonicalise_suite();
1711 badusage "incorrect arguments to dgit fetch or dgit pull";
1729 badusage "-p is not allowed with dgit push" if defined $package;
1731 my $clogp = parsechangelog();
1732 $package = getfield $clogp, 'Source';
1735 } elsif (@ARGV==1) {
1736 ($specsuite) = (@ARGV);
1738 badusage "incorrect arguments to dgit push";
1740 $isuite = getfield $clogp, 'Distribution';
1742 local ($package) = $existing_package; # this is a hack
1743 canonicalise_suite();
1745 if (defined $specsuite && $specsuite ne $isuite) {
1746 canonicalise_suite();
1747 $csuite eq $specsuite or
1748 fail "dgit push: changelog specifies $isuite ($csuite)".
1749 " but command line specifies $specsuite";
1751 if (check_for_git()) {
1754 if (fetch_from_archive()) {
1755 is_fast_fwd(lrref(), 'HEAD') or
1756 fail "dgit push: HEAD is not a descendant".
1757 " of the archive's version.\n".
1758 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1761 fail "package appears to be new in this suite;".
1762 " if this is intentional, use --new";
1767 #---------- remote commands' implementation ----------
1769 sub cmd_remote_push_build_host {
1770 my ($nrargs) = shift @ARGV;
1771 my (@rargs) = @ARGV[0..$nrargs-1];
1772 @ARGV = @ARGV[$nrargs..$#ARGV];
1774 my ($dir,$vsnwant) = @rargs;
1775 # vsnwant is a comma-separated list; we report which we have
1776 # chosen in our ready response (so other end can tell if they
1779 $we_are_responder = 1;
1781 open PI, "<&STDIN" or die $!;
1782 open STDIN, "/dev/null" or die $!;
1783 open PO, ">&STDOUT" or die $!;
1785 open STDOUT, ">&STDERR" or die $!;
1789 fail "build host has dgit rpush protocol version".
1790 " $rpushprotovsn but invocation host has $vsnwant"
1791 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1793 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1799 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1800 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1801 # a good error message)
1807 my $report = i_child_report();
1808 if (defined $report) {
1809 printdebug "($report)\n";
1810 } elsif ($i_child_pid) {
1811 printdebug "(killing build host child $i_child_pid)\n";
1812 kill 15, $i_child_pid;
1814 if (defined $i_tmp && !defined $initiator_tempdir) {
1816 eval { rmtree $i_tmp; };
1820 END { i_cleanup(); }
1823 my ($base,$selector,@args) = @_;
1824 $selector =~ s/\-/_/g;
1825 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1831 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1838 my @rargs = ($dir,$rpushprotovsn);
1841 push @rdgit, @ropts;
1842 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1844 my @cmd = (@ssh, $host, shellquote @rdgit);
1845 printcmd \*DEBUG,$debugprefix."+",@cmd;
1847 if (defined $initiator_tempdir) {
1848 rmtree $initiator_tempdir;
1849 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1850 $i_tmp = $initiator_tempdir;
1854 $i_child_pid = open2(\*RO, \*RI, @cmd);
1856 initiator_expect { m/^dgit-remote-push-ready/ };
1858 my ($icmd,$iargs) = initiator_expect {
1859 m/^(\S+)(?: (.*))?$/;
1862 i_method "i_resp", $icmd, $iargs;
1866 sub i_resp_progress ($) {
1868 my $msg = protocol_read_bytes \*RO, $rhs;
1872 sub i_resp_complete {
1873 my $pid = $i_child_pid;
1874 $i_child_pid = undef; # prevents killing some other process with same pid
1875 printdebug "waiting for build host child $pid...\n";
1876 my $got = waitpid $pid, 0;
1877 die $! unless $got == $pid;
1878 die "build host child failed $?" if $?;
1881 printdebug "all done\n";
1885 sub i_resp_file ($) {
1887 my $localname = i_method "i_localname", $keyword;
1888 my $localpath = "$i_tmp/$localname";
1889 stat_exists $localpath and
1890 badproto \*RO, "file $keyword ($localpath) twice";
1891 protocol_receive_file \*RO, $localpath;
1892 i_method "i_file", $keyword;
1897 sub i_resp_param ($) {
1898 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1904 sub i_resp_want ($) {
1906 die "$keyword ?" if $i_wanted{$keyword}++;
1907 my @localpaths = i_method "i_want", $keyword;
1908 printdebug "[[ $keyword @localpaths\n";
1909 foreach my $localpath (@localpaths) {
1910 protocol_send_file \*RI, $localpath;
1912 print RI "files-end\n" or die $!;
1915 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1917 sub i_localname_parsed_changelog {
1918 return "remote-changelog.822";
1920 sub i_file_parsed_changelog {
1921 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1922 push_parse_changelog "$i_tmp/remote-changelog.822";
1923 die if $i_dscfn =~ m#/|^\W#;
1926 sub i_localname_dsc {
1927 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1932 sub i_localname_changes {
1933 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1934 $i_changesfn = $i_dscfn;
1935 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1936 return $i_changesfn;
1938 sub i_file_changes { }
1940 sub i_want_signed_tag {
1941 printdebug Dumper(\%i_param, $i_dscfn);
1942 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1943 && defined $i_param{'csuite'}
1944 or badproto \*RO, "premature desire for signed-tag";
1945 my $head = $i_param{'head'};
1946 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1948 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1950 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1953 push_mktag $head, $i_clogp, $i_tag,
1955 $i_changesfn, 'remote changes',
1956 sub { "tag$_[0]"; };
1961 sub i_want_signed_dsc_changes {
1962 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1963 sign_changes $i_changesfn;
1964 return ($i_dscfn, $i_changesfn);
1967 #---------- building etc. ----------
1973 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1975 sub build_maybe_quilt_fixup () {
1976 my $format=get_source_format;
1977 return unless madformat $format;
1981 # - honour any existing .pc in case it has any strangeness
1982 # - determine the git commit corresponding to the tip of
1983 # the patch stack (if there is one)
1984 # - if there is such a git commit, convert each subsequent
1985 # git commit into a quilt patch with dpkg-source --commit
1986 # - otherwise convert all the differences in the tree into
1987 # a single git commit
1991 # Our git tree doesn't necessarily contain .pc. (Some versions of
1992 # dgit would include the .pc in the git tree.) If there isn't
1993 # one, we need to generate one by unpacking the patches that we
1996 # We first look for a .pc in the git tree. If there is one, we
1997 # will use it. (This is not the normal case.)
1999 # Otherwise need to regenerate .pc so that dpkg-source --commit
2000 # can work. We do this as follows:
2001 # 1. Collect all relevant .orig from parent directory
2002 # 2. Generate a debian.tar.gz out of
2003 # debian/{patches,rules,source/format}
2004 # 3. Generate a fake .dsc containing just these fields:
2005 # Format Source Version Files
2006 # 4. Extract the fake .dsc
2007 # Now the fake .dsc has a .pc directory.
2008 # (In fact we do this in every case, because in future we will
2009 # want to search for a good base commit for generating patches.)
2011 # Then we can actually do the dpkg-source --commit
2012 # 1. Make a new working tree with the same object
2013 # store as our main tree and check out the main
2015 # 2. Copy .pc from the fake's extraction, if necessary
2016 # 3. Run dpkg-source --commit
2017 # 4. If the result has changes to debian/, then
2018 # - git-add them them
2019 # - git-add .pc if we had a .pc in-tree
2021 # 5. If we had a .pc in-tree, delete it, and git-commit
2022 # 6. Back in the main tree, fast forward to the new HEAD
2024 my $clogp = parsechangelog();
2025 my $headref = rev_parse('HEAD');
2030 my $upstreamversion=$version;
2031 $upstreamversion =~ s/-[^-]*$//;
2033 my $fakeversion="$upstreamversion-~~DGITFAKE";
2035 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2036 print $fakedsc <<END or die $!;
2039 Version: $fakeversion
2043 my $dscaddfile=sub {
2046 my $md = new Digest::MD5;
2048 my $fh = new IO::File $b, '<' or die "$b $!";
2053 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2056 foreach my $f (<../../../../*>) { #/){
2057 my $b=$f; $b =~ s{.*/}{};
2058 next unless is_orig_file $b, srcfn $upstreamversion,'';
2059 link $f, $b or die "$b $!";
2063 my @files=qw(debian/source/format debian/rules);
2064 if (stat_exists '../../../debian/patches') {
2065 push @files, 'debian/patches';
2068 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2069 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2071 $dscaddfile->($debtar);
2072 close $fakedsc or die $!;
2074 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2076 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2077 rename $fakexdir, "fake" or die "$fakexdir $!";
2079 mkdir "work" or die $!;
2081 mktree_in_ud_here();
2082 runcmd @git, qw(reset --hard), $headref;
2085 if (stat_exists ".pc") {
2087 progress "Tree already contains .pc - will use it then delete it.";
2090 rename '../fake/.pc','.pc' or die $!;
2093 my $author = getfield $clogp, 'Maintainer';
2096 my $patchname = "auto-$version-$headref-$time";
2097 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2099 my $descfn = ".git/dgit/quilt-description.tmp";
2100 open O, '>', $descfn or die "$descfn: $!";
2102 $msg =~ s/^\s+$/ ./mg;
2103 print O <<END or die $!;
2104 Description: Automatically generated patch ($clogp->{Version})
2105 Last (up to) $ncommits git changes, FYI:
2115 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2116 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2117 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2118 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2121 if (!open P, '>>', ".pc/applied-patches") {
2122 $!==&ENOENT or die $!;
2127 commit_quilty_patch();
2129 if ($mustdeletepc) {
2130 runcmd @git, qw(rm -rq .pc);
2131 commit_admin "Commit removal of .pc (quilt series tracking data)";
2134 changedir '../../../..';
2135 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2138 sub quilt_fixup_editor () {
2139 my $descfn = $ENV{$fakeeditorenv};
2140 my $editing = $ARGV[$#ARGV];
2141 open I1, '<', $descfn or die "$descfn: $!";
2142 open I2, '<', $editing or die "$editing: $!";
2143 unlink $editing or die "$editing: $!";
2144 open O, '>', $editing or die "$editing: $!";
2145 while (<I1>) { print O or die $!; } I1->error and die $!;
2148 $copying ||= m/^\-\-\- /;
2149 next unless $copying;
2152 I2->error and die $!;
2158 if ($cleanmode eq 'dpkg-source') {
2159 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2160 } elsif ($cleanmode eq 'git') {
2161 runcmd_ordryrun_local @git, qw(clean -xdf);
2162 } elsif ($cleanmode eq 'none') {
2169 badusage "clean takes no additional arguments" if @ARGV;
2174 badusage "-p is not allowed when building" if defined $package;
2177 my $clogp = parsechangelog();
2178 $isuite = getfield $clogp, 'Distribution';
2179 $package = getfield $clogp, 'Source';
2180 $version = getfield $clogp, 'Version';
2181 build_maybe_quilt_fixup();
2184 sub changesopts () {
2185 my @opts =@changesopts[1..$#changesopts];
2186 if (!defined $changes_since_version) {
2187 my @vsns = archive_query('archive_query');
2188 my @quirk = access_quirk();
2189 if ($quirk[0] eq 'backports') {
2190 local $isuite = $quirk[2];
2192 canonicalise_suite();
2193 push @vsns, archive_query('archive_query');
2196 @vsns = map { $_->[0] } @vsns;
2197 @vsns = sort { -version_compare($a, $b) } @vsns;
2198 $changes_since_version = $vsns[0];
2199 progress "changelog will contain changes since $vsns[0]";
2201 $changes_since_version = '_';
2202 progress "package seems new, not specifying -v<version>";
2205 if ($changes_since_version ne '_') {
2206 unshift @opts, "-v$changes_since_version";
2213 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2214 printdone "build successful\n";
2220 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2221 "--git-builder=@dpkgbuildpackage");
2222 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2223 canonicalise_suite();
2224 push @cmd, "--git-debian-branch=".lbranch();
2226 push @cmd, changesopts();
2227 runcmd_ordryrun_local @cmd, @ARGV;
2228 printdone "build successful\n";
2233 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2234 $dscfn = dscfn($version);
2235 if ($cleanmode eq 'dpkg-source') {
2236 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2239 my $pwd = must_getcwd();
2240 my $leafdir = basename $pwd;
2242 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2244 runcmd_ordryrun_local qw(sh -ec),
2245 'exec >$1; shift; exec "$@"','x',
2246 "../$sourcechanges",
2247 @dpkggenchanges, qw(-S), changesopts();
2251 sub cmd_build_source {
2252 badusage "build-source takes no additional arguments" if @ARGV;
2254 printdone "source built, results in $dscfn and $sourcechanges";
2260 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2262 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2263 stat_exists $sourcechanges
2264 or fail "$sourcechanges (in parent directory): $!";
2265 foreach my $cf (glob $pat) {
2266 next if $cf eq $sourcechanges;
2267 unlink $cf or fail "remove $cf: $!";
2270 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2271 my @changesfiles = glob $pat;
2272 @changesfiles = sort {
2273 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2276 fail "wrong number of different changes files (@changesfiles)"
2277 unless @changesfiles;
2278 runcmd_ordryrun_local @mergechanges, @changesfiles;
2279 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2281 stat_exists $multichanges or fail "$multichanges: $!";
2283 printdone "build successful, results in $multichanges\n" or die $!;
2286 sub cmd_quilt_fixup {
2287 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2288 my $clogp = parsechangelog();
2289 $version = getfield $clogp, 'Version';
2290 $package = getfield $clogp, 'Source';
2291 build_maybe_quilt_fixup();
2294 #---------- argument parsing and main program ----------
2297 print "dgit version $our_version\n" or die $!;
2304 if (defined $ENV{'DGIT_SSH'}) {
2305 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2306 } elsif (defined $ENV{'GIT_SSH'}) {
2307 @ssh = ($ENV{'GIT_SSH'});
2311 last unless $ARGV[0] =~ m/^-/;
2315 if (m/^--dry-run$/) {
2318 } elsif (m/^--damp-run$/) {
2321 } elsif (m/^--no-sign$/) {
2324 } elsif (m/^--help$/) {
2326 } elsif (m/^--version$/) {
2328 } elsif (m/^--new$/) {
2331 } elsif (m/^--since-version=([^_]+|_)$/) {
2333 $changes_since_version = $1;
2334 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2335 ($om = $opts_opt_map{$1}) &&
2339 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2340 !$opts_opt_cmdonly{$1} &&
2341 ($om = $opts_opt_map{$1})) {
2344 } elsif (m/^--existing-package=(.*)/s) {
2346 $existing_package = $1;
2347 } elsif (m/^--initiator-tempdir=(.*)/s) {
2348 $initiator_tempdir = $1;
2349 $initiator_tempdir =~ m#^/# or
2350 badusage "--initiator-tempdir must be used specify an".
2351 " absolute, not relative, directory."
2352 } elsif (m/^--distro=(.*)/s) {
2355 } elsif (m/^--build-products-dir=(.*)/s) {
2357 $buildproductsdir = $1;
2358 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2361 } elsif (m/^--clean=(.*)$/s) {
2362 badusage "unknown cleaning mode \`$1'";
2363 } elsif (m/^--ignore-dirty$/s) {
2366 } elsif (m/^--no-quilt-fixup$/s) {
2369 } elsif (m/^--no-rm-on-error$/s) {
2373 badusage "unknown long option \`$_'";
2380 } elsif (s/^-L/-/) {
2383 } elsif (s/^-h/-/) {
2385 } elsif (s/^-D/-/) {
2387 open DEBUG, ">&STDERR" or die $!;
2390 } elsif (s/^-N/-/) {
2393 } elsif (s/^-v([^_]+|_)$//s) {
2395 $changes_since_version = $1;
2398 push @changesopts, $_;
2400 } elsif (s/^-c(.*=.*)//s) {
2402 push @git, '-c', $1;
2403 } elsif (s/^-d(.*)//s) {
2406 } elsif (s/^-C(.*)//s) {
2409 if ($changesfile =~ s#^(.*)/##) {
2410 $buildproductsdir = $1;
2412 } elsif (s/^-k(.*)//s) {
2414 } elsif (s/^-wn//s) {
2416 $cleanmode = 'none';
2417 } elsif (s/^-wg//s) {
2420 } elsif (s/^-wd//s) {
2422 $cleanmode = 'dpkg-source';
2424 badusage "unknown short option \`$_'";
2431 if ($ENV{$fakeeditorenv}) {
2432 quilt_fixup_editor();
2436 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2437 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2438 if $dryrun_level == 1;
2440 print STDERR $helpmsg or die $!;
2443 my $cmd = shift @ARGV;
2446 my $fn = ${*::}{"cmd_$cmd"};
2447 $fn or badusage "unknown operation $cmd";