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 or undef, 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',undef);
594 sub access_distros () {
595 # Returns list of distros to try, in order
598 # 1. the access_quirk distro, if any
599 # 2a. the user's specified distro, or failing that } basedistro
600 # 2b. the distro calculated from the suite }
601 my @l = access_basedistro();
603 my (undef,$quirkdistro) = access_quirk();
604 unshift @l, $quirkdistro if defined $quirkdistro;
612 # The nesting of these loops determines the search order. We put
613 # the key loop on the outside so that we search all the distros
614 # for each key, before going on to the next key. That means that
615 # if access_cfg is called with a more specific, and then a less
616 # specific, key, an earlier distro can override the less specific
617 # without necessarily overriding any more specific keys. (If the
618 # distro wants to override the more specific keys it can simply do
619 # so; whereas if we did the loop the other way around, it would be
620 # impossible to for an earlier distro to override a less specific
621 # key but not the more specific ones without restating the unknown
622 # values of the more specific keys.
625 # We have to deal with RETURN-UNDEF specially, so that we don't
626 # terminate the search prematurely.
628 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
631 foreach my $d (access_distros()) {
632 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
634 push @cfgs, map { "dgit.default.$_" } @realkeys;
636 my $value = cfg(@cfgs);
640 sub string_to_ssh ($) {
642 if ($spec =~ m/\s/) {
643 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
649 sub access_cfg_ssh () {
650 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
651 if (!defined $gitssh) {
654 return string_to_ssh $gitssh;
658 sub access_someuserhost ($) {
660 my $user = access_cfg("$some-user",'username');
661 my $host = access_cfg("$some-host");
662 return length($user) ? "$user\@$host" : $host;
665 sub access_gituserhost () {
666 return access_someuserhost('git');
669 sub access_giturl (;$) {
671 my $url = access_cfg('git-url','RETURN-UNDEF');
673 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
674 return undef unless defined $proto;
677 access_gituserhost().
678 access_cfg('git-path');
680 return "$url/$package.git";
683 sub parsecontrolfh ($$;$) {
684 my ($fh, $desc, $allowsigned) = @_;
685 our $dpkgcontrolhash_noissigned;
688 my %opts = ('name' => $desc);
689 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
690 $c = Dpkg::Control::Hash->new(%opts);
691 $c->parse($fh,$desc) or die "parsing of $desc failed";
692 last if $allowsigned;
693 last if $dpkgcontrolhash_noissigned;
694 my $issigned= $c->get_option('is_pgp_signed');
695 if (!defined $issigned) {
696 $dpkgcontrolhash_noissigned= 1;
697 seek $fh, 0,0 or die "seek $desc: $!";
698 } elsif ($issigned) {
699 fail "control file $desc is (already) PGP-signed. ".
700 " Note that dgit push needs to modify the .dsc and then".
701 " do the signature itself";
710 my ($file, $desc) = @_;
711 my $fh = new IO::Handle;
712 open $fh, '<', $file or die "$file: $!";
713 my $c = parsecontrolfh($fh,$desc);
714 $fh->error and die $!;
720 my ($dctrl,$field) = @_;
721 my $v = $dctrl->{$field};
722 return $v if defined $v;
723 fail "missing field $field in ".$v->get_option('name');
727 my $c = Dpkg::Control::Hash->new();
728 my $p = new IO::Handle;
729 my @cmd = (qw(dpkg-parsechangelog), @_);
730 open $p, '-|', @cmd or die $!;
732 $?=0; $!=0; close $p or failedcmd @cmd;
736 sub git_get_ref ($) {
738 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
740 $?==256 or fail "git show-ref failed (status $?)";
741 printdebug "ref $refname= [show-ref exited 1]\n";
744 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
745 printdebug "ref $refname=$1\n";
748 printdebug "ref $refname= [no match]\n";
755 defined $d or fail "getcwd failed: $!";
761 sub archive_query ($) {
763 my $query = access_cfg('archive-query','RETURN-UNDEF');
764 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
767 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
770 sub pool_dsc_subpath ($$) {
771 my ($vsn,$component) = @_; # $package is implict arg
772 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
773 return "/pool/$component/$prefix/$package/".dscfn($vsn);
776 sub archive_query_madison {
777 return map { [ @$_[0..1] ] } madison_get_parse(@_);
780 sub madison_get_parse {
781 my ($proto,$data) = @_;
782 die unless $proto eq 'madison';
784 $data= access_cfg('madison-distro','RETURN-UNDEF');
785 $data //= access_basedistro();
787 $rmad{$proto,$data,$package} ||= cmdoutput
788 qw(rmadison -asource),"-s$isuite","-u$data",$package;
789 my $rmad = $rmad{$proto,$data,$package};
792 foreach my $l (split /\n/, $rmad) {
793 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
794 \s*( [^ \t|]+ )\s* \|
795 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
796 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
797 $1 eq $package or die "$rmad $package ?";
804 $component = access_cfg('archive-query-default-component');
806 $5 eq 'source' or die "$rmad ?";
807 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
809 return sort { -version_compare($a->[0],$b->[0]); } @out;
812 sub canonicalise_suite_madison {
813 # madison canonicalises for us
814 my @r = madison_get_parse(@_);
816 "unable to canonicalise suite using package $package".
817 " which does not appear to exist in suite $isuite;".
818 " --existing-package may help";
823 my ($data,$sql) = @_;
825 $data= access_someuserhost('sshpsql').':'.
826 access_cfg('sshpsql-dbname');
828 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
829 my ($userhost,$dbname) = ($`,$'); #';
831 my @cmd = (access_cfg_ssh, $userhost,
832 "export LANG=C; ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
833 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
834 open P, "-|", @cmd or die $!;
837 printdebug("$debugprefix>|$_|\n");
840 $!=0; $?=0; close P or failedcmd @cmd;
842 my $nrows = pop @rows;
843 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
844 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
845 @rows = map { [ split /\|/, $_ ] } @rows;
846 my $ncols = scalar @{ shift @rows };
847 die if grep { scalar @$_ != $ncols } @rows;
851 sub sql_injection_check {
852 foreach (@_) { die "$_ $& ?" if m/[']/; }
855 sub archive_query_sshpsql ($$) {
856 my ($proto,$data) = @_;
857 sql_injection_check $isuite, $package;
858 my @rows = sshpsql($data, <<END);
859 SELECT source.version, component.name, files.filename, files.sha256sum
861 JOIN src_associations ON source.id = src_associations.source
862 JOIN suite ON suite.id = src_associations.suite
863 JOIN dsc_files ON dsc_files.source = source.id
864 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
865 JOIN component ON component.id = files_archive_map.component_id
866 JOIN files ON files.id = dsc_files.file
867 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
868 AND source.source='$package'
869 AND files.filename LIKE '%.dsc';
871 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
872 my $digester = Digest::SHA->new(256);
874 my ($vsn,$component,$filename,$sha256sum) = @$_;
875 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
880 sub canonicalise_suite_sshpsql ($$) {
881 my ($proto,$data) = @_;
882 sql_injection_check $isuite;
883 my @rows = sshpsql($data, <<END);
884 SELECT suite.codename
885 FROM suite where suite_name='$isuite' or codename='$isuite';
887 @rows = map { $_->[0] } @rows;
888 fail "unknown suite $isuite" unless @rows;
889 die "ambiguous $isuite: @rows ?" if @rows>1;
893 sub canonicalise_suite_dummycat ($$) {
894 my ($proto,$data) = @_;
895 my $dpath = "$data/suite.$isuite";
896 if (!open C, "<", $dpath) {
897 $!==ENOENT or die "$dpath: $!";
898 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
902 chomp or die "$dpath: $!";
904 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
908 sub archive_query_dummycat ($$) {
909 my ($proto,$data) = @_;
910 canonicalise_suite();
911 my $dpath = "$data/package.$csuite.$package";
912 if (!open C, "<", $dpath) {
913 $!==ENOENT or die "$dpath: $!";
914 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
922 printdebug "dummycat query $csuite $package $dpath | $_\n";
923 my @row = split /\s+/, $_;
924 @row==2 or die "$dpath: $_ ?";
927 C->error and die "$dpath: $!";
929 return sort { -version_compare($a->[0],$b->[0]); } @rows;
932 sub canonicalise_suite () {
933 return if defined $csuite;
934 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
935 $csuite = archive_query('canonicalise_suite');
936 if ($isuite ne $csuite) {
937 progress "canonical suite name for $isuite is $csuite";
941 sub get_archive_dsc () {
942 canonicalise_suite();
943 my @vsns = archive_query('archive_query');
944 foreach my $vinfo (@vsns) {
945 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
946 $dscurl = access_cfg('mirror').$subpath;
947 $dscdata = url_get($dscurl);
949 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
954 $digester->add($dscdata);
955 my $got = $digester->hexdigest();
957 fail "$dscurl has hash $got but".
958 " archive told us to expect $digest";
960 my $dscfh = new IO::File \$dscdata, '<' or die $!;
961 printdebug Dumper($dscdata) if $debug>1;
962 $dsc = parsecontrolfh($dscfh,$dscurl,1);
963 printdebug Dumper($dsc) if $debug>1;
964 my $fmt = getfield $dsc, 'Format';
965 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
966 $dsc_checked = !!$digester;
972 sub check_for_git () {
974 my $how = access_cfg('git-check');
975 if ($how eq 'ssh-cmd') {
977 (access_cfg_ssh, access_gituserhost(),
978 " set -e; cd ".access_cfg('git-path').";".
979 " if test -d $package.git; then echo 1; else echo 0; fi");
980 my $r= cmdoutput @cmd;
981 failedcmd @cmd unless $r =~ m/^[01]$/;
983 } elsif ($how eq 'true') {
985 } elsif ($how eq 'false') {
988 badcfg "unknown git-check \`$how'";
992 sub create_remote_git_repo () {
993 my $how = access_cfg('git-create');
994 if ($how eq 'ssh-cmd') {
996 (access_cfg_ssh, access_gituserhost(),
997 "set -e; cd ".access_cfg('git-path').";".
998 " cp -a _template $package.git");
999 } elsif ($how eq 'true') {
1002 badcfg "unknown git-create \`$how'";
1006 our ($dsc_hash,$lastpush_hash);
1008 our $ud = '.git/dgit/unpack';
1013 mkdir $ud or die $!;
1016 sub mktree_in_ud_here () {
1017 runcmd qw(git init -q);
1018 rmtree('.git/objects');
1019 symlink '../../../../objects','.git/objects' or die $!;
1022 sub mktree_in_ud_from_only_subdir () {
1023 # changes into the subdir
1025 die unless @dirs==1;
1026 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1029 fail "source package contains .git directory" if stat_exists '.git';
1030 mktree_in_ud_here();
1031 my $format=get_source_format();
1032 if (madformat($format)) {
1035 runcmd @git, qw(add -Af);
1036 my $tree = cmdoutput @git, qw(write-tree);
1037 $tree =~ m/^\w+$/ or die "$tree ?";
1038 return ($tree,$dir);
1041 sub dsc_files_info () {
1042 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1043 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1044 ['Files', 'Digest::MD5', 'new()']) {
1045 my ($fname, $module, $method) = @$csumi;
1046 my $field = $dsc->{$fname};
1047 next unless defined $field;
1048 eval "use $module; 1;" or die $@;
1050 foreach (split /\n/, $field) {
1052 m/^(\w+) (\d+) (\S+)$/ or
1053 fail "could not parse .dsc $fname line \`$_'";
1054 my $digester = eval "$module"."->$method;" or die $@;
1059 Digester => $digester,
1064 fail "missing any supported Checksums-* or Files field in ".
1065 $dsc->get_option('name');
1069 map { $_->{Filename} } dsc_files_info();
1072 sub is_orig_file ($;$) {
1075 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1076 defined $base or return 1;
1080 sub make_commit ($) {
1082 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1085 sub clogp_authline ($) {
1087 my $author = getfield $clogp, 'Maintainer';
1088 $author =~ s#,.*##ms;
1089 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1090 my $authline = "$author $date";
1091 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1092 fail "unexpected commit author line format \`$authline'".
1093 " (was generated from changelog Maintainer field)";
1097 sub generate_commit_from_dsc () {
1101 foreach my $fi (dsc_files_info()) {
1102 my $f = $fi->{Filename};
1103 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1105 link "../../../$f", $f
1109 complete_file_from_dsc('.', $fi);
1111 if (is_orig_file($f)) {
1112 link $f, "../../../../$f"
1118 my $dscfn = "$package.dsc";
1120 open D, ">", $dscfn or die "$dscfn: $!";
1121 print D $dscdata or die "$dscfn: $!";
1122 close D or die "$dscfn: $!";
1123 my @cmd = qw(dpkg-source);
1124 push @cmd, '--no-check' if $dsc_checked;
1125 push @cmd, qw(-x --), $dscfn;
1128 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1129 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1130 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1131 my $authline = clogp_authline $clogp;
1132 my $changes = getfield $clogp, 'Changes';
1133 open C, ">../commit.tmp" or die $!;
1134 print C <<END or die $!;
1141 # imported from the archive
1144 my $outputhash = make_commit qw(../commit.tmp);
1145 my $cversion = getfield $clogp, 'Version';
1146 progress "synthesised git commit from .dsc $cversion";
1147 if ($lastpush_hash) {
1148 runcmd @git, qw(reset --hard), $lastpush_hash;
1149 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1150 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1151 my $oversion = getfield $oldclogp, 'Version';
1153 version_compare($oversion, $cversion);
1155 # git upload/ is earlier vsn than archive, use archive
1156 open C, ">../commit2.tmp" or die $!;
1157 print C <<END or die $!;
1159 parent $lastpush_hash
1164 Record $package ($cversion) in archive suite $csuite
1166 $outputhash = make_commit qw(../commit2.tmp);
1167 } elsif ($vcmp > 0) {
1168 print STDERR <<END or die $!;
1170 Version actually in archive: $cversion (older)
1171 Last allegedly pushed/uploaded: $oversion (newer or same)
1174 $outputhash = $lastpush_hash;
1176 $outputhash = $lastpush_hash;
1179 changedir '../../../..';
1180 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1181 'DGIT_ARCHIVE', $outputhash;
1182 cmdoutput @git, qw(log -n2), $outputhash;
1183 # ... gives git a chance to complain if our commit is malformed
1188 sub complete_file_from_dsc ($$) {
1189 our ($dstdir, $fi) = @_;
1190 # Ensures that we have, in $dir, the file $fi, with the correct
1191 # contents. (Downloading it from alongside $dscurl if necessary.)
1193 my $f = $fi->{Filename};
1194 my $tf = "$dstdir/$f";
1197 if (stat_exists $tf) {
1198 progress "using existing $f";
1201 $furl =~ s{/[^/]+$}{};
1203 die "$f ?" unless $f =~ m/^${package}_/;
1204 die "$f ?" if $f =~ m#/#;
1205 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1206 next if !act_local();
1210 open F, "<", "$tf" or die "$tf: $!";
1211 $fi->{Digester}->reset();
1212 $fi->{Digester}->addfile(*F);
1213 F->error and die $!;
1214 my $got = $fi->{Digester}->hexdigest();
1215 $got eq $fi->{Hash} or
1216 fail "file $f has hash $got but .dsc".
1217 " demands hash $fi->{Hash} ".
1218 ($downloaded ? "(got wrong file from archive!)"
1219 : "(perhaps you should delete this file?)");
1222 sub ensure_we_have_orig () {
1223 foreach my $fi (dsc_files_info()) {
1224 my $f = $fi->{Filename};
1225 next unless is_orig_file($f);
1226 complete_file_from_dsc('..', $fi);
1231 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1234 sub is_fast_fwd ($$) {
1235 my ($ancestor,$child) = @_;
1236 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1237 my $mb = cmdoutput_errok @cmd;
1239 return rev_parse($mb) eq rev_parse($ancestor);
1241 $?==256 or failedcmd @cmd;
1246 sub git_fetch_us () {
1247 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1250 sub fetch_from_archive () {
1251 # ensures that lrref() is what is actually in the archive,
1252 # one way or another
1256 foreach my $field (@ourdscfield) {
1257 $dsc_hash = $dsc->{$field};
1258 last if defined $dsc_hash;
1260 if (defined $dsc_hash) {
1261 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1263 progress "last upload to archive specified git hash";
1265 progress "last upload to archive has NO git hash";
1268 progress "no version available from the archive";
1271 $lastpush_hash = git_get_ref(lrref());
1272 printdebug "previous reference hash=$lastpush_hash\n";
1274 if (defined $dsc_hash) {
1275 fail "missing remote git history even though dsc has hash -".
1276 " could not find ref ".lrref().
1277 " (should have been fetched from ".access_giturl()."#".rrref().")"
1278 unless $lastpush_hash;
1280 ensure_we_have_orig();
1281 if ($dsc_hash eq $lastpush_hash) {
1282 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1283 print STDERR <<END or die $!;
1285 Git commit in archive is behind the last version allegedly pushed/uploaded.
1286 Commit referred to by archive: $dsc_hash
1287 Last allegedly pushed/uploaded: $lastpush_hash
1290 $hash = $lastpush_hash;
1292 fail "archive's .dsc refers to ".$dsc_hash.
1293 " but this is an ancestor of ".$lastpush_hash;
1296 $hash = generate_commit_from_dsc();
1297 } elsif ($lastpush_hash) {
1298 # only in git, not in the archive yet
1299 $hash = $lastpush_hash;
1300 print STDERR <<END or die $!;
1302 Package not found in the archive, but has allegedly been pushed using dgit.
1306 printdebug "nothing found!\n";
1307 if (defined $skew_warning_vsn) {
1308 print STDERR <<END or die $!;
1310 Warning: relevant archive skew detected.
1311 Archive allegedly contains $skew_warning_vsn
1312 But we were not able to obtain any version from the archive or git.
1318 printdebug "current hash=$hash\n";
1319 if ($lastpush_hash) {
1320 fail "not fast forward on last upload branch!".
1321 " (archive's version left in DGIT_ARCHIVE)"
1322 unless is_fast_fwd($lastpush_hash, $hash);
1324 if (defined $skew_warning_vsn) {
1326 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1327 my $clogf = ".git/dgit/changelog.tmp";
1328 runcmd shell_cmd "exec >$clogf",
1329 @git, qw(cat-file blob), "$hash:debian/changelog";
1330 my $gotclogp = parsechangelog("-l$clogf");
1331 my $got_vsn = getfield $gotclogp, 'Version';
1332 printdebug "SKEW CHECK GOT $got_vsn\n";
1333 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1334 print STDERR <<END or die $!;
1336 Warning: archive skew detected. Using the available version:
1337 Archive allegedly contains $skew_warning_vsn
1338 We were able to obtain only $got_vsn
1343 if ($lastpush_hash ne $hash) {
1344 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1348 dryrun_report @upd_cmd;
1356 canonicalise_suite();
1357 badusage "dry run makes no sense with clone" unless act_local();
1358 mkdir $dstdir or die "$dstdir $!";
1360 runcmd @git, qw(init -q);
1361 my $giturl = access_giturl(1);
1362 if (defined $giturl) {
1363 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1364 open H, "> .git/HEAD" or die $!;
1365 print H "ref: ".lref()."\n" or die $!;
1367 runcmd @git, qw(remote add), 'origin', $giturl;
1369 if (check_for_git()) {
1370 progress "fetching existing git history";
1372 runcmd_ordryrun_local @git, qw(fetch origin);
1374 progress "starting new git history";
1376 fetch_from_archive() or no_such_package;
1377 my $vcsgiturl = $dsc->{'Vcs-Git'};
1378 if (length $vcsgiturl) {
1379 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1381 runcmd @git, qw(reset --hard), lrref();
1382 printdone "ready for work in $dstdir";
1386 if (check_for_git()) {
1389 fetch_from_archive() or no_such_package();
1390 printdone "fetched into ".lrref();
1395 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1397 printdone "fetched to ".lrref()." and merged into HEAD";
1400 sub check_not_dirty () {
1401 return if $ignoredirty;
1402 my @cmd = (@git, qw(diff --quiet HEAD));
1403 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1404 $!=0; $?=0; system @cmd;
1405 return if !$! && !$?;
1406 if (!$! && $?==256) {
1407 fail "working tree is dirty (does not match HEAD)";
1413 sub commit_admin ($) {
1416 runcmd_ordryrun_local @git, qw(commit -m), $m;
1419 sub commit_quilty_patch () {
1420 my $output = cmdoutput @git, qw(status --porcelain);
1422 foreach my $l (split /\n/, $output) {
1423 next unless $l =~ m/\S/;
1424 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1428 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1430 progress "nothing quilty to commit, ok.";
1433 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1434 commit_admin "Commit Debian 3.0 (quilt) metadata";
1437 sub get_source_format () {
1438 if (!open F, "debian/source/format") {
1439 die $! unless $!==&ENOENT;
1443 F->error and die $!;
1450 return 0 unless $format eq '3.0 (quilt)';
1452 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1455 progress "Format \`$format', checking/updating patch stack";
1459 sub push_parse_changelog ($) {
1462 my $clogp = Dpkg::Control::Hash->new();
1463 $clogp->load($clogpfn) or die;
1465 $package = getfield $clogp, 'Source';
1466 my $cversion = getfield $clogp, 'Version';
1467 my $tag = debiantag($cversion);
1468 runcmd @git, qw(check-ref-format), $tag;
1470 my $dscfn = dscfn($cversion);
1472 return ($clogp, $cversion, $tag, $dscfn);
1475 sub push_parse_dsc ($$$) {
1476 my ($dscfn,$dscfnwhat, $cversion) = @_;
1477 $dsc = parsecontrol($dscfn,$dscfnwhat);
1478 my $dversion = getfield $dsc, 'Version';
1479 my $dscpackage = getfield $dsc, 'Source';
1480 ($dscpackage eq $package && $dversion eq $cversion) or
1481 fail "$dscfn is for $dscpackage $dversion".
1482 " but debian/changelog is for $package $cversion";
1485 sub push_mktag ($$$$$$$) {
1486 my ($head,$clogp,$tag,
1488 $changesfile,$changesfilewhat,
1491 $dsc->{$ourdscfield[0]} = $head;
1492 $dsc->save("$dscfn.tmp") or die $!;
1494 my $changes = parsecontrol($changesfile,$changesfilewhat);
1495 foreach my $field (qw(Source Distribution Version)) {
1496 $changes->{$field} eq $clogp->{$field} or
1497 fail "changes field $field \`$changes->{$field}'".
1498 " does not match changelog \`$clogp->{$field}'";
1501 my $cversion = getfield $clogp, 'Version';
1502 my $clogsuite = getfield $clogp, 'Distribution';
1504 # We make the git tag by hand because (a) that makes it easier
1505 # to control the "tagger" (b) we can do remote signing
1506 my $authline = clogp_authline $clogp;
1507 open TO, '>', $tfn->('.tmp') or die $!;
1508 print TO <<END or die $!;
1514 $package release $cversion for $clogsuite ($csuite) [dgit]
1518 my $tagobjfn = $tfn->('.tmp');
1520 if (!defined $keyid) {
1521 $keyid = access_cfg('keyid','RETURN-UNDEF');
1523 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1524 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1525 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1526 push @sign_cmd, $tfn->('.tmp');
1527 runcmd_ordryrun @sign_cmd;
1529 $tagobjfn = $tfn->('.signed.tmp');
1530 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1531 $tfn->('.tmp'), $tfn->('.tmp.asc');
1538 sub sign_changes ($) {
1539 my ($changesfile) = @_;
1541 my @debsign_cmd = @debsign;
1542 push @debsign_cmd, "-k$keyid" if defined $keyid;
1543 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1544 push @debsign_cmd, $changesfile;
1545 runcmd_ordryrun @debsign_cmd;
1550 printdebug "actually entering push\n";
1553 access_giturl(); # check that success is vaguely likely
1555 my $clogpfn = ".git/dgit/changelog.822.tmp";
1556 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1558 responder_send_file('parsed-changelog', $clogpfn);
1560 my ($clogp, $cversion, $tag, $dscfn) =
1561 push_parse_changelog("$clogpfn");
1563 my $dscpath = "$buildproductsdir/$dscfn";
1564 stat_exists $dscpath or
1565 fail "looked for .dsc $dscfn, but $!;".
1566 " maybe you forgot to build";
1568 responder_send_file('dsc', $dscpath);
1570 push_parse_dsc($dscpath, $dscfn, $cversion);
1572 my $format = getfield $dsc, 'Format';
1573 printdebug "format $format\n";
1574 if (madformat($format)) {
1575 commit_quilty_patch();
1579 progress "checking that $dscfn corresponds to HEAD";
1580 runcmd qw(dpkg-source -x --),
1581 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1582 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1583 changedir '../../../..';
1584 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1585 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1586 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1588 my $r = system @diffcmd;
1591 fail "$dscfn specifies a different tree to your HEAD commit;".
1592 " perhaps you forgot to build".
1593 ($diffopt eq '--exit-code' ? "" :
1594 " (run with -D to see full diff output)");
1600 #do fast forward check and maybe fake merge
1601 # if (!is_fast_fwd(mainbranch
1602 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1603 # map { lref($_).":".rref($_) }
1605 my $head = rev_parse('HEAD');
1606 if (!$changesfile) {
1607 my $multi = "$buildproductsdir/".
1608 "${package}_".(stripepoch $cversion)."_multi.changes";
1609 if (stat_exists "$multi") {
1610 $changesfile = $multi;
1612 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1613 my @cs = glob "$buildproductsdir/$pat";
1614 fail "failed to find unique changes file".
1615 " (looked for $pat in $buildproductsdir, or $multi);".
1616 " perhaps you need to use dgit -C"
1618 ($changesfile) = @cs;
1621 $changesfile = "$buildproductsdir/$changesfile";
1624 responder_send_file('changes',$changesfile);
1625 responder_send_command("param head $head");
1626 responder_send_command("param csuite $csuite");
1628 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1631 if ($we_are_responder) {
1632 $tagobjfn = $tfn->('.signed.tmp');
1633 responder_receive_files('signed-tag', $tagobjfn);
1636 push_mktag($head,$clogp,$tag,
1638 $changesfile,$changesfile,
1642 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1643 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1644 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1645 runcmd_ordryrun @git, qw(tag -v --), $tag;
1647 if (!check_for_git()) {
1648 create_remote_git_repo();
1650 runcmd_ordryrun @git, qw(push),access_giturl(),
1651 "HEAD:".rrref(), "refs/tags/$tag";
1652 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1654 if ($we_are_responder) {
1655 my $dryrunsuffix = act_local() ? "" : ".tmp";
1656 responder_receive_files('signed-dsc-changes',
1657 "$dscpath$dryrunsuffix",
1658 "$changesfile$dryrunsuffix");
1661 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1663 progress "[new .dsc left in $dscpath.tmp]";
1665 sign_changes $changesfile;
1668 my $host = access_cfg('upload-host','RETURN-UNDEF');
1669 my @hostarg = defined($host) ? ($host,) : ();
1670 runcmd_ordryrun @dput, @hostarg, $changesfile;
1671 printdone "pushed and uploaded $cversion";
1673 responder_send_command("complete");
1679 badusage "-p is not allowed with clone; specify as argument instead"
1680 if defined $package;
1683 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1684 ($package,$isuite) = @ARGV;
1685 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1686 ($package,$dstdir) = @ARGV;
1687 } elsif (@ARGV==3) {
1688 ($package,$isuite,$dstdir) = @ARGV;
1690 badusage "incorrect arguments to dgit clone";
1692 $dstdir ||= "$package";
1694 if (stat_exists $dstdir) {
1695 fail "$dstdir already exists";
1699 if ($rmonerror && !$dryrun_level) {
1700 $cwd_remove= getcwd();
1702 return unless defined $cwd_remove;
1703 if (!chdir "$cwd_remove") {
1704 return if $!==&ENOENT;
1705 die "chdir $cwd_remove: $!";
1707 rmtree($dstdir) or die "remove $dstdir: $!\n";
1712 $cwd_remove = undef;
1715 sub branchsuite () {
1716 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1717 if ($branch =~ m#$lbranch_re#o) {
1724 sub fetchpullargs () {
1725 if (!defined $package) {
1726 my $sourcep = parsecontrol('debian/control','debian/control');
1727 $package = getfield $sourcep, 'Source';
1730 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1732 my $clogp = parsechangelog();
1733 $isuite = getfield $clogp, 'Distribution';
1735 canonicalise_suite();
1736 progress "fetching from suite $csuite";
1737 } elsif (@ARGV==1) {
1739 canonicalise_suite();
1741 badusage "incorrect arguments to dgit fetch or dgit pull";
1759 badusage "-p is not allowed with dgit push" if defined $package;
1761 my $clogp = parsechangelog();
1762 $package = getfield $clogp, 'Source';
1765 } elsif (@ARGV==1) {
1766 ($specsuite) = (@ARGV);
1768 badusage "incorrect arguments to dgit push";
1770 $isuite = getfield $clogp, 'Distribution';
1772 local ($package) = $existing_package; # this is a hack
1773 canonicalise_suite();
1775 if (defined $specsuite && $specsuite ne $isuite) {
1776 canonicalise_suite();
1777 $csuite eq $specsuite or
1778 fail "dgit push: changelog specifies $isuite ($csuite)".
1779 " but command line specifies $specsuite";
1781 if (check_for_git()) {
1784 if (fetch_from_archive()) {
1785 is_fast_fwd(lrref(), 'HEAD') or
1786 fail "dgit push: HEAD is not a descendant".
1787 " of the archive's version.\n".
1788 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1791 fail "package appears to be new in this suite;".
1792 " if this is intentional, use --new";
1797 #---------- remote commands' implementation ----------
1799 sub cmd_remote_push_build_host {
1800 my ($nrargs) = shift @ARGV;
1801 my (@rargs) = @ARGV[0..$nrargs-1];
1802 @ARGV = @ARGV[$nrargs..$#ARGV];
1804 my ($dir,$vsnwant) = @rargs;
1805 # vsnwant is a comma-separated list; we report which we have
1806 # chosen in our ready response (so other end can tell if they
1809 $we_are_responder = 1;
1811 open PI, "<&STDIN" or die $!;
1812 open STDIN, "/dev/null" or die $!;
1813 open PO, ">&STDOUT" or die $!;
1815 open STDOUT, ">&STDERR" or die $!;
1819 fail "build host has dgit rpush protocol version".
1820 " $rpushprotovsn but invocation host has $vsnwant"
1821 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1823 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1829 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1830 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1831 # a good error message)
1837 my $report = i_child_report();
1838 if (defined $report) {
1839 printdebug "($report)\n";
1840 } elsif ($i_child_pid) {
1841 printdebug "(killing build host child $i_child_pid)\n";
1842 kill 15, $i_child_pid;
1844 if (defined $i_tmp && !defined $initiator_tempdir) {
1846 eval { rmtree $i_tmp; };
1850 END { i_cleanup(); }
1853 my ($base,$selector,@args) = @_;
1854 $selector =~ s/\-/_/g;
1855 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1861 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1868 my @rargs = ($dir,$rpushprotovsn);
1871 push @rdgit, @ropts;
1872 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1874 my @cmd = (@ssh, $host, shellquote @rdgit);
1875 printcmd \*DEBUG,$debugprefix."+",@cmd;
1877 if (defined $initiator_tempdir) {
1878 rmtree $initiator_tempdir;
1879 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1880 $i_tmp = $initiator_tempdir;
1884 $i_child_pid = open2(\*RO, \*RI, @cmd);
1886 initiator_expect { m/^dgit-remote-push-ready/ };
1888 my ($icmd,$iargs) = initiator_expect {
1889 m/^(\S+)(?: (.*))?$/;
1892 i_method "i_resp", $icmd, $iargs;
1896 sub i_resp_progress ($) {
1898 my $msg = protocol_read_bytes \*RO, $rhs;
1902 sub i_resp_complete {
1903 my $pid = $i_child_pid;
1904 $i_child_pid = undef; # prevents killing some other process with same pid
1905 printdebug "waiting for build host child $pid...\n";
1906 my $got = waitpid $pid, 0;
1907 die $! unless $got == $pid;
1908 die "build host child failed $?" if $?;
1911 printdebug "all done\n";
1915 sub i_resp_file ($) {
1917 my $localname = i_method "i_localname", $keyword;
1918 my $localpath = "$i_tmp/$localname";
1919 stat_exists $localpath and
1920 badproto \*RO, "file $keyword ($localpath) twice";
1921 protocol_receive_file \*RO, $localpath;
1922 i_method "i_file", $keyword;
1927 sub i_resp_param ($) {
1928 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1934 sub i_resp_want ($) {
1936 die "$keyword ?" if $i_wanted{$keyword}++;
1937 my @localpaths = i_method "i_want", $keyword;
1938 printdebug "[[ $keyword @localpaths\n";
1939 foreach my $localpath (@localpaths) {
1940 protocol_send_file \*RI, $localpath;
1942 print RI "files-end\n" or die $!;
1945 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1947 sub i_localname_parsed_changelog {
1948 return "remote-changelog.822";
1950 sub i_file_parsed_changelog {
1951 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1952 push_parse_changelog "$i_tmp/remote-changelog.822";
1953 die if $i_dscfn =~ m#/|^\W#;
1956 sub i_localname_dsc {
1957 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1962 sub i_localname_changes {
1963 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1964 $i_changesfn = $i_dscfn;
1965 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1966 return $i_changesfn;
1968 sub i_file_changes { }
1970 sub i_want_signed_tag {
1971 printdebug Dumper(\%i_param, $i_dscfn);
1972 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1973 && defined $i_param{'csuite'}
1974 or badproto \*RO, "premature desire for signed-tag";
1975 my $head = $i_param{'head'};
1976 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1978 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
1980 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
1983 push_mktag $head, $i_clogp, $i_tag,
1985 $i_changesfn, 'remote changes',
1986 sub { "tag$_[0]"; };
1991 sub i_want_signed_dsc_changes {
1992 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1993 sign_changes $i_changesfn;
1994 return ($i_dscfn, $i_changesfn);
1997 #---------- building etc. ----------
2003 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2005 sub build_maybe_quilt_fixup () {
2006 my $format=get_source_format;
2007 return unless madformat $format;
2011 # - honour any existing .pc in case it has any strangeness
2012 # - determine the git commit corresponding to the tip of
2013 # the patch stack (if there is one)
2014 # - if there is such a git commit, convert each subsequent
2015 # git commit into a quilt patch with dpkg-source --commit
2016 # - otherwise convert all the differences in the tree into
2017 # a single git commit
2021 # Our git tree doesn't necessarily contain .pc. (Some versions of
2022 # dgit would include the .pc in the git tree.) If there isn't
2023 # one, we need to generate one by unpacking the patches that we
2026 # We first look for a .pc in the git tree. If there is one, we
2027 # will use it. (This is not the normal case.)
2029 # Otherwise need to regenerate .pc so that dpkg-source --commit
2030 # can work. We do this as follows:
2031 # 1. Collect all relevant .orig from parent directory
2032 # 2. Generate a debian.tar.gz out of
2033 # debian/{patches,rules,source/format}
2034 # 3. Generate a fake .dsc containing just these fields:
2035 # Format Source Version Files
2036 # 4. Extract the fake .dsc
2037 # Now the fake .dsc has a .pc directory.
2038 # (In fact we do this in every case, because in future we will
2039 # want to search for a good base commit for generating patches.)
2041 # Then we can actually do the dpkg-source --commit
2042 # 1. Make a new working tree with the same object
2043 # store as our main tree and check out the main
2045 # 2. Copy .pc from the fake's extraction, if necessary
2046 # 3. Run dpkg-source --commit
2047 # 4. If the result has changes to debian/, then
2048 # - git-add them them
2049 # - git-add .pc if we had a .pc in-tree
2051 # 5. If we had a .pc in-tree, delete it, and git-commit
2052 # 6. Back in the main tree, fast forward to the new HEAD
2054 my $clogp = parsechangelog();
2055 my $headref = rev_parse('HEAD');
2060 my $upstreamversion=$version;
2061 $upstreamversion =~ s/-[^-]*$//;
2063 my $fakeversion="$upstreamversion-~~DGITFAKE";
2065 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2066 print $fakedsc <<END or die $!;
2069 Version: $fakeversion
2073 my $dscaddfile=sub {
2076 my $md = new Digest::MD5;
2078 my $fh = new IO::File $b, '<' or die "$b $!";
2083 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2086 foreach my $f (<../../../../*>) { #/){
2087 my $b=$f; $b =~ s{.*/}{};
2088 next unless is_orig_file $b, srcfn $upstreamversion,'';
2089 link $f, $b or die "$b $!";
2093 my @files=qw(debian/source/format debian/rules);
2094 if (stat_exists '../../../debian/patches') {
2095 push @files, 'debian/patches';
2098 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2099 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2101 $dscaddfile->($debtar);
2102 close $fakedsc or die $!;
2104 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2106 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2107 rename $fakexdir, "fake" or die "$fakexdir $!";
2109 mkdir "work" or die $!;
2111 mktree_in_ud_here();
2112 runcmd @git, qw(reset --hard), $headref;
2115 if (stat_exists ".pc") {
2117 progress "Tree already contains .pc - will use it then delete it.";
2120 rename '../fake/.pc','.pc' or die $!;
2123 my $author = getfield $clogp, 'Maintainer';
2126 my $patchname = "auto-$version-$headref-$time";
2127 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2129 my $descfn = ".git/dgit/quilt-description.tmp";
2130 open O, '>', $descfn or die "$descfn: $!";
2132 $msg =~ s/^\s+$/ ./mg;
2133 print O <<END or die $!;
2134 Description: Automatically generated patch ($clogp->{Version})
2135 Last (up to) $ncommits git changes, FYI:
2145 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2146 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2147 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2148 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2151 if (!open P, '>>', ".pc/applied-patches") {
2152 $!==&ENOENT or die $!;
2157 commit_quilty_patch();
2159 if ($mustdeletepc) {
2160 runcmd @git, qw(rm -rq .pc);
2161 commit_admin "Commit removal of .pc (quilt series tracking data)";
2164 changedir '../../../..';
2165 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2168 sub quilt_fixup_editor () {
2169 my $descfn = $ENV{$fakeeditorenv};
2170 my $editing = $ARGV[$#ARGV];
2171 open I1, '<', $descfn or die "$descfn: $!";
2172 open I2, '<', $editing or die "$editing: $!";
2173 unlink $editing or die "$editing: $!";
2174 open O, '>', $editing or die "$editing: $!";
2175 while (<I1>) { print O or die $!; } I1->error and die $!;
2178 $copying ||= m/^\-\-\- /;
2179 next unless $copying;
2182 I2->error and die $!;
2188 if ($cleanmode eq 'dpkg-source') {
2189 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2190 } elsif ($cleanmode eq 'git') {
2191 runcmd_ordryrun_local @git, qw(clean -xdf);
2192 } elsif ($cleanmode eq 'none') {
2199 badusage "clean takes no additional arguments" if @ARGV;
2204 badusage "-p is not allowed when building" if defined $package;
2207 my $clogp = parsechangelog();
2208 $isuite = getfield $clogp, 'Distribution';
2209 $package = getfield $clogp, 'Source';
2210 $version = getfield $clogp, 'Version';
2211 build_maybe_quilt_fixup();
2214 sub changesopts () {
2215 my @opts =@changesopts[1..$#changesopts];
2216 if (!defined $changes_since_version) {
2217 my @vsns = archive_query('archive_query');
2218 my @quirk = access_quirk();
2219 if ($quirk[0] eq 'backports') {
2220 local $isuite = $quirk[2];
2222 canonicalise_suite();
2223 push @vsns, archive_query('archive_query');
2226 @vsns = map { $_->[0] } @vsns;
2227 @vsns = sort { -version_compare($a, $b) } @vsns;
2228 $changes_since_version = $vsns[0];
2229 progress "changelog will contain changes since $vsns[0]";
2231 $changes_since_version = '_';
2232 progress "package seems new, not specifying -v<version>";
2235 if ($changes_since_version ne '_') {
2236 unshift @opts, "-v$changes_since_version";
2243 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2244 printdone "build successful\n";
2250 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2251 "--git-builder=@dpkgbuildpackage");
2252 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2253 canonicalise_suite();
2254 push @cmd, "--git-debian-branch=".lbranch();
2256 push @cmd, changesopts();
2257 runcmd_ordryrun_local @cmd, @ARGV;
2258 printdone "build successful\n";
2263 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2264 $dscfn = dscfn($version);
2265 if ($cleanmode eq 'dpkg-source') {
2266 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2269 my $pwd = must_getcwd();
2270 my $leafdir = basename $pwd;
2272 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2274 runcmd_ordryrun_local qw(sh -ec),
2275 'exec >$1; shift; exec "$@"','x',
2276 "../$sourcechanges",
2277 @dpkggenchanges, qw(-S), changesopts();
2281 sub cmd_build_source {
2282 badusage "build-source takes no additional arguments" if @ARGV;
2284 printdone "source built, results in $dscfn and $sourcechanges";
2290 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2292 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2293 stat_exists $sourcechanges
2294 or fail "$sourcechanges (in parent directory): $!";
2295 foreach my $cf (glob $pat) {
2296 next if $cf eq $sourcechanges;
2297 unlink $cf or fail "remove $cf: $!";
2300 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2301 my @changesfiles = glob $pat;
2302 @changesfiles = sort {
2303 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2306 fail "wrong number of different changes files (@changesfiles)"
2307 unless @changesfiles;
2308 runcmd_ordryrun_local @mergechanges, @changesfiles;
2309 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2311 stat_exists $multichanges or fail "$multichanges: $!";
2313 printdone "build successful, results in $multichanges\n" or die $!;
2316 sub cmd_quilt_fixup {
2317 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2318 my $clogp = parsechangelog();
2319 $version = getfield $clogp, 'Version';
2320 $package = getfield $clogp, 'Source';
2321 build_maybe_quilt_fixup();
2324 #---------- argument parsing and main program ----------
2327 print "dgit version $our_version\n" or die $!;
2334 if (defined $ENV{'DGIT_SSH'}) {
2335 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2336 } elsif (defined $ENV{'GIT_SSH'}) {
2337 @ssh = ($ENV{'GIT_SSH'});
2341 last unless $ARGV[0] =~ m/^-/;
2345 if (m/^--dry-run$/) {
2348 } elsif (m/^--damp-run$/) {
2351 } elsif (m/^--no-sign$/) {
2354 } elsif (m/^--help$/) {
2356 } elsif (m/^--version$/) {
2358 } elsif (m/^--new$/) {
2361 } elsif (m/^--since-version=([^_]+|_)$/) {
2363 $changes_since_version = $1;
2364 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2365 ($om = $opts_opt_map{$1}) &&
2369 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2370 !$opts_opt_cmdonly{$1} &&
2371 ($om = $opts_opt_map{$1})) {
2374 } elsif (m/^--existing-package=(.*)/s) {
2376 $existing_package = $1;
2377 } elsif (m/^--initiator-tempdir=(.*)/s) {
2378 $initiator_tempdir = $1;
2379 $initiator_tempdir =~ m#^/# or
2380 badusage "--initiator-tempdir must be used specify an".
2381 " absolute, not relative, directory."
2382 } elsif (m/^--distro=(.*)/s) {
2385 } elsif (m/^--build-products-dir=(.*)/s) {
2387 $buildproductsdir = $1;
2388 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2391 } elsif (m/^--clean=(.*)$/s) {
2392 badusage "unknown cleaning mode \`$1'";
2393 } elsif (m/^--ignore-dirty$/s) {
2396 } elsif (m/^--no-quilt-fixup$/s) {
2399 } elsif (m/^--no-rm-on-error$/s) {
2403 badusage "unknown long option \`$_'";
2410 } elsif (s/^-L/-/) {
2413 } elsif (s/^-h/-/) {
2415 } elsif (s/^-D/-/) {
2417 open DEBUG, ">&STDERR" or die $!;
2420 } elsif (s/^-N/-/) {
2423 } elsif (s/^-v([^_]+|_)$//s) {
2425 $changes_since_version = $1;
2428 push @changesopts, $_;
2430 } elsif (s/^-c(.*=.*)//s) {
2432 push @git, '-c', $1;
2433 } elsif (s/^-d(.*)//s) {
2436 } elsif (s/^-C(.*)//s) {
2439 if ($changesfile =~ s#^(.*)/##) {
2440 $buildproductsdir = $1;
2442 } elsif (s/^-k(.*)//s) {
2444 } elsif (s/^-wn//s) {
2446 $cleanmode = 'none';
2447 } elsif (s/^-wg//s) {
2450 } elsif (s/^-wd//s) {
2452 $cleanmode = 'dpkg-source';
2454 badusage "unknown short option \`$_'";
2461 if ($ENV{$fakeeditorenv}) {
2462 quilt_fixup_editor();
2466 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2467 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2468 if $dryrun_level == 1;
2470 print STDERR $helpmsg or die $!;
2473 my $cmd = shift @ARGV;
2476 my $fn = ${*::}{"cmd_$cmd"};
2477 $fn or badusage "unknown operation $cmd";