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) {
569 return cfg("dgit-distro.basedistro.distro",
570 "dgit-suite.$isuite.distro",
571 'RETURN-UNDEF') // $idistro;
573 return cfg("dgit-suite.$isuite.distro",
574 "dgit.default.distro");
578 sub access_quirk () {
579 # returns (quirk name, distro to use instead, quirk-specific info)
580 my $basedistro = access_basedistro();
581 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
583 if (defined $backports_quirk) {
584 my $re = $backports_quirk;
585 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
587 $re =~ s/\%/([-0-9a-z_]+)/
588 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
589 if ($isuite =~ m/^$re$/) {
590 return ('backports',"$basedistro-backports",$1);
593 return ('none',$basedistro);
596 sub access_distro () {
597 return (access_quirk())[1];
602 my $basedistro = access_basedistro();
603 my $distro = $idistro || access_distro();
604 my $value = cfg(map {
605 ("dgit-distro.$distro.$_",
606 "dgit-distro.$basedistro.$_",
612 sub string_to_ssh ($) {
614 if ($spec =~ m/\s/) {
615 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
621 sub access_cfg_ssh () {
622 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
623 if (!defined $gitssh) {
626 return string_to_ssh $gitssh;
630 sub access_someuserhost ($) {
632 my $user = access_cfg("$some-user",'username');
633 my $host = access_cfg("$some-host");
634 return length($user) ? "$user\@$host" : $host;
637 sub access_gituserhost () {
638 return access_someuserhost('git');
641 sub access_giturl (;$) {
643 my $url = access_cfg('git-url','RETURN-UNDEF');
645 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
646 return undef unless defined $proto;
649 access_gituserhost().
650 access_cfg('git-path');
652 return "$url/$package.git";
655 sub parsecontrolfh ($$;$) {
656 my ($fh, $desc, $allowsigned) = @_;
657 our $dpkgcontrolhash_noissigned;
660 my %opts = ('name' => $desc);
661 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
662 $c = Dpkg::Control::Hash->new(%opts);
663 $c->parse($fh,$desc) or die "parsing of $desc failed";
664 last if $allowsigned;
665 last if $dpkgcontrolhash_noissigned;
666 my $issigned= $c->get_option('is_pgp_signed');
667 if (!defined $issigned) {
668 $dpkgcontrolhash_noissigned= 1;
669 seek $fh, 0,0 or die "seek $desc: $!";
670 } elsif ($issigned) {
671 fail "control file $desc is (already) PGP-signed. ".
672 " Note that dgit push needs to modify the .dsc and then".
673 " do the signature itself";
682 my ($file, $desc) = @_;
683 my $fh = new IO::Handle;
684 open $fh, '<', $file or die "$file: $!";
685 my $c = parsecontrolfh($fh,$desc);
686 $fh->error and die $!;
692 my ($dctrl,$field) = @_;
693 my $v = $dctrl->{$field};
694 return $v if defined $v;
695 fail "missing field $field in ".$v->get_option('name');
699 my $c = Dpkg::Control::Hash->new();
700 my $p = new IO::Handle;
701 my @cmd = (qw(dpkg-parsechangelog), @_);
702 open $p, '-|', @cmd or die $!;
704 $?=0; $!=0; close $p or failedcmd @cmd;
708 sub git_get_ref ($) {
710 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
712 $?==256 or fail "git show-ref failed (status $?)";
713 printdebug "ref $refname= [show-ref exited 1]\n";
716 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
717 printdebug "ref $refname=$1\n";
720 printdebug "ref $refname= [no match]\n";
727 defined $d or fail "getcwd failed: $!";
733 sub archive_query ($) {
735 my $query = access_cfg('archive-query','RETURN-UNDEF');
736 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
739 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
742 sub pool_dsc_subpath ($$) {
743 my ($vsn,$component) = @_; # $package is implict arg
744 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
745 return "/pool/$component/$prefix/$package/".dscfn($vsn);
748 sub archive_query_madison {
749 return map { [ @$_[0..1] ] } madison_get_parse(@_);
752 sub madison_get_parse {
753 my ($proto,$data) = @_;
754 die unless $proto eq 'madison';
756 $data= access_cfg('madison-distro','RETURN-UNDEF');
757 $data //= access_basedistro();
759 $rmad{$proto,$data,$package} ||= cmdoutput
760 qw(rmadison -asource),"-s$isuite","-u$data",$package;
761 my $rmad = $rmad{$proto,$data,$package};
764 foreach my $l (split /\n/, $rmad) {
765 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
766 \s*( [^ \t|]+ )\s* \|
767 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
768 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
769 $1 eq $package or die "$rmad $package ?";
776 $component = access_cfg('archive-query-default-component');
778 $5 eq 'source' or die "$rmad ?";
779 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
781 return sort { -version_compare($a->[0],$b->[0]); } @out;
784 sub canonicalise_suite_madison {
785 # madison canonicalises for us
786 my @r = madison_get_parse(@_);
788 "unable to canonicalise suite using package $package".
789 " which does not appear to exist in suite $isuite;".
790 " --existing-package may help";
795 my ($data,$sql) = @_;
797 $data= access_someuserhost('sshpsql').':'.
798 access_cfg('sshpsql-dbname');
800 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
801 my ($userhost,$dbname) = ($`,$'); #';
803 my @cmd = (access_cfg_ssh, $userhost,
804 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
805 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
806 open P, "-|", @cmd or die $!;
809 printdebug("$debugprefix>|$_|\n");
812 $!=0; $?=0; close P or failedcmd @cmd;
814 my $nrows = pop @rows;
815 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
816 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
817 @rows = map { [ split /\|/, $_ ] } @rows;
818 my $ncols = scalar @{ shift @rows };
819 die if grep { scalar @$_ != $ncols } @rows;
823 sub sql_injection_check {
824 foreach (@_) { die "$_ $& ?" if m/[']/; }
827 sub archive_query_sshpsql ($$) {
828 my ($proto,$data) = @_;
829 sql_injection_check $isuite, $package;
830 my @rows = sshpsql($data, <<END);
831 SELECT source.version, component.name, files.filename, files.sha256sum
833 JOIN src_associations ON source.id = src_associations.source
834 JOIN suite ON suite.id = src_associations.suite
835 JOIN dsc_files ON dsc_files.source = source.id
836 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
837 JOIN component ON component.id = files_archive_map.component_id
838 JOIN files ON files.id = dsc_files.file
839 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
840 AND source.source='$package'
841 AND files.filename LIKE '%.dsc';
843 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
844 my $digester = Digest::SHA->new(256);
846 my ($vsn,$component,$filename,$sha256sum) = @$_;
847 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
852 sub canonicalise_suite_sshpsql ($$) {
853 my ($proto,$data) = @_;
854 sql_injection_check $isuite;
855 my @rows = sshpsql($data, <<END);
856 SELECT suite.codename
857 FROM suite where suite_name='$isuite' or codename='$isuite';
859 @rows = map { $_->[0] } @rows;
860 fail "unknown suite $isuite" unless @rows;
861 die "ambiguous $isuite: @rows ?" if @rows>1;
865 sub canonicalise_suite_dummycat ($$) {
866 my ($proto,$data) = @_;
867 my $dpath = "$data/suite.$isuite";
868 if (!open C, "<", $dpath) {
869 $!==ENOENT or die "$dpath: $!";
870 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
874 chomp or die "$dpath: $!";
876 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
880 sub archive_query_dummycat ($$) {
881 my ($proto,$data) = @_;
882 canonicalise_suite();
883 my $dpath = "$data/package.$csuite.$package";
884 if (!open C, "<", $dpath) {
885 $!==ENOENT or die "$dpath: $!";
886 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
894 printdebug "dummycat query $csuite $package $dpath | $_\n";
895 my @row = split /\s+/, $_;
896 @row==2 or die "$dpath: $_ ?";
899 C->error and die "$dpath: $!";
901 return sort { -version_compare($a->[0],$b->[0]); } @rows;
904 sub canonicalise_suite () {
905 return if defined $csuite;
906 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
907 $csuite = archive_query('canonicalise_suite');
908 if ($isuite ne $csuite) {
909 progress "canonical suite name for $isuite is $csuite";
913 sub get_archive_dsc () {
914 canonicalise_suite();
915 my @vsns = archive_query('archive_query');
916 foreach my $vinfo (@vsns) {
917 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
918 $dscurl = access_cfg('mirror').$subpath;
919 $dscdata = url_get($dscurl);
921 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
926 $digester->add($dscdata);
927 my $got = $digester->hexdigest();
929 fail "$dscurl has hash $got but".
930 " archive told us to expect $digest";
932 my $dscfh = new IO::File \$dscdata, '<' or die $!;
933 printdebug Dumper($dscdata) if $debug>1;
934 $dsc = parsecontrolfh($dscfh,$dscurl,1);
935 printdebug Dumper($dsc) if $debug>1;
936 my $fmt = getfield $dsc, 'Format';
937 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
938 $dsc_checked = !!$digester;
944 sub check_for_git () {
946 my $how = access_cfg('git-check');
947 if ($how eq 'ssh-cmd') {
949 (access_cfg_ssh, access_gituserhost(),
950 " set -e; cd ".access_cfg('git-path').";".
951 " if test -d $package.git; then echo 1; else echo 0; fi");
952 my $r= cmdoutput @cmd;
953 failedcmd @cmd unless $r =~ m/^[01]$/;
955 } elsif ($how eq 'true') {
957 } elsif ($how eq 'false') {
960 badcfg "unknown git-check \`$how'";
964 sub create_remote_git_repo () {
965 my $how = access_cfg('git-create');
966 if ($how eq 'ssh-cmd') {
968 (access_cfg_ssh, access_gituserhost(),
969 "set -e; cd ".access_cfg('git-path').";".
970 " cp -a _template $package.git");
971 } elsif ($how eq 'true') {
974 badcfg "unknown git-create \`$how'";
978 our ($dsc_hash,$lastpush_hash);
980 our $ud = '.git/dgit/unpack';
988 sub mktree_in_ud_here () {
989 runcmd qw(git init -q);
990 rmtree('.git/objects');
991 symlink '../../../../objects','.git/objects' or die $!;
994 sub mktree_in_ud_from_only_subdir () {
995 # changes into the subdir
998 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1001 fail "source package contains .git directory" if stat_exists '.git';
1002 mktree_in_ud_here();
1003 my $format=get_source_format();
1004 if (madformat($format)) {
1007 runcmd @git, qw(add -Af);
1008 my $tree = cmdoutput @git, qw(write-tree);
1009 $tree =~ m/^\w+$/ or die "$tree ?";
1010 return ($tree,$dir);
1013 sub dsc_files_info () {
1014 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1015 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1016 ['Files', 'Digest::MD5', 'new()']) {
1017 my ($fname, $module, $method) = @$csumi;
1018 my $field = $dsc->{$fname};
1019 next unless defined $field;
1020 eval "use $module; 1;" or die $@;
1022 foreach (split /\n/, $field) {
1024 m/^(\w+) (\d+) (\S+)$/ or
1025 fail "could not parse .dsc $fname line \`$_'";
1026 my $digester = eval "$module"."->$method;" or die $@;
1031 Digester => $digester,
1036 fail "missing any supported Checksums-* or Files field in ".
1037 $dsc->get_option('name');
1041 map { $_->{Filename} } dsc_files_info();
1044 sub is_orig_file ($;$) {
1047 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1048 defined $base or return 1;
1052 sub make_commit ($) {
1054 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1057 sub clogp_authline ($) {
1059 my $author = getfield $clogp, 'Maintainer';
1060 $author =~ s#,.*##ms;
1061 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1062 my $authline = "$author $date";
1063 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1064 fail "unexpected commit author line format \`$authline'".
1065 " (was generated from changelog Maintainer field)";
1069 sub generate_commit_from_dsc () {
1073 foreach my $fi (dsc_files_info()) {
1074 my $f = $fi->{Filename};
1075 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1077 link "../../../$f", $f
1081 complete_file_from_dsc('.', $fi);
1083 if (is_orig_file($f)) {
1084 link $f, "../../../../$f"
1090 my $dscfn = "$package.dsc";
1092 open D, ">", $dscfn or die "$dscfn: $!";
1093 print D $dscdata or die "$dscfn: $!";
1094 close D or die "$dscfn: $!";
1095 my @cmd = qw(dpkg-source);
1096 push @cmd, '--no-check' if $dsc_checked;
1097 push @cmd, qw(-x --), $dscfn;
1100 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1101 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1102 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1103 my $authline = clogp_authline $clogp;
1104 my $changes = getfield $clogp, 'Changes';
1105 open C, ">../commit.tmp" or die $!;
1106 print C <<END or die $!;
1113 # imported from the archive
1116 my $outputhash = make_commit qw(../commit.tmp);
1117 my $cversion = getfield $clogp, 'Version';
1118 progress "synthesised git commit from .dsc $cversion";
1119 if ($lastpush_hash) {
1120 runcmd @git, qw(reset --hard), $lastpush_hash;
1121 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1122 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1123 my $oversion = getfield $oldclogp, 'Version';
1125 version_compare($oversion, $cversion);
1127 # git upload/ is earlier vsn than archive, use archive
1128 open C, ">../commit2.tmp" or die $!;
1129 print C <<END or die $!;
1131 parent $lastpush_hash
1136 Record $package ($cversion) in archive suite $csuite
1138 $outputhash = make_commit qw(../commit2.tmp);
1139 } elsif ($vcmp > 0) {
1140 print STDERR <<END or die $!;
1142 Version actually in archive: $cversion (older)
1143 Last allegedly pushed/uploaded: $oversion (newer or same)
1146 $outputhash = $lastpush_hash;
1148 $outputhash = $lastpush_hash;
1151 changedir '../../../..';
1152 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1153 'DGIT_ARCHIVE', $outputhash;
1154 cmdoutput @git, qw(log -n2), $outputhash;
1155 # ... gives git a chance to complain if our commit is malformed
1160 sub complete_file_from_dsc ($$) {
1161 our ($dstdir, $fi) = @_;
1162 # Ensures that we have, in $dir, the file $fi, with the correct
1163 # contents. (Downloading it from alongside $dscurl if necessary.)
1165 my $f = $fi->{Filename};
1166 my $tf = "$dstdir/$f";
1169 if (stat_exists $tf) {
1170 progress "using existing $f";
1173 $furl =~ s{/[^/]+$}{};
1175 die "$f ?" unless $f =~ m/^${package}_/;
1176 die "$f ?" if $f =~ m#/#;
1177 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1178 next if !act_local();
1182 open F, "<", "$tf" or die "$tf: $!";
1183 $fi->{Digester}->reset();
1184 $fi->{Digester}->addfile(*F);
1185 F->error and die $!;
1186 my $got = $fi->{Digester}->hexdigest();
1187 $got eq $fi->{Hash} or
1188 fail "file $f has hash $got but .dsc".
1189 " demands hash $fi->{Hash} ".
1190 ($downloaded ? "(got wrong file from archive!)"
1191 : "(perhaps you should delete this file?)");
1194 sub ensure_we_have_orig () {
1195 foreach my $fi (dsc_files_info()) {
1196 my $f = $fi->{Filename};
1197 next unless is_orig_file($f);
1198 complete_file_from_dsc('..', $fi);
1203 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1206 sub is_fast_fwd ($$) {
1207 my ($ancestor,$child) = @_;
1208 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1209 my $mb = cmdoutput_errok @cmd;
1211 return rev_parse($mb) eq rev_parse($ancestor);
1213 $?==256 or failedcmd @cmd;
1218 sub git_fetch_us () {
1219 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1222 sub fetch_from_archive () {
1223 # ensures that lrref() is what is actually in the archive,
1224 # one way or another
1228 foreach my $field (@ourdscfield) {
1229 $dsc_hash = $dsc->{$field};
1230 last if defined $dsc_hash;
1232 if (defined $dsc_hash) {
1233 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1235 progress "last upload to archive specified git hash";
1237 progress "last upload to archive has NO git hash";
1240 progress "no version available from the archive";
1243 $lastpush_hash = git_get_ref(lrref());
1244 printdebug "previous reference hash=$lastpush_hash\n";
1246 if (defined $dsc_hash) {
1247 fail "missing remote git history even though dsc has hash -".
1248 " could not find ref ".lrref().
1249 " (should have been fetched from ".access_giturl()."#".rrref().")"
1250 unless $lastpush_hash;
1252 ensure_we_have_orig();
1253 if ($dsc_hash eq $lastpush_hash) {
1254 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1255 print STDERR <<END or die $!;
1257 Git commit in archive is behind the last version allegedly pushed/uploaded.
1258 Commit referred to by archive: $dsc_hash
1259 Last allegedly pushed/uploaded: $lastpush_hash
1262 $hash = $lastpush_hash;
1264 fail "archive's .dsc refers to ".$dsc_hash.
1265 " but this is an ancestor of ".$lastpush_hash;
1268 $hash = generate_commit_from_dsc();
1269 } elsif ($lastpush_hash) {
1270 # only in git, not in the archive yet
1271 $hash = $lastpush_hash;
1272 print STDERR <<END or die $!;
1274 Package not found in the archive, but has allegedly been pushed using dgit.
1278 printdebug "nothing found!\n";
1279 if (defined $skew_warning_vsn) {
1280 print STDERR <<END or die $!;
1282 Warning: relevant archive skew detected.
1283 Archive allegedly contains $skew_warning_vsn
1284 But we were not able to obtain any version from the archive or git.
1290 printdebug "current hash=$hash\n";
1291 if ($lastpush_hash) {
1292 fail "not fast forward on last upload branch!".
1293 " (archive's version left in DGIT_ARCHIVE)"
1294 unless is_fast_fwd($lastpush_hash, $hash);
1296 if (defined $skew_warning_vsn) {
1298 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1299 my $clogf = ".git/dgit/changelog.tmp";
1300 runcmd shell_cmd "exec >$clogf",
1301 @git, qw(cat-file blob), "$hash:debian/changelog";
1302 my $gotclogp = parsechangelog("-l$clogf");
1303 my $got_vsn = getfield $gotclogp, 'Version';
1304 printdebug "SKEW CHECK GOT $got_vsn\n";
1305 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1306 print STDERR <<END or die $!;
1308 Warning: archive skew detected. Using the available version:
1309 Archive allegedly contains $skew_warning_vsn
1310 We were able to obtain only $got_vsn
1315 if ($lastpush_hash ne $hash) {
1316 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1320 dryrun_report @upd_cmd;
1328 canonicalise_suite();
1329 badusage "dry run makes no sense with clone" unless act_local();
1330 mkdir $dstdir or die "$dstdir $!";
1332 runcmd @git, qw(init -q);
1333 my $giturl = access_giturl(1);
1334 if (defined $giturl) {
1335 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1336 open H, "> .git/HEAD" or die $!;
1337 print H "ref: ".lref()."\n" or die $!;
1339 runcmd @git, qw(remote add), 'origin', $giturl;
1341 if (check_for_git()) {
1342 progress "fetching existing git history";
1344 runcmd_ordryrun_local @git, qw(fetch origin);
1346 progress "starting new git history";
1348 fetch_from_archive() or no_such_package;
1349 my $vcsgiturl = $dsc->{'Vcs-Git'};
1350 if (length $vcsgiturl) {
1351 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1353 runcmd @git, qw(reset --hard), lrref();
1354 printdone "ready for work in $dstdir";
1358 if (check_for_git()) {
1361 fetch_from_archive() or no_such_package();
1362 printdone "fetched into ".lrref();
1367 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1369 printdone "fetched to ".lrref()." and merged into HEAD";
1372 sub check_not_dirty () {
1373 return if $ignoredirty;
1374 my @cmd = (@git, qw(diff --quiet HEAD));
1375 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1376 $!=0; $?=0; system @cmd;
1377 return if !$! && !$?;
1378 if (!$! && $?==256) {
1379 fail "working tree is dirty (does not match HEAD)";
1385 sub commit_admin ($) {
1388 runcmd_ordryrun_local @git, qw(commit -m), $m;
1391 sub commit_quilty_patch () {
1392 my $output = cmdoutput @git, qw(status --porcelain);
1394 foreach my $l (split /\n/, $output) {
1395 next unless $l =~ m/\S/;
1396 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1400 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1402 progress "nothing quilty to commit, ok.";
1405 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1406 commit_admin "Commit Debian 3.0 (quilt) metadata";
1409 sub get_source_format () {
1410 if (!open F, "debian/source/format") {
1411 die $! unless $!==&ENOENT;
1415 F->error and die $!;
1422 return 0 unless $format eq '3.0 (quilt)';
1424 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1427 progress "Format \`$format', checking/updating patch stack";
1431 sub push_parse_changelog ($) {
1434 my $clogp = Dpkg::Control::Hash->new();
1435 $clogp->load($clogpfn) or die;
1437 $package = getfield $clogp, 'Source';
1438 my $cversion = getfield $clogp, 'Version';
1439 my $tag = debiantag($cversion);
1440 runcmd @git, qw(check-ref-format), $tag;
1442 my $dscfn = dscfn($cversion);
1444 return ($clogp, $cversion, $tag, $dscfn);
1447 sub push_parse_dsc ($$$) {
1448 my ($dscfn,$dscfnwhat, $cversion) = @_;
1449 $dsc = parsecontrol($dscfn,$dscfnwhat);
1450 my $dversion = getfield $dsc, 'Version';
1451 my $dscpackage = getfield $dsc, 'Source';
1452 ($dscpackage eq $package && $dversion eq $cversion) or
1453 fail "$dscfn is for $dscpackage $dversion".
1454 " but debian/changelog is for $package $cversion";
1457 sub push_mktag ($$$$$$$) {
1458 my ($head,$clogp,$tag,
1460 $changesfile,$changesfilewhat,
1463 $dsc->{$ourdscfield[0]} = $head;
1464 $dsc->save("$dscfn.tmp") or die $!;
1466 my $changes = parsecontrol($changesfile,$changesfilewhat);
1467 foreach my $field (qw(Source Distribution Version)) {
1468 $changes->{$field} eq $clogp->{$field} or
1469 fail "changes field $field \`$changes->{$field}'".
1470 " does not match changelog \`$clogp->{$field}'";
1473 my $cversion = getfield $clogp, 'Version';
1474 my $clogsuite = getfield $clogp, 'Distribution';
1476 # We make the git tag by hand because (a) that makes it easier
1477 # to control the "tagger" (b) we can do remote signing
1478 my $authline = clogp_authline $clogp;
1479 open TO, '>', $tfn->('.tmp') or die $!;
1480 print TO <<END or die $!;
1486 $package release $cversion for $clogsuite ($csuite) [dgit]
1490 my $tagobjfn = $tfn->('.tmp');
1492 if (!defined $keyid) {
1493 $keyid = access_cfg('keyid','RETURN-UNDEF');
1495 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1496 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1497 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1498 push @sign_cmd, $tfn->('.tmp');
1499 runcmd_ordryrun @sign_cmd;
1501 $tagobjfn = $tfn->('.signed.tmp');
1502 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1503 $tfn->('.tmp'), $tfn->('.tmp.asc');
1510 sub sign_changes ($) {
1511 my ($changesfile) = @_;
1513 my @debsign_cmd = @debsign;
1514 push @debsign_cmd, "-k$keyid" if defined $keyid;
1515 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1516 push @debsign_cmd, $changesfile;
1517 runcmd_ordryrun @debsign_cmd;
1522 printdebug "actually entering push\n";
1525 access_giturl(); # check that success is vaguely likely
1527 my $clogpfn = ".git/dgit/changelog.822.tmp";
1528 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1530 responder_send_file('parsed-changelog', $clogpfn);
1532 my ($clogp, $cversion, $tag, $dscfn) =
1533 push_parse_changelog("$clogpfn");
1535 my $dscpath = "$buildproductsdir/$dscfn";
1536 stat_exists $dscpath or
1537 fail "looked for .dsc $dscfn, but $!;".
1538 " maybe you forgot to build";
1540 responder_send_file('dsc', $dscpath);
1542 push_parse_dsc($dscpath, $dscfn, $cversion);
1544 my $format = getfield $dsc, 'Format';
1545 printdebug "format $format\n";
1546 if (madformat($format)) {
1547 commit_quilty_patch();
1551 progress "checking that $dscfn corresponds to HEAD";
1552 runcmd qw(dpkg-source -x --),
1553 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1554 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1555 changedir '../../../..';
1556 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1557 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1558 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1560 my $r = system @diffcmd;
1563 fail "$dscfn specifies a different tree to your HEAD commit;".
1564 " perhaps you forgot to build".
1565 ($diffopt eq '--exit-code' ? "" :
1566 " (run with -D to see full diff output)");
1572 #do fast forward check and maybe fake merge
1573 # if (!is_fast_fwd(mainbranch
1574 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1575 # map { lref($_).":".rref($_) }
1577 my $head = rev_parse('HEAD');
1578 if (!$changesfile) {
1579 my $multi = "$buildproductsdir/".
1580 "${package}_".(stripepoch $cversion)."_multi.changes";
1581 if (stat_exists "$multi") {
1582 $changesfile = $multi;
1584 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1585 my @cs = glob "$buildproductsdir/$pat";
1586 fail "failed to find unique changes file".
1587 " (looked for $pat in $buildproductsdir, or $multi);".
1588 " perhaps you need to use dgit -C"
1590 ($changesfile) = @cs;
1593 $changesfile = "$buildproductsdir/$changesfile";
1596 responder_send_file('changes',$changesfile);
1597 responder_send_command("param head $head");
1598 responder_send_command("param csuite $csuite");
1600 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1603 if ($we_are_responder) {
1604 $tagobjfn = $tfn->('.signed.tmp');
1605 responder_receive_files('signed-tag', $tagobjfn);
1608 push_mktag($head,$clogp,$tag,
1610 $changesfile,$changesfile,
1614 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1615 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1616 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1617 runcmd_ordryrun @git, qw(tag -v --), $tag;
1619 if (!check_for_git()) {
1620 create_remote_git_repo();
1622 runcmd_ordryrun @git, qw(push),access_giturl(),
1623 "HEAD:".rrref(), "refs/tags/$tag";
1624 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1626 if ($we_are_responder) {
1627 my $dryrunsuffix = act_local() ? "" : ".tmp";
1628 responder_receive_files('signed-dsc-changes',
1629 "$dscpath$dryrunsuffix",
1630 "$changesfile$dryrunsuffix");
1633 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1635 progress "[new .dsc left in $dscpath.tmp]";
1637 sign_changes $changesfile;
1640 my $host = access_cfg('upload-host','RETURN-UNDEF');
1641 my @hostarg = defined($host) ? ($host,) : ();
1642 runcmd_ordryrun @dput, @hostarg, $changesfile;
1643 printdone "pushed and uploaded $cversion";
1645 responder_send_command("complete");
1651 badusage "-p is not allowed with clone; specify as argument instead"
1652 if defined $package;
1655 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1656 ($package,$isuite) = @ARGV;
1657 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1658 ($package,$dstdir) = @ARGV;
1659 } elsif (@ARGV==3) {
1660 ($package,$isuite,$dstdir) = @ARGV;
1662 badusage "incorrect arguments to dgit clone";
1664 $dstdir ||= "$package";
1666 if (stat_exists $dstdir) {
1667 fail "$dstdir already exists";
1671 if ($rmonerror && !$dryrun_level) {
1672 $cwd_remove= getcwd();
1674 return unless defined $cwd_remove;
1675 if (!chdir "$cwd_remove") {
1676 return if $!==&ENOENT;
1677 die "chdir $cwd_remove: $!";
1679 rmtree($dstdir) or die "remove $dstdir: $!\n";
1684 $cwd_remove = undef;
1687 sub branchsuite () {
1688 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1689 if ($branch =~ m#$lbranch_re#o) {
1696 sub fetchpullargs () {
1697 if (!defined $package) {
1698 my $sourcep = parsecontrol('debian/control','debian/control');
1699 $package = getfield $sourcep, 'Source';
1702 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1704 my $clogp = parsechangelog();
1705 $isuite = getfield $clogp, 'Distribution';
1707 canonicalise_suite();
1708 progress "fetching from suite $csuite";
1709 } elsif (@ARGV==1) {
1711 canonicalise_suite();
1713 badusage "incorrect arguments to dgit fetch or dgit pull";
1731 badusage "-p is not allowed with dgit push" if defined $package;
1733 my $clogp = parsechangelog();
1734 $package = getfield $clogp, 'Source';
1737 } elsif (@ARGV==1) {
1738 ($specsuite) = (@ARGV);
1740 badusage "incorrect arguments to dgit push";
1742 $isuite = getfield $clogp, 'Distribution';
1744 local ($package) = $existing_package; # this is a hack
1745 canonicalise_suite();
1747 if (defined $specsuite && $specsuite ne $isuite) {
1748 canonicalise_suite();
1749 $csuite eq $specsuite or
1750 fail "dgit push: changelog specifies $isuite ($csuite)".
1751 " but command line specifies $specsuite";
1753 if (check_for_git()) {
1756 if (fetch_from_archive()) {
1757 is_fast_fwd(lrref(), 'HEAD') or
1758 fail "dgit push: HEAD is not a descendant".
1759 " of the archive's version.\n".
1760 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1763 fail "package appears to be new in this suite;".
1764 " if this is intentional, use --new";
1769 #---------- remote commands' implementation ----------
1771 sub cmd_remote_push_build_host {
1772 my ($nrargs) = shift @ARGV;
1773 my (@rargs) = @ARGV[0..$nrargs-1];
1774 @ARGV = @ARGV[$nrargs..$#ARGV];
1776 my ($dir,$vsnwant) = @rargs;
1777 # vsnwant is a comma-separated list; we report which we have
1778 # chosen in our ready response (so other end can tell if they
1781 $we_are_responder = 1;
1783 open PI, "<&STDIN" or die $!;
1784 open STDIN, "/dev/null" or die $!;
1785 open PO, ">&STDOUT" or die $!;
1787 open STDOUT, ">&STDERR" or die $!;
1791 fail "build host has dgit rpush protocol version".
1792 " $rpushprotovsn but invocation host has $vsnwant"
1793 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1795 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1801 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1802 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1803 # a good error message)
1809 my $report = i_child_report();
1810 if (defined $report) {
1811 printdebug "($report)\n";
1812 } elsif ($i_child_pid) {
1813 printdebug "(killing build host child $i_child_pid)\n";
1814 kill 15, $i_child_pid;
1816 if (defined $i_tmp && !defined $initiator_tempdir) {
1818 eval { rmtree $i_tmp; };
1822 END { i_cleanup(); }
1825 my ($base,$selector,@args) = @_;
1826 $selector =~ s/\-/_/g;
1827 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1833 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1840 my @rargs = ($dir,$rpushprotovsn);
1843 push @rdgit, @ropts;
1844 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1846 my @cmd = (@ssh, $host, shellquote @rdgit);
1847 printcmd \*DEBUG,$debugprefix."+",@cmd;
1849 if (defined $initiator_tempdir) {
1850 rmtree $initiator_tempdir;
1851 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1852 $i_tmp = $initiator_tempdir;
1856 $i_child_pid = open2(\*RO, \*RI, @cmd);
1858 initiator_expect { m/^dgit-remote-push-ready/ };
1860 my ($icmd,$iargs) = initiator_expect {
1861 m/^(\S+)(?: (.*))?$/;
1864 i_method "i_resp", $icmd, $iargs;
1868 sub i_resp_progress ($) {
1870 my $msg = protocol_read_bytes \*RO, $rhs;
1874 sub i_resp_complete {
1875 my $pid = $i_child_pid;
1876 $i_child_pid = undef; # prevents killing some other process with same pid
1877 printdebug "waiting for build host child $pid...\n";
1878 my $got = waitpid $pid, 0;
1879 die $! unless $got == $pid;
1880 die "build host child failed $?" if $?;
1883 printdebug "all done\n";
1887 sub i_resp_file ($) {
1889 my $localname = i_method "i_localname", $keyword;
1890 my $localpath = "$i_tmp/$localname";
1891 stat_exists $localpath and
1892 badproto \*RO, "file $keyword ($localpath) twice";
1893 protocol_receive_file \*RO, $localpath;
1894 i_method "i_file", $keyword;
1899 sub i_resp_param ($) {
1900 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1906 sub i_resp_want ($) {
1908 die "$keyword ?" if $i_wanted{$keyword}++;
1909 my @localpaths = i_method "i_want", $keyword;
1910 printdebug "[[ $keyword @localpaths\n";
1911 foreach my $localpath (@localpaths) {
1912 protocol_send_file \*RI, $localpath;
1914 print RI "files-end\n" or die $!;
1917 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1919 sub i_localname_parsed_changelog {
1920 return "remote-changelog.822";
1922 sub i_file_parsed_changelog {
1923 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1924 push_parse_changelog "$i_tmp/remote-changelog.822";
1925 die if $i_dscfn =~ m#/|^\W#;
1928 sub i_localname_dsc {
1929 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1934 sub i_localname_changes {
1935 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1936 $i_changesfn = $i_dscfn;
1937 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1938 return $i_changesfn;
1940 sub i_file_changes { }
1942 sub i_want_signed_tag {
1943 printdebug Dumper(\%i_param, $i_dscfn);
1944 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1945 && defined $i_param{'csuite'}
1946 or badproto \*RO, "premature desire for signed-tag";
1947 my $head = $i_param{'head'};
1948 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1950 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1952 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1955 push_mktag $head, $i_clogp, $i_tag,
1957 $i_changesfn, 'remote changes',
1958 sub { "tag$_[0]"; };
1963 sub i_want_signed_dsc_changes {
1964 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1965 sign_changes $i_changesfn;
1966 return ($i_dscfn, $i_changesfn);
1969 #---------- building etc. ----------
1975 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1977 sub build_maybe_quilt_fixup () {
1978 my $format=get_source_format;
1979 return unless madformat $format;
1983 # - honour any existing .pc in case it has any strangeness
1984 # - determine the git commit corresponding to the tip of
1985 # the patch stack (if there is one)
1986 # - if there is such a git commit, convert each subsequent
1987 # git commit into a quilt patch with dpkg-source --commit
1988 # - otherwise convert all the differences in the tree into
1989 # a single git commit
1993 # Our git tree doesn't necessarily contain .pc. (Some versions of
1994 # dgit would include the .pc in the git tree.) If there isn't
1995 # one, we need to generate one by unpacking the patches that we
1998 # We first look for a .pc in the git tree. If there is one, we
1999 # will use it. (This is not the normal case.)
2001 # Otherwise need to regenerate .pc so that dpkg-source --commit
2002 # can work. We do this as follows:
2003 # 1. Collect all relevant .orig from parent directory
2004 # 2. Generate a debian.tar.gz out of
2005 # debian/{patches,rules,source/format}
2006 # 3. Generate a fake .dsc containing just these fields:
2007 # Format Source Version Files
2008 # 4. Extract the fake .dsc
2009 # Now the fake .dsc has a .pc directory.
2010 # (In fact we do this in every case, because in future we will
2011 # want to search for a good base commit for generating patches.)
2013 # Then we can actually do the dpkg-source --commit
2014 # 1. Make a new working tree with the same object
2015 # store as our main tree and check out the main
2017 # 2. Copy .pc from the fake's extraction, if necessary
2018 # 3. Run dpkg-source --commit
2019 # 4. If the result has changes to debian/, then
2020 # - git-add them them
2021 # - git-add .pc if we had a .pc in-tree
2023 # 5. If we had a .pc in-tree, delete it, and git-commit
2024 # 6. Back in the main tree, fast forward to the new HEAD
2026 my $clogp = parsechangelog();
2027 my $headref = rev_parse('HEAD');
2032 my $upstreamversion=$version;
2033 $upstreamversion =~ s/-[^-]*$//;
2035 my $fakeversion="$upstreamversion-~~DGITFAKE";
2037 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2038 print $fakedsc <<END or die $!;
2041 Version: $fakeversion
2045 my $dscaddfile=sub {
2048 my $md = new Digest::MD5;
2050 my $fh = new IO::File $b, '<' or die "$b $!";
2055 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2058 foreach my $f (<../../../../*>) { #/){
2059 my $b=$f; $b =~ s{.*/}{};
2060 next unless is_orig_file $b, srcfn $upstreamversion,'';
2061 link $f, $b or die "$b $!";
2065 my @files=qw(debian/source/format debian/rules);
2066 if (stat_exists '../../../debian/patches') {
2067 push @files, 'debian/patches';
2070 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2071 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2073 $dscaddfile->($debtar);
2074 close $fakedsc or die $!;
2076 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2078 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2079 rename $fakexdir, "fake" or die "$fakexdir $!";
2081 mkdir "work" or die $!;
2083 mktree_in_ud_here();
2084 runcmd @git, qw(reset --hard), $headref;
2087 if (stat_exists ".pc") {
2089 progress "Tree already contains .pc - will use it then delete it.";
2092 rename '../fake/.pc','.pc' or die $!;
2095 my $author = getfield $clogp, 'Maintainer';
2098 my $patchname = "auto-$version-$headref-$time";
2099 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2101 my $descfn = ".git/dgit/quilt-description.tmp";
2102 open O, '>', $descfn or die "$descfn: $!";
2104 $msg =~ s/^\s+$/ ./mg;
2105 print O <<END or die $!;
2106 Description: Automatically generated patch ($clogp->{Version})
2107 Last (up to) $ncommits git changes, FYI:
2117 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2118 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2119 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2120 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2123 if (!open P, '>>', ".pc/applied-patches") {
2124 $!==&ENOENT or die $!;
2129 commit_quilty_patch();
2131 if ($mustdeletepc) {
2132 runcmd @git, qw(rm -rq .pc);
2133 commit_admin "Commit removal of .pc (quilt series tracking data)";
2136 changedir '../../../..';
2137 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2140 sub quilt_fixup_editor () {
2141 my $descfn = $ENV{$fakeeditorenv};
2142 my $editing = $ARGV[$#ARGV];
2143 open I1, '<', $descfn or die "$descfn: $!";
2144 open I2, '<', $editing or die "$editing: $!";
2145 unlink $editing or die "$editing: $!";
2146 open O, '>', $editing or die "$editing: $!";
2147 while (<I1>) { print O or die $!; } I1->error and die $!;
2150 $copying ||= m/^\-\-\- /;
2151 next unless $copying;
2154 I2->error and die $!;
2160 if ($cleanmode eq 'dpkg-source') {
2161 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2162 } elsif ($cleanmode eq 'git') {
2163 runcmd_ordryrun_local @git, qw(clean -xdf);
2164 } elsif ($cleanmode eq 'none') {
2171 badusage "clean takes no additional arguments" if @ARGV;
2176 badusage "-p is not allowed when building" if defined $package;
2179 my $clogp = parsechangelog();
2180 $isuite = getfield $clogp, 'Distribution';
2181 $package = getfield $clogp, 'Source';
2182 $version = getfield $clogp, 'Version';
2183 build_maybe_quilt_fixup();
2186 sub changesopts () {
2187 my @opts =@changesopts[1..$#changesopts];
2188 if (!defined $changes_since_version) {
2189 my @vsns = archive_query('archive_query');
2190 my @quirk = access_quirk();
2191 if ($quirk[0] eq 'backports') {
2192 local $isuite = $quirk[2];
2194 canonicalise_suite();
2195 push @vsns, archive_query('archive_query');
2198 @vsns = map { $_->[0] } @vsns;
2199 @vsns = sort { -version_compare($a, $b) } @vsns;
2200 $changes_since_version = $vsns[0];
2201 progress "changelog will contain changes since $vsns[0]";
2203 $changes_since_version = '_';
2204 progress "package seems new, not specifying -v<version>";
2207 if ($changes_since_version ne '_') {
2208 unshift @opts, "-v$changes_since_version";
2215 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2216 printdone "build successful\n";
2222 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2223 "--git-builder=@dpkgbuildpackage");
2224 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2225 canonicalise_suite();
2226 push @cmd, "--git-debian-branch=".lbranch();
2228 push @cmd, changesopts();
2229 runcmd_ordryrun_local @cmd, @ARGV;
2230 printdone "build successful\n";
2235 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2236 $dscfn = dscfn($version);
2237 if ($cleanmode eq 'dpkg-source') {
2238 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2241 my $pwd = must_getcwd();
2242 my $leafdir = basename $pwd;
2244 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2246 runcmd_ordryrun_local qw(sh -ec),
2247 'exec >$1; shift; exec "$@"','x',
2248 "../$sourcechanges",
2249 @dpkggenchanges, qw(-S), changesopts();
2253 sub cmd_build_source {
2254 badusage "build-source takes no additional arguments" if @ARGV;
2256 printdone "source built, results in $dscfn and $sourcechanges";
2262 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2264 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2265 stat_exists $sourcechanges
2266 or fail "$sourcechanges (in parent directory): $!";
2267 foreach my $cf (glob $pat) {
2268 next if $cf eq $sourcechanges;
2269 unlink $cf or fail "remove $cf: $!";
2272 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2273 my @changesfiles = glob $pat;
2274 @changesfiles = sort {
2275 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2278 fail "wrong number of different changes files (@changesfiles)"
2279 unless @changesfiles;
2280 runcmd_ordryrun_local @mergechanges, @changesfiles;
2281 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2283 stat_exists $multichanges or fail "$multichanges: $!";
2285 printdone "build successful, results in $multichanges\n" or die $!;
2288 sub cmd_quilt_fixup {
2289 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2290 my $clogp = parsechangelog();
2291 $version = getfield $clogp, 'Version';
2292 $package = getfield $clogp, 'Source';
2293 build_maybe_quilt_fixup();
2296 #---------- argument parsing and main program ----------
2299 print "dgit version $our_version\n" or die $!;
2306 if (defined $ENV{'DGIT_SSH'}) {
2307 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2308 } elsif (defined $ENV{'GIT_SSH'}) {
2309 @ssh = ($ENV{'GIT_SSH'});
2313 last unless $ARGV[0] =~ m/^-/;
2317 if (m/^--dry-run$/) {
2320 } elsif (m/^--damp-run$/) {
2323 } elsif (m/^--no-sign$/) {
2326 } elsif (m/^--help$/) {
2328 } elsif (m/^--version$/) {
2330 } elsif (m/^--new$/) {
2333 } elsif (m/^--since-version=([^_]+|_)$/) {
2335 $changes_since_version = $1;
2336 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2337 ($om = $opts_opt_map{$1}) &&
2341 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2342 !$opts_opt_cmdonly{$1} &&
2343 ($om = $opts_opt_map{$1})) {
2346 } elsif (m/^--existing-package=(.*)/s) {
2348 $existing_package = $1;
2349 } elsif (m/^--initiator-tempdir=(.*)/s) {
2350 $initiator_tempdir = $1;
2351 $initiator_tempdir =~ m#^/# or
2352 badusage "--initiator-tempdir must be used specify an".
2353 " absolute, not relative, directory."
2354 } elsif (m/^--distro=(.*)/s) {
2357 } elsif (m/^--build-products-dir=(.*)/s) {
2359 $buildproductsdir = $1;
2360 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2363 } elsif (m/^--clean=(.*)$/s) {
2364 badusage "unknown cleaning mode \`$1'";
2365 } elsif (m/^--ignore-dirty$/s) {
2368 } elsif (m/^--no-quilt-fixup$/s) {
2371 } elsif (m/^--no-rm-on-error$/s) {
2375 badusage "unknown long option \`$_'";
2382 } elsif (s/^-L/-/) {
2385 } elsif (s/^-h/-/) {
2387 } elsif (s/^-D/-/) {
2389 open DEBUG, ">&STDERR" or die $!;
2392 } elsif (s/^-N/-/) {
2395 } elsif (s/^-v([^_]+|_)$//s) {
2397 $changes_since_version = $1;
2400 push @changesopts, $_;
2402 } elsif (s/^-c(.*=.*)//s) {
2404 push @git, '-c', $1;
2405 } elsif (s/^-d(.*)//s) {
2408 } elsif (s/^-C(.*)//s) {
2411 if ($changesfile =~ s#^(.*)/##) {
2412 $buildproductsdir = $1;
2414 } elsif (s/^-k(.*)//s) {
2416 } elsif (s/^-wn//s) {
2418 $cleanmode = 'none';
2419 } elsif (s/^-wg//s) {
2422 } elsif (s/^-wd//s) {
2424 $cleanmode = 'dpkg-source';
2426 badusage "unknown short option \`$_'";
2433 if ($ENV{$fakeeditorenv}) {
2434 quilt_fixup_editor();
2438 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2439 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2440 if $dryrun_level == 1;
2442 print STDERR $helpmsg or die $!;
2445 my $cmd = shift @ARGV;
2448 my $fn = ${*::}{"cmd_$cmd"};
2449 $fn or badusage "unknown operation $cmd";