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';
107 sub lbranch () { return "$branchprefix/$csuite"; }
108 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
109 sub lref () { return "refs/heads/".lbranch(); }
110 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
111 sub rrref () { return "refs/$branchprefix/$csuite"; }
126 return "${package}_".(stripepoch $vsn).$sfx
131 return srcfn($vsn,".dsc");
135 our $debugprefix = '';
140 foreach my $f (@end) {
142 warn "$us: cleanup: $@" if length $@;
146 our @signames = split / /, $Config{sig_name};
148 sub waitstatusmsg () {
150 return "terminated, reporting successful completion";
151 } elsif (!($? & 255)) {
152 return "failed with error exit status ".WEXITSTATUS($?);
153 } elsif (WIFSIGNALED($?)) {
154 my $signum=WTERMSIG($?);
155 return "died due to fatal signal ".
156 ($signames[$signum] // "number $signum").
157 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
159 return "failed with unknown wait status ".$?;
163 sub printdebug { print DEBUG $debugprefix, @_ or die $!; }
166 die $us.($we_are_responder ? " (build host)" : "").": @_\n";
169 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
171 sub no_such_package () {
172 print STDERR "$us: package $package does not exist in suite $isuite\n";
178 return "+".rrref().":".lrref();
183 printdebug "CD $newdir\n";
184 chdir $newdir or die "chdir: $newdir: $!";
187 sub stat_exists ($) {
190 return 0 if $!==&ENOENT;
194 #---------- remote protocol support, common ----------
196 # remote push initiator/responder protocol:
197 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
199 # > file parsed-changelog
200 # [indicates that output of dpkg-parsechangelog follows]
201 # > data-block NBYTES
202 # > [NBYTES bytes of data (no newline)]
203 # [maybe some more blocks]
215 # [indicates that signed tag is wanted]
216 # < data-block NBYTES
217 # < [NBYTES bytes of data (no newline)]
218 # [maybe some more blocks]
222 # > want signed-dsc-changes
223 # < data-block NBYTES [transfer of signed dsc]
225 # < data-block NBYTES [transfer of signed changes]
233 sub i_child_report () {
234 # Sees if our child has died, and reap it if so. Returns a string
235 # describing how it died if it failed, or undef otherwise.
236 return undef unless $i_child_pid;
237 my $got = waitpid $i_child_pid, WNOHANG;
238 return undef if $got <= 0;
239 die unless $got == $i_child_pid;
240 $i_child_pid = undef;
241 return undef unless $?;
242 return "build host child ".waitstatusmsg();
247 fail "connection lost: $!" if $fh->error;
248 fail "protocol violation; $m not expected";
251 sub badproto_badread ($$) {
253 fail "connection lost: $!" if $!;
254 my $report = i_child_report();
255 fail $report if defined $report;
256 badproto $fh, "eof (reading $wh)";
259 sub protocol_expect (&$) {
260 my ($match, $fh) = @_;
263 defined && chomp or badproto_badread $fh, "protocol message";
271 badproto $fh, "\`$_'";
274 sub protocol_send_file ($$) {
275 my ($fh, $ourfn) = @_;
276 open PF, "<", $ourfn or die "$ourfn: $!";
279 my $got = read PF, $d, 65536;
280 die "$ourfn: $!" unless defined $got;
282 print $fh "data-block ".length($d)."\n" or die $!;
283 print $fh $d or die $!;
285 PF->error and die "$ourfn $!";
286 print $fh "data-end\n" or die $!;
290 sub protocol_read_bytes ($$) {
291 my ($fh, $nbytes) = @_;
292 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
294 my $got = read $fh, $d, $nbytes;
295 $got==$nbytes or badproto_badread $fh, "data block";
299 sub protocol_receive_file ($$) {
300 my ($fh, $ourfn) = @_;
301 printdebug "() $ourfn\n";
302 open PF, ">", $ourfn or die "$ourfn: $!";
304 my ($y,$l) = protocol_expect {
305 m/^data-block (.*)$/ ? (1,$1) :
306 m/^data-end$/ ? (0,) :
310 my $d = protocol_read_bytes $fh, $l;
311 print PF $d or die $!;
316 #---------- remote protocol support, responder ----------
318 sub responder_send_command ($) {
320 return unless $we_are_responder;
321 # called even without $we_are_responder
322 printdebug ">> $command\n";
323 print PO $command, "\n" or die $!;
326 sub responder_send_file ($$) {
327 my ($keyword, $ourfn) = @_;
328 return unless $we_are_responder;
329 printdebug "]] $keyword $ourfn\n";
330 responder_send_command "file $keyword";
331 protocol_send_file \*PO, $ourfn;
334 sub responder_receive_files ($@) {
335 my ($keyword, @ourfns) = @_;
336 die unless $we_are_responder;
337 printdebug "[[ $keyword @ourfns\n";
338 responder_send_command "want $keyword";
339 foreach my $fn (@ourfns) {
340 protocol_receive_file \*PI, $fn;
343 protocol_expect { m/^files-end$/ } \*PI;
346 #---------- remote protocol support, initiator ----------
348 sub initiator_expect (&) {
350 protocol_expect { &$match } \*RO;
353 #---------- end remote code ----------
356 if ($we_are_responder) {
358 responder_send_command "progress ".length($m) or die $!;
359 print PO $m or die $!;
369 $ua = LWP::UserAgent->new();
373 progress "downloading $what...";
374 my $r = $ua->get(@_) or die $!;
375 return undef if $r->code == 404;
376 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
377 return $r->decoded_content(charset => 'none');
380 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
387 if (m{[^-=_./0-9a-z]}i) {
394 return join ' ', @out;
399 my $intro = shift @_;
400 print $fh $intro," " or die $!;
401 print $fh shellquote @_ or die $!;
402 print $fh "\n" or die $!;
406 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
408 fail "failed to fork/exec: $!";
410 fail "subprocess ".waitstatusmsg();
412 fail "subprocess produced invalid output";
417 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
419 failedcmd @_ if system @_;
422 sub act_local () { return $dryrun_level <= 1; }
423 sub act_scary () { return !$dryrun_level; }
426 if (!$dryrun_level) {
427 progress "dgit ok: @_";
429 progress "would be ok: @_ (but dry run only)";
433 sub cmdoutput_errok {
434 die Dumper(\@_)." ?" if grep { !defined } @_;
435 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
436 open P, "-|", @_ or die $!;
439 { local $/ = undef; $d = <P>; }
441 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
444 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
449 my $d = cmdoutput_errok @_;
450 defined $d or failedcmd @_;
455 printcmd(\*STDERR,$debugprefix."#",@_);
458 sub runcmd_ordryrun {
466 sub runcmd_ordryrun_local {
475 my ($first_shell, @cmd) = @_;
476 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
479 our $helpmsg = <<END;
481 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
482 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
483 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
484 dgit [dgit-opts] push [dgit-opts] [suite]
485 dgit [dgit-opts] rpush build-host:build-dir ...
486 important dgit options:
487 -k<keyid> sign tag and package with <keyid> instead of default
488 --dry-run -n do not change anything, but go through the motions
489 --damp-run -L like --dry-run but make local changes, without signing
490 --new -N allow introducing a new package
491 --debug -D increase debug level
492 -c<name>=<value> set git config option (used directly by dgit too)
495 our $later_warning_msg = <<END;
496 Perhaps the upload is stuck in incoming. Using the version from git.
500 print STDERR "$us: @_\n", $helpmsg or die $!;
505 @ARGV or badusage "too few arguments";
506 return scalar shift @ARGV;
510 print $helpmsg or die $!;
514 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
516 our %defcfg = ('dgit.default.distro' => 'debian',
517 'dgit.default.username' => '',
518 'dgit.default.archive-query-default-component' => 'main',
519 'dgit.default.ssh' => 'ssh',
520 'dgit.default.archive-query' => 'madison:',
521 'dgit.default.sshpsql-dbname' => 'service=projectb',
522 'dgit-distro.debian.archive-query' => 'sshpsql:',
523 'dgit-distro.debian.git-host' => 'git.debian.org',
524 'dgit-distro.debian.git-proto' => 'git+ssh://',
525 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
526 'dgit-distro.debian.git-check' => 'ssh-cmd',
527 'dgit-distro.debian.git-create' => 'ssh-cmd',
528 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
529 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
530 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
531 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
532 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
533 'dgit-distro.ubuntu.git-check' => 'false',
534 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
535 'dgit-distro.test-dummy.ssh' => "$td/ssh",
536 'dgit-distro.test-dummy.username' => "alice",
537 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
538 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
539 'dgit-distro.test-dummy.git-url' => "$td/git",
540 'dgit-distro.test-dummy.git-host' => "git",
541 'dgit-distro.test-dummy.git-path' => "$td/git",
542 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
543 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
544 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
549 return undef if $c =~ /RETURN-UNDEF/;
550 my @cmd = (@git, qw(config --), $c);
553 local ($debug) = $debug-1;
554 $v = cmdoutput_errok @cmd;
561 my $dv = $defcfg{$c};
562 return $dv if defined $dv;
564 badcfg "need value for one of: @_\n".
565 "$us: distro or suite appears not to be (properly) supported";
568 sub access_basedistro () {
569 if (defined $idistro) {
572 return cfg("dgit-suite.$isuite.distro",
573 "dgit.default.distro");
577 sub access_quirk () {
578 # returns (quirk name, distro to use instead or undef, quirk-specific info)
579 my $basedistro = access_basedistro();
580 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
582 if (defined $backports_quirk) {
583 my $re = $backports_quirk;
584 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
586 $re =~ s/\%/([-0-9a-z_]+)/
587 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
588 if ($isuite =~ m/^$re$/) {
589 return ('backports',"$basedistro-backports",$1);
592 return ('none',undef);
595 sub access_distros () {
596 # Returns list of distros to try, in order
599 # 0. `instead of' distro name(s) we have been pointed to
600 # 1. the access_quirk distro, if any
601 # 2a. the user's specified distro, or failing that } basedistro
602 # 2b. the distro calculated from the suite }
603 my @l = access_basedistro();
605 my (undef,$quirkdistro) = access_quirk();
606 unshift @l, $quirkdistro;
607 unshift @l, $instead_distro;
608 return grep { defined } @l;
614 # The nesting of these loops determines the search order. We put
615 # the key loop on the outside so that we search all the distros
616 # for each key, before going on to the next key. That means that
617 # if access_cfg is called with a more specific, and then a less
618 # specific, key, an earlier distro can override the less specific
619 # without necessarily overriding any more specific keys. (If the
620 # distro wants to override the more specific keys it can simply do
621 # so; whereas if we did the loop the other way around, it would be
622 # impossible to for an earlier distro to override a less specific
623 # key but not the more specific ones without restating the unknown
624 # values of the more specific keys.
627 # We have to deal with RETURN-UNDEF specially, so that we don't
628 # terminate the search prematurely.
630 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
633 foreach my $d (access_distros()) {
634 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
636 push @cfgs, map { "dgit.default.$_" } @realkeys;
638 my $value = cfg(@cfgs);
642 sub string_to_ssh ($) {
644 if ($spec =~ m/\s/) {
645 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
651 sub access_cfg_ssh () {
652 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
653 if (!defined $gitssh) {
656 return string_to_ssh $gitssh;
660 sub access_runeinfo ($) {
662 return ": dgit ".access_basedistro()." $info ;";
665 sub access_someuserhost ($) {
667 my $user = access_cfg("$some-user",'username');
668 my $host = access_cfg("$some-host");
669 return length($user) ? "$user\@$host" : $host;
672 sub access_gituserhost () {
673 return access_someuserhost('git');
676 sub access_giturl (;$) {
678 my $url = access_cfg('git-url','RETURN-UNDEF');
680 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
681 return undef unless defined $proto;
684 access_gituserhost().
685 access_cfg('git-path');
687 return "$url/$package.git";
690 sub parsecontrolfh ($$;$) {
691 my ($fh, $desc, $allowsigned) = @_;
692 our $dpkgcontrolhash_noissigned;
695 my %opts = ('name' => $desc);
696 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
697 $c = Dpkg::Control::Hash->new(%opts);
698 $c->parse($fh,$desc) or die "parsing of $desc failed";
699 last if $allowsigned;
700 last if $dpkgcontrolhash_noissigned;
701 my $issigned= $c->get_option('is_pgp_signed');
702 if (!defined $issigned) {
703 $dpkgcontrolhash_noissigned= 1;
704 seek $fh, 0,0 or die "seek $desc: $!";
705 } elsif ($issigned) {
706 fail "control file $desc is (already) PGP-signed. ".
707 " Note that dgit push needs to modify the .dsc and then".
708 " do the signature itself";
717 my ($file, $desc) = @_;
718 my $fh = new IO::Handle;
719 open $fh, '<', $file or die "$file: $!";
720 my $c = parsecontrolfh($fh,$desc);
721 $fh->error and die $!;
727 my ($dctrl,$field) = @_;
728 my $v = $dctrl->{$field};
729 return $v if defined $v;
730 fail "missing field $field in ".$v->get_option('name');
734 my $c = Dpkg::Control::Hash->new();
735 my $p = new IO::Handle;
736 my @cmd = (qw(dpkg-parsechangelog), @_);
737 open $p, '-|', @cmd or die $!;
739 $?=0; $!=0; close $p or failedcmd @cmd;
743 sub git_get_ref ($) {
745 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
747 $?==256 or fail "git show-ref failed (status $?)";
748 printdebug "ref $refname= [show-ref exited 1]\n";
751 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
752 printdebug "ref $refname=$1\n";
755 printdebug "ref $refname= [no match]\n";
762 defined $d or fail "getcwd failed: $!";
768 sub archive_query ($) {
770 my $query = access_cfg('archive-query','RETURN-UNDEF');
771 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
774 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
777 sub pool_dsc_subpath ($$) {
778 my ($vsn,$component) = @_; # $package is implict arg
779 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
780 return "/pool/$component/$prefix/$package/".dscfn($vsn);
783 sub archive_query_madison {
784 return map { [ @$_[0..1] ] } madison_get_parse(@_);
787 sub madison_get_parse {
788 my ($proto,$data) = @_;
789 die unless $proto eq 'madison';
791 $data= access_cfg('madison-distro','RETURN-UNDEF');
792 $data //= access_basedistro();
794 $rmad{$proto,$data,$package} ||= cmdoutput
795 qw(rmadison -asource),"-s$isuite","-u$data",$package;
796 my $rmad = $rmad{$proto,$data,$package};
799 foreach my $l (split /\n/, $rmad) {
800 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
801 \s*( [^ \t|]+ )\s* \|
802 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
803 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
804 $1 eq $package or die "$rmad $package ?";
811 $component = access_cfg('archive-query-default-component');
813 $5 eq 'source' or die "$rmad ?";
814 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
816 return sort { -version_compare($a->[0],$b->[0]); } @out;
819 sub canonicalise_suite_madison {
820 # madison canonicalises for us
821 my @r = madison_get_parse(@_);
823 "unable to canonicalise suite using package $package".
824 " which does not appear to exist in suite $isuite;".
825 " --existing-package may help";
830 my ($data,$runeinfo,$sql) = @_;
832 $data= access_someuserhost('sshpsql').':'.
833 access_cfg('sshpsql-dbname');
835 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
836 my ($userhost,$dbname) = ($`,$'); #';
838 my @cmd = (access_cfg_ssh, $userhost,
839 access_runeinfo("ssh-psql $runeinfo").
841 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
842 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
843 open P, "-|", @cmd or die $!;
846 printdebug("$debugprefix>|$_|\n");
849 $!=0; $?=0; close P or failedcmd @cmd;
851 my $nrows = pop @rows;
852 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
853 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
854 @rows = map { [ split /\|/, $_ ] } @rows;
855 my $ncols = scalar @{ shift @rows };
856 die if grep { scalar @$_ != $ncols } @rows;
860 sub sql_injection_check {
861 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
864 sub archive_query_sshpsql ($$) {
865 my ($proto,$data) = @_;
866 sql_injection_check $isuite, $package;
867 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
868 SELECT source.version, component.name, files.filename, files.sha256sum
870 JOIN src_associations ON source.id = src_associations.source
871 JOIN suite ON suite.id = src_associations.suite
872 JOIN dsc_files ON dsc_files.source = source.id
873 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
874 JOIN component ON component.id = files_archive_map.component_id
875 JOIN files ON files.id = dsc_files.file
876 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
877 AND source.source='$package'
878 AND files.filename LIKE '%.dsc';
880 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
881 my $digester = Digest::SHA->new(256);
883 my ($vsn,$component,$filename,$sha256sum) = @$_;
884 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
889 sub canonicalise_suite_sshpsql ($$) {
890 my ($proto,$data) = @_;
891 sql_injection_check $isuite;
892 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
893 SELECT suite.codename
894 FROM suite where suite_name='$isuite' or codename='$isuite';
896 @rows = map { $_->[0] } @rows;
897 fail "unknown suite $isuite" unless @rows;
898 die "ambiguous $isuite: @rows ?" if @rows>1;
902 sub canonicalise_suite_dummycat ($$) {
903 my ($proto,$data) = @_;
904 my $dpath = "$data/suite.$isuite";
905 if (!open C, "<", $dpath) {
906 $!==ENOENT or die "$dpath: $!";
907 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
911 chomp or die "$dpath: $!";
913 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
917 sub archive_query_dummycat ($$) {
918 my ($proto,$data) = @_;
919 canonicalise_suite();
920 my $dpath = "$data/package.$csuite.$package";
921 if (!open C, "<", $dpath) {
922 $!==ENOENT or die "$dpath: $!";
923 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
931 printdebug "dummycat query $csuite $package $dpath | $_\n";
932 my @row = split /\s+/, $_;
933 @row==2 or die "$dpath: $_ ?";
936 C->error and die "$dpath: $!";
938 return sort { -version_compare($a->[0],$b->[0]); } @rows;
941 sub canonicalise_suite () {
942 return if defined $csuite;
943 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
944 $csuite = archive_query('canonicalise_suite');
945 if ($isuite ne $csuite) {
946 progress "canonical suite name for $isuite is $csuite";
950 sub get_archive_dsc () {
951 canonicalise_suite();
952 my @vsns = archive_query('archive_query');
953 foreach my $vinfo (@vsns) {
954 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
955 $dscurl = access_cfg('mirror').$subpath;
956 $dscdata = url_get($dscurl);
958 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
963 $digester->add($dscdata);
964 my $got = $digester->hexdigest();
966 fail "$dscurl has hash $got but".
967 " archive told us to expect $digest";
969 my $dscfh = new IO::File \$dscdata, '<' or die $!;
970 printdebug Dumper($dscdata) if $debug>1;
971 $dsc = parsecontrolfh($dscfh,$dscurl,1);
972 printdebug Dumper($dsc) if $debug>1;
973 my $fmt = getfield $dsc, 'Format';
974 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
975 $dsc_checked = !!$digester;
981 sub check_for_git ();
982 sub check_for_git () {
984 my $how = access_cfg('git-check');
985 if ($how eq 'ssh-cmd') {
987 (access_cfg_ssh, access_gituserhost(),
988 access_runeinfo("git-check $package").
989 " set -e; cd ".access_cfg('git-path').";".
990 " if test -d $package.git; then echo 1; else echo 0; fi");
991 my $r= cmdoutput @cmd;
992 if ($r =~ m/^divert (\w+)$/) {
994 my ($usedistro,) = access_distros();
995 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
996 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
997 printdebug "diverting $divert so using distro $instead_distro\n";
998 return check_for_git();
1000 failedcmd @cmd unless $r =~ m/^[01]$/;
1002 } elsif ($how eq 'true') {
1004 } elsif ($how eq 'false') {
1007 badcfg "unknown git-check \`$how'";
1011 sub create_remote_git_repo () {
1012 my $how = access_cfg('git-create');
1013 if ($how eq 'ssh-cmd') {
1015 (access_cfg_ssh, access_gituserhost(),
1016 access_runeinfo("git-create $package").
1017 "set -e; cd ".access_cfg('git-path').";".
1018 " cp -a _template $package.git");
1019 } elsif ($how eq 'true') {
1022 badcfg "unknown git-create \`$how'";
1026 our ($dsc_hash,$lastpush_hash);
1028 our $ud = '.git/dgit/unpack';
1033 mkdir $ud or die $!;
1036 sub mktree_in_ud_here () {
1037 runcmd qw(git init -q);
1038 rmtree('.git/objects');
1039 symlink '../../../../objects','.git/objects' or die $!;
1042 sub mktree_in_ud_from_only_subdir () {
1043 # changes into the subdir
1045 die unless @dirs==1;
1046 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1049 fail "source package contains .git directory" if stat_exists '.git';
1050 mktree_in_ud_here();
1051 my $format=get_source_format();
1052 if (madformat($format)) {
1055 runcmd @git, qw(add -Af);
1056 my $tree = cmdoutput @git, qw(write-tree);
1057 $tree =~ m/^\w+$/ or die "$tree ?";
1058 return ($tree,$dir);
1061 sub dsc_files_info () {
1062 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1063 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1064 ['Files', 'Digest::MD5', 'new()']) {
1065 my ($fname, $module, $method) = @$csumi;
1066 my $field = $dsc->{$fname};
1067 next unless defined $field;
1068 eval "use $module; 1;" or die $@;
1070 foreach (split /\n/, $field) {
1072 m/^(\w+) (\d+) (\S+)$/ or
1073 fail "could not parse .dsc $fname line \`$_'";
1074 my $digester = eval "$module"."->$method;" or die $@;
1079 Digester => $digester,
1084 fail "missing any supported Checksums-* or Files field in ".
1085 $dsc->get_option('name');
1089 map { $_->{Filename} } dsc_files_info();
1092 sub is_orig_file ($;$) {
1095 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1096 defined $base or return 1;
1100 sub make_commit ($) {
1102 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1105 sub clogp_authline ($) {
1107 my $author = getfield $clogp, 'Maintainer';
1108 $author =~ s#,.*##ms;
1109 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1110 my $authline = "$author $date";
1111 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1112 fail "unexpected commit author line format \`$authline'".
1113 " (was generated from changelog Maintainer field)";
1117 sub generate_commit_from_dsc () {
1121 foreach my $fi (dsc_files_info()) {
1122 my $f = $fi->{Filename};
1123 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1125 link "../../../$f", $f
1129 complete_file_from_dsc('.', $fi);
1131 if (is_orig_file($f)) {
1132 link $f, "../../../../$f"
1138 my $dscfn = "$package.dsc";
1140 open D, ">", $dscfn or die "$dscfn: $!";
1141 print D $dscdata or die "$dscfn: $!";
1142 close D or die "$dscfn: $!";
1143 my @cmd = qw(dpkg-source);
1144 push @cmd, '--no-check' if $dsc_checked;
1145 push @cmd, qw(-x --), $dscfn;
1148 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1149 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1150 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1151 my $authline = clogp_authline $clogp;
1152 my $changes = getfield $clogp, 'Changes';
1153 open C, ">../commit.tmp" or die $!;
1154 print C <<END or die $!;
1161 # imported from the archive
1164 my $outputhash = make_commit qw(../commit.tmp);
1165 my $cversion = getfield $clogp, 'Version';
1166 progress "synthesised git commit from .dsc $cversion";
1167 if ($lastpush_hash) {
1168 runcmd @git, qw(reset --hard), $lastpush_hash;
1169 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1170 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1171 my $oversion = getfield $oldclogp, 'Version';
1173 version_compare($oversion, $cversion);
1175 # git upload/ is earlier vsn than archive, use archive
1176 open C, ">../commit2.tmp" or die $!;
1177 print C <<END or die $!;
1179 parent $lastpush_hash
1184 Record $package ($cversion) in archive suite $csuite
1186 $outputhash = make_commit qw(../commit2.tmp);
1187 } elsif ($vcmp > 0) {
1188 print STDERR <<END or die $!;
1190 Version actually in archive: $cversion (older)
1191 Last allegedly pushed/uploaded: $oversion (newer or same)
1194 $outputhash = $lastpush_hash;
1196 $outputhash = $lastpush_hash;
1199 changedir '../../../..';
1200 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1201 'DGIT_ARCHIVE', $outputhash;
1202 cmdoutput @git, qw(log -n2), $outputhash;
1203 # ... gives git a chance to complain if our commit is malformed
1208 sub complete_file_from_dsc ($$) {
1209 our ($dstdir, $fi) = @_;
1210 # Ensures that we have, in $dir, the file $fi, with the correct
1211 # contents. (Downloading it from alongside $dscurl if necessary.)
1213 my $f = $fi->{Filename};
1214 my $tf = "$dstdir/$f";
1217 if (stat_exists $tf) {
1218 progress "using existing $f";
1221 $furl =~ s{/[^/]+$}{};
1223 die "$f ?" unless $f =~ m/^${package}_/;
1224 die "$f ?" if $f =~ m#/#;
1225 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1226 next if !act_local();
1230 open F, "<", "$tf" or die "$tf: $!";
1231 $fi->{Digester}->reset();
1232 $fi->{Digester}->addfile(*F);
1233 F->error and die $!;
1234 my $got = $fi->{Digester}->hexdigest();
1235 $got eq $fi->{Hash} or
1236 fail "file $f has hash $got but .dsc".
1237 " demands hash $fi->{Hash} ".
1238 ($downloaded ? "(got wrong file from archive!)"
1239 : "(perhaps you should delete this file?)");
1242 sub ensure_we_have_orig () {
1243 foreach my $fi (dsc_files_info()) {
1244 my $f = $fi->{Filename};
1245 next unless is_orig_file($f);
1246 complete_file_from_dsc('..', $fi);
1251 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1254 sub is_fast_fwd ($$) {
1255 my ($ancestor,$child) = @_;
1256 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1257 my $mb = cmdoutput_errok @cmd;
1259 return rev_parse($mb) eq rev_parse($ancestor);
1261 $?==256 or failedcmd @cmd;
1266 sub git_fetch_us () {
1267 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1270 sub fetch_from_archive () {
1271 # ensures that lrref() is what is actually in the archive,
1272 # one way or another
1276 foreach my $field (@ourdscfield) {
1277 $dsc_hash = $dsc->{$field};
1278 last if defined $dsc_hash;
1280 if (defined $dsc_hash) {
1281 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1283 progress "last upload to archive specified git hash";
1285 progress "last upload to archive has NO git hash";
1288 progress "no version available from the archive";
1291 $lastpush_hash = git_get_ref(lrref());
1292 printdebug "previous reference hash=$lastpush_hash\n";
1294 if (defined $dsc_hash) {
1295 fail "missing remote git history even though dsc has hash -".
1296 " could not find ref ".lrref().
1297 " (should have been fetched from ".access_giturl()."#".rrref().")"
1298 unless $lastpush_hash;
1300 ensure_we_have_orig();
1301 if ($dsc_hash eq $lastpush_hash) {
1302 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1303 print STDERR <<END or die $!;
1305 Git commit in archive is behind the last version allegedly pushed/uploaded.
1306 Commit referred to by archive: $dsc_hash
1307 Last allegedly pushed/uploaded: $lastpush_hash
1310 $hash = $lastpush_hash;
1312 fail "archive's .dsc refers to ".$dsc_hash.
1313 " but this is an ancestor of ".$lastpush_hash;
1316 $hash = generate_commit_from_dsc();
1317 } elsif ($lastpush_hash) {
1318 # only in git, not in the archive yet
1319 $hash = $lastpush_hash;
1320 print STDERR <<END or die $!;
1322 Package not found in the archive, but has allegedly been pushed using dgit.
1326 printdebug "nothing found!\n";
1327 if (defined $skew_warning_vsn) {
1328 print STDERR <<END or die $!;
1330 Warning: relevant archive skew detected.
1331 Archive allegedly contains $skew_warning_vsn
1332 But we were not able to obtain any version from the archive or git.
1338 printdebug "current hash=$hash\n";
1339 if ($lastpush_hash) {
1340 fail "not fast forward on last upload branch!".
1341 " (archive's version left in DGIT_ARCHIVE)"
1342 unless is_fast_fwd($lastpush_hash, $hash);
1344 if (defined $skew_warning_vsn) {
1346 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1347 my $clogf = ".git/dgit/changelog.tmp";
1348 runcmd shell_cmd "exec >$clogf",
1349 @git, qw(cat-file blob), "$hash:debian/changelog";
1350 my $gotclogp = parsechangelog("-l$clogf");
1351 my $got_vsn = getfield $gotclogp, 'Version';
1352 printdebug "SKEW CHECK GOT $got_vsn\n";
1353 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1354 print STDERR <<END or die $!;
1356 Warning: archive skew detected. Using the available version:
1357 Archive allegedly contains $skew_warning_vsn
1358 We were able to obtain only $got_vsn
1363 if ($lastpush_hash ne $hash) {
1364 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1368 dryrun_report @upd_cmd;
1376 canonicalise_suite();
1377 badusage "dry run makes no sense with clone" unless act_local();
1378 mkdir $dstdir or die "$dstdir $!";
1380 runcmd @git, qw(init -q);
1381 my $giturl = access_giturl(1);
1382 if (defined $giturl) {
1383 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1384 open H, "> .git/HEAD" or die $!;
1385 print H "ref: ".lref()."\n" or die $!;
1387 runcmd @git, qw(remote add), 'origin', $giturl;
1389 if (check_for_git()) {
1390 progress "fetching existing git history";
1392 runcmd_ordryrun_local @git, qw(fetch origin);
1394 progress "starting new git history";
1396 fetch_from_archive() or no_such_package;
1397 my $vcsgiturl = $dsc->{'Vcs-Git'};
1398 if (length $vcsgiturl) {
1399 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1401 runcmd @git, qw(reset --hard), lrref();
1402 printdone "ready for work in $dstdir";
1406 if (check_for_git()) {
1409 fetch_from_archive() or no_such_package();
1410 printdone "fetched into ".lrref();
1415 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1417 printdone "fetched to ".lrref()." and merged into HEAD";
1420 sub check_not_dirty () {
1421 return if $ignoredirty;
1422 my @cmd = (@git, qw(diff --quiet HEAD));
1423 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1424 $!=0; $?=0; system @cmd;
1425 return if !$! && !$?;
1426 if (!$! && $?==256) {
1427 fail "working tree is dirty (does not match HEAD)";
1433 sub commit_admin ($) {
1436 runcmd_ordryrun_local @git, qw(commit -m), $m;
1439 sub commit_quilty_patch () {
1440 my $output = cmdoutput @git, qw(status --porcelain);
1442 foreach my $l (split /\n/, $output) {
1443 next unless $l =~ m/\S/;
1444 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1448 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1450 progress "nothing quilty to commit, ok.";
1453 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1454 commit_admin "Commit Debian 3.0 (quilt) metadata";
1457 sub get_source_format () {
1458 if (!open F, "debian/source/format") {
1459 die $! unless $!==&ENOENT;
1463 F->error and die $!;
1470 return 0 unless $format eq '3.0 (quilt)';
1472 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1475 progress "Format \`$format', checking/updating patch stack";
1479 sub push_parse_changelog ($) {
1482 my $clogp = Dpkg::Control::Hash->new();
1483 $clogp->load($clogpfn) or die;
1485 $package = getfield $clogp, 'Source';
1486 my $cversion = getfield $clogp, 'Version';
1487 my $tag = debiantag($cversion);
1488 runcmd @git, qw(check-ref-format), $tag;
1490 my $dscfn = dscfn($cversion);
1492 return ($clogp, $cversion, $tag, $dscfn);
1495 sub push_parse_dsc ($$$) {
1496 my ($dscfn,$dscfnwhat, $cversion) = @_;
1497 $dsc = parsecontrol($dscfn,$dscfnwhat);
1498 my $dversion = getfield $dsc, 'Version';
1499 my $dscpackage = getfield $dsc, 'Source';
1500 ($dscpackage eq $package && $dversion eq $cversion) or
1501 fail "$dscfn is for $dscpackage $dversion".
1502 " but debian/changelog is for $package $cversion";
1505 sub push_mktag ($$$$$$$) {
1506 my ($head,$clogp,$tag,
1508 $changesfile,$changesfilewhat,
1511 $dsc->{$ourdscfield[0]} = $head;
1512 $dsc->save("$dscfn.tmp") or die $!;
1514 my $changes = parsecontrol($changesfile,$changesfilewhat);
1515 foreach my $field (qw(Source Distribution Version)) {
1516 $changes->{$field} eq $clogp->{$field} or
1517 fail "changes field $field \`$changes->{$field}'".
1518 " does not match changelog \`$clogp->{$field}'";
1521 my $cversion = getfield $clogp, 'Version';
1522 my $clogsuite = getfield $clogp, 'Distribution';
1524 # We make the git tag by hand because (a) that makes it easier
1525 # to control the "tagger" (b) we can do remote signing
1526 my $authline = clogp_authline $clogp;
1527 open TO, '>', $tfn->('.tmp') or die $!;
1528 print TO <<END or die $!;
1534 $package release $cversion for $clogsuite ($csuite) [dgit]
1538 my $tagobjfn = $tfn->('.tmp');
1540 if (!defined $keyid) {
1541 $keyid = access_cfg('keyid','RETURN-UNDEF');
1543 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1544 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1545 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1546 push @sign_cmd, $tfn->('.tmp');
1547 runcmd_ordryrun @sign_cmd;
1549 $tagobjfn = $tfn->('.signed.tmp');
1550 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1551 $tfn->('.tmp'), $tfn->('.tmp.asc');
1558 sub sign_changes ($) {
1559 my ($changesfile) = @_;
1561 my @debsign_cmd = @debsign;
1562 push @debsign_cmd, "-k$keyid" if defined $keyid;
1563 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1564 push @debsign_cmd, $changesfile;
1565 runcmd_ordryrun @debsign_cmd;
1570 printdebug "actually entering push\n";
1573 access_giturl(); # check that success is vaguely likely
1575 my $clogpfn = ".git/dgit/changelog.822.tmp";
1576 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1578 responder_send_file('parsed-changelog', $clogpfn);
1580 my ($clogp, $cversion, $tag, $dscfn) =
1581 push_parse_changelog("$clogpfn");
1583 my $dscpath = "$buildproductsdir/$dscfn";
1584 stat_exists $dscpath or
1585 fail "looked for .dsc $dscfn, but $!;".
1586 " maybe you forgot to build";
1588 responder_send_file('dsc', $dscpath);
1590 push_parse_dsc($dscpath, $dscfn, $cversion);
1592 my $format = getfield $dsc, 'Format';
1593 printdebug "format $format\n";
1594 if (madformat($format)) {
1595 commit_quilty_patch();
1599 progress "checking that $dscfn corresponds to HEAD";
1600 runcmd qw(dpkg-source -x --),
1601 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1602 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1603 changedir '../../../..';
1604 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1605 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1606 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1608 my $r = system @diffcmd;
1611 fail "$dscfn specifies a different tree to your HEAD commit;".
1612 " perhaps you forgot to build".
1613 ($diffopt eq '--exit-code' ? "" :
1614 " (run with -D to see full diff output)");
1620 #do fast forward check and maybe fake merge
1621 # if (!is_fast_fwd(mainbranch
1622 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1623 # map { lref($_).":".rref($_) }
1625 my $head = rev_parse('HEAD');
1626 if (!$changesfile) {
1627 my $multi = "$buildproductsdir/".
1628 "${package}_".(stripepoch $cversion)."_multi.changes";
1629 if (stat_exists "$multi") {
1630 $changesfile = $multi;
1632 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1633 my @cs = glob "$buildproductsdir/$pat";
1634 fail "failed to find unique changes file".
1635 " (looked for $pat in $buildproductsdir, or $multi);".
1636 " perhaps you need to use dgit -C"
1638 ($changesfile) = @cs;
1641 $changesfile = "$buildproductsdir/$changesfile";
1644 responder_send_file('changes',$changesfile);
1645 responder_send_command("param head $head");
1646 responder_send_command("param csuite $csuite");
1648 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1651 if ($we_are_responder) {
1652 $tagobjfn = $tfn->('.signed.tmp');
1653 responder_receive_files('signed-tag', $tagobjfn);
1656 push_mktag($head,$clogp,$tag,
1658 $changesfile,$changesfile,
1662 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1663 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1664 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1665 runcmd_ordryrun @git, qw(tag -v --), $tag;
1667 if (!check_for_git()) {
1668 create_remote_git_repo();
1670 runcmd_ordryrun @git, qw(push),access_giturl(),
1671 "HEAD:".rrref(), "refs/tags/$tag";
1672 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1674 if ($we_are_responder) {
1675 my $dryrunsuffix = act_local() ? "" : ".tmp";
1676 responder_receive_files('signed-dsc-changes',
1677 "$dscpath$dryrunsuffix",
1678 "$changesfile$dryrunsuffix");
1681 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1683 progress "[new .dsc left in $dscpath.tmp]";
1685 sign_changes $changesfile;
1688 my $host = access_cfg('upload-host','RETURN-UNDEF');
1689 my @hostarg = defined($host) ? ($host,) : ();
1690 runcmd_ordryrun @dput, @hostarg, $changesfile;
1691 printdone "pushed and uploaded $cversion";
1693 responder_send_command("complete");
1699 badusage "-p is not allowed with clone; specify as argument instead"
1700 if defined $package;
1703 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1704 ($package,$isuite) = @ARGV;
1705 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1706 ($package,$dstdir) = @ARGV;
1707 } elsif (@ARGV==3) {
1708 ($package,$isuite,$dstdir) = @ARGV;
1710 badusage "incorrect arguments to dgit clone";
1712 $dstdir ||= "$package";
1714 if (stat_exists $dstdir) {
1715 fail "$dstdir already exists";
1719 if ($rmonerror && !$dryrun_level) {
1720 $cwd_remove= getcwd();
1722 return unless defined $cwd_remove;
1723 if (!chdir "$cwd_remove") {
1724 return if $!==&ENOENT;
1725 die "chdir $cwd_remove: $!";
1727 rmtree($dstdir) or die "remove $dstdir: $!\n";
1732 $cwd_remove = undef;
1735 sub branchsuite () {
1736 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1737 if ($branch =~ m#$lbranch_re#o) {
1744 sub fetchpullargs () {
1745 if (!defined $package) {
1746 my $sourcep = parsecontrol('debian/control','debian/control');
1747 $package = getfield $sourcep, 'Source';
1750 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1752 my $clogp = parsechangelog();
1753 $isuite = getfield $clogp, 'Distribution';
1755 canonicalise_suite();
1756 progress "fetching from suite $csuite";
1757 } elsif (@ARGV==1) {
1759 canonicalise_suite();
1761 badusage "incorrect arguments to dgit fetch or dgit pull";
1779 badusage "-p is not allowed with dgit push" if defined $package;
1781 my $clogp = parsechangelog();
1782 $package = getfield $clogp, 'Source';
1785 } elsif (@ARGV==1) {
1786 ($specsuite) = (@ARGV);
1788 badusage "incorrect arguments to dgit push";
1790 $isuite = getfield $clogp, 'Distribution';
1792 local ($package) = $existing_package; # this is a hack
1793 canonicalise_suite();
1795 if (defined $specsuite && $specsuite ne $isuite) {
1796 canonicalise_suite();
1797 $csuite eq $specsuite or
1798 fail "dgit push: changelog specifies $isuite ($csuite)".
1799 " but command line specifies $specsuite";
1801 if (check_for_git()) {
1804 if (fetch_from_archive()) {
1805 is_fast_fwd(lrref(), 'HEAD') or
1806 fail "dgit push: HEAD is not a descendant".
1807 " of the archive's version.\n".
1808 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1811 fail "package appears to be new in this suite;".
1812 " if this is intentional, use --new";
1817 #---------- remote commands' implementation ----------
1819 sub cmd_remote_push_build_host {
1820 my ($nrargs) = shift @ARGV;
1821 my (@rargs) = @ARGV[0..$nrargs-1];
1822 @ARGV = @ARGV[$nrargs..$#ARGV];
1824 my ($dir,$vsnwant) = @rargs;
1825 # vsnwant is a comma-separated list; we report which we have
1826 # chosen in our ready response (so other end can tell if they
1829 $we_are_responder = 1;
1831 open PI, "<&STDIN" or die $!;
1832 open STDIN, "/dev/null" or die $!;
1833 open PO, ">&STDOUT" or die $!;
1835 open STDOUT, ">&STDERR" or die $!;
1839 fail "build host has dgit rpush protocol version".
1840 " $rpushprotovsn but invocation host has $vsnwant"
1841 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1843 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1849 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1850 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1851 # a good error message)
1857 my $report = i_child_report();
1858 if (defined $report) {
1859 printdebug "($report)\n";
1860 } elsif ($i_child_pid) {
1861 printdebug "(killing build host child $i_child_pid)\n";
1862 kill 15, $i_child_pid;
1864 if (defined $i_tmp && !defined $initiator_tempdir) {
1866 eval { rmtree $i_tmp; };
1870 END { i_cleanup(); }
1873 my ($base,$selector,@args) = @_;
1874 $selector =~ s/\-/_/g;
1875 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1881 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1888 my @rargs = ($dir,$rpushprotovsn);
1891 push @rdgit, @ropts;
1892 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1894 my @cmd = (@ssh, $host, shellquote @rdgit);
1895 printcmd \*DEBUG,$debugprefix."+",@cmd;
1897 if (defined $initiator_tempdir) {
1898 rmtree $initiator_tempdir;
1899 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1900 $i_tmp = $initiator_tempdir;
1904 $i_child_pid = open2(\*RO, \*RI, @cmd);
1906 initiator_expect { m/^dgit-remote-push-ready/ };
1908 my ($icmd,$iargs) = initiator_expect {
1909 m/^(\S+)(?: (.*))?$/;
1912 i_method "i_resp", $icmd, $iargs;
1916 sub i_resp_progress ($) {
1918 my $msg = protocol_read_bytes \*RO, $rhs;
1922 sub i_resp_complete {
1923 my $pid = $i_child_pid;
1924 $i_child_pid = undef; # prevents killing some other process with same pid
1925 printdebug "waiting for build host child $pid...\n";
1926 my $got = waitpid $pid, 0;
1927 die $! unless $got == $pid;
1928 die "build host child failed $?" if $?;
1931 printdebug "all done\n";
1935 sub i_resp_file ($) {
1937 my $localname = i_method "i_localname", $keyword;
1938 my $localpath = "$i_tmp/$localname";
1939 stat_exists $localpath and
1940 badproto \*RO, "file $keyword ($localpath) twice";
1941 protocol_receive_file \*RO, $localpath;
1942 i_method "i_file", $keyword;
1947 sub i_resp_param ($) {
1948 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1954 sub i_resp_want ($) {
1956 die "$keyword ?" if $i_wanted{$keyword}++;
1957 my @localpaths = i_method "i_want", $keyword;
1958 printdebug "[[ $keyword @localpaths\n";
1959 foreach my $localpath (@localpaths) {
1960 protocol_send_file \*RI, $localpath;
1962 print RI "files-end\n" or die $!;
1965 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1967 sub i_localname_parsed_changelog {
1968 return "remote-changelog.822";
1970 sub i_file_parsed_changelog {
1971 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1972 push_parse_changelog "$i_tmp/remote-changelog.822";
1973 die if $i_dscfn =~ m#/|^\W#;
1976 sub i_localname_dsc {
1977 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1982 sub i_localname_changes {
1983 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1984 $i_changesfn = $i_dscfn;
1985 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1986 return $i_changesfn;
1988 sub i_file_changes { }
1990 sub i_want_signed_tag {
1991 printdebug Dumper(\%i_param, $i_dscfn);
1992 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
1993 && defined $i_param{'csuite'}
1994 or badproto \*RO, "premature desire for signed-tag";
1995 my $head = $i_param{'head'};
1996 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1998 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2000 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2003 push_mktag $head, $i_clogp, $i_tag,
2005 $i_changesfn, 'remote changes',
2006 sub { "tag$_[0]"; };
2011 sub i_want_signed_dsc_changes {
2012 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2013 sign_changes $i_changesfn;
2014 return ($i_dscfn, $i_changesfn);
2017 #---------- building etc. ----------
2023 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2025 sub build_maybe_quilt_fixup () {
2026 my $format=get_source_format;
2027 return unless madformat $format;
2031 # - honour any existing .pc in case it has any strangeness
2032 # - determine the git commit corresponding to the tip of
2033 # the patch stack (if there is one)
2034 # - if there is such a git commit, convert each subsequent
2035 # git commit into a quilt patch with dpkg-source --commit
2036 # - otherwise convert all the differences in the tree into
2037 # a single git commit
2041 # Our git tree doesn't necessarily contain .pc. (Some versions of
2042 # dgit would include the .pc in the git tree.) If there isn't
2043 # one, we need to generate one by unpacking the patches that we
2046 # We first look for a .pc in the git tree. If there is one, we
2047 # will use it. (This is not the normal case.)
2049 # Otherwise need to regenerate .pc so that dpkg-source --commit
2050 # can work. We do this as follows:
2051 # 1. Collect all relevant .orig from parent directory
2052 # 2. Generate a debian.tar.gz out of
2053 # debian/{patches,rules,source/format}
2054 # 3. Generate a fake .dsc containing just these fields:
2055 # Format Source Version Files
2056 # 4. Extract the fake .dsc
2057 # Now the fake .dsc has a .pc directory.
2058 # (In fact we do this in every case, because in future we will
2059 # want to search for a good base commit for generating patches.)
2061 # Then we can actually do the dpkg-source --commit
2062 # 1. Make a new working tree with the same object
2063 # store as our main tree and check out the main
2065 # 2. Copy .pc from the fake's extraction, if necessary
2066 # 3. Run dpkg-source --commit
2067 # 4. If the result has changes to debian/, then
2068 # - git-add them them
2069 # - git-add .pc if we had a .pc in-tree
2071 # 5. If we had a .pc in-tree, delete it, and git-commit
2072 # 6. Back in the main tree, fast forward to the new HEAD
2074 my $clogp = parsechangelog();
2075 my $headref = rev_parse('HEAD');
2080 my $upstreamversion=$version;
2081 $upstreamversion =~ s/-[^-]*$//;
2083 my $fakeversion="$upstreamversion-~~DGITFAKE";
2085 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2086 print $fakedsc <<END or die $!;
2089 Version: $fakeversion
2093 my $dscaddfile=sub {
2096 my $md = new Digest::MD5;
2098 my $fh = new IO::File $b, '<' or die "$b $!";
2103 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2106 foreach my $f (<../../../../*>) { #/){
2107 my $b=$f; $b =~ s{.*/}{};
2108 next unless is_orig_file $b, srcfn $upstreamversion,'';
2109 link $f, $b or die "$b $!";
2113 my @files=qw(debian/source/format debian/rules);
2114 if (stat_exists '../../../debian/patches') {
2115 push @files, 'debian/patches';
2118 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2119 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2121 $dscaddfile->($debtar);
2122 close $fakedsc or die $!;
2124 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2126 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2127 rename $fakexdir, "fake" or die "$fakexdir $!";
2129 mkdir "work" or die $!;
2131 mktree_in_ud_here();
2132 runcmd @git, qw(reset --hard), $headref;
2135 if (stat_exists ".pc") {
2137 progress "Tree already contains .pc - will use it then delete it.";
2140 rename '../fake/.pc','.pc' or die $!;
2143 my $author = getfield $clogp, 'Maintainer';
2146 my $patchname = "auto-$version-$headref-$time";
2147 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2149 my $descfn = ".git/dgit/quilt-description.tmp";
2150 open O, '>', $descfn or die "$descfn: $!";
2152 $msg =~ s/^\s+$/ ./mg;
2153 print O <<END or die $!;
2154 Description: Automatically generated patch ($clogp->{Version})
2155 Last (up to) $ncommits git changes, FYI:
2165 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2166 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2167 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2168 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2171 if (!open P, '>>', ".pc/applied-patches") {
2172 $!==&ENOENT or die $!;
2177 commit_quilty_patch();
2179 if ($mustdeletepc) {
2180 runcmd @git, qw(rm -rq .pc);
2181 commit_admin "Commit removal of .pc (quilt series tracking data)";
2184 changedir '../../../..';
2185 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2188 sub quilt_fixup_editor () {
2189 my $descfn = $ENV{$fakeeditorenv};
2190 my $editing = $ARGV[$#ARGV];
2191 open I1, '<', $descfn or die "$descfn: $!";
2192 open I2, '<', $editing or die "$editing: $!";
2193 unlink $editing or die "$editing: $!";
2194 open O, '>', $editing or die "$editing: $!";
2195 while (<I1>) { print O or die $!; } I1->error and die $!;
2198 $copying ||= m/^\-\-\- /;
2199 next unless $copying;
2202 I2->error and die $!;
2208 if ($cleanmode eq 'dpkg-source') {
2209 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2210 } elsif ($cleanmode eq 'git') {
2211 runcmd_ordryrun_local @git, qw(clean -xdf);
2212 } elsif ($cleanmode eq 'none') {
2219 badusage "clean takes no additional arguments" if @ARGV;
2224 badusage "-p is not allowed when building" if defined $package;
2227 my $clogp = parsechangelog();
2228 $isuite = getfield $clogp, 'Distribution';
2229 $package = getfield $clogp, 'Source';
2230 $version = getfield $clogp, 'Version';
2231 build_maybe_quilt_fixup();
2234 sub changesopts () {
2235 my @opts =@changesopts[1..$#changesopts];
2236 if (!defined $changes_since_version) {
2237 my @vsns = archive_query('archive_query');
2238 my @quirk = access_quirk();
2239 if ($quirk[0] eq 'backports') {
2240 local $isuite = $quirk[2];
2242 canonicalise_suite();
2243 push @vsns, archive_query('archive_query');
2246 @vsns = map { $_->[0] } @vsns;
2247 @vsns = sort { -version_compare($a, $b) } @vsns;
2248 $changes_since_version = $vsns[0];
2249 progress "changelog will contain changes since $vsns[0]";
2251 $changes_since_version = '_';
2252 progress "package seems new, not specifying -v<version>";
2255 if ($changes_since_version ne '_') {
2256 unshift @opts, "-v$changes_since_version";
2263 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2264 printdone "build successful\n";
2270 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2271 "--git-builder=@dpkgbuildpackage");
2272 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2273 canonicalise_suite();
2274 push @cmd, "--git-debian-branch=".lbranch();
2276 push @cmd, changesopts();
2277 runcmd_ordryrun_local @cmd, @ARGV;
2278 printdone "build successful\n";
2283 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2284 $dscfn = dscfn($version);
2285 if ($cleanmode eq 'dpkg-source') {
2286 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2289 my $pwd = must_getcwd();
2290 my $leafdir = basename $pwd;
2292 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2294 runcmd_ordryrun_local qw(sh -ec),
2295 'exec >$1; shift; exec "$@"','x',
2296 "../$sourcechanges",
2297 @dpkggenchanges, qw(-S), changesopts();
2301 sub cmd_build_source {
2302 badusage "build-source takes no additional arguments" if @ARGV;
2304 printdone "source built, results in $dscfn and $sourcechanges";
2310 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2312 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2313 stat_exists $sourcechanges
2314 or fail "$sourcechanges (in parent directory): $!";
2315 foreach my $cf (glob $pat) {
2316 next if $cf eq $sourcechanges;
2317 unlink $cf or fail "remove $cf: $!";
2320 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2321 my @changesfiles = glob $pat;
2322 @changesfiles = sort {
2323 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2326 fail "wrong number of different changes files (@changesfiles)"
2327 unless @changesfiles;
2328 runcmd_ordryrun_local @mergechanges, @changesfiles;
2329 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2331 stat_exists $multichanges or fail "$multichanges: $!";
2333 printdone "build successful, results in $multichanges\n" or die $!;
2336 sub cmd_quilt_fixup {
2337 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2338 my $clogp = parsechangelog();
2339 $version = getfield $clogp, 'Version';
2340 $package = getfield $clogp, 'Source';
2341 build_maybe_quilt_fixup();
2344 #---------- argument parsing and main program ----------
2347 print "dgit version $our_version\n" or die $!;
2354 if (defined $ENV{'DGIT_SSH'}) {
2355 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2356 } elsif (defined $ENV{'GIT_SSH'}) {
2357 @ssh = ($ENV{'GIT_SSH'});
2361 last unless $ARGV[0] =~ m/^-/;
2365 if (m/^--dry-run$/) {
2368 } elsif (m/^--damp-run$/) {
2371 } elsif (m/^--no-sign$/) {
2374 } elsif (m/^--help$/) {
2376 } elsif (m/^--version$/) {
2378 } elsif (m/^--new$/) {
2381 } elsif (m/^--since-version=([^_]+|_)$/) {
2383 $changes_since_version = $1;
2384 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2385 ($om = $opts_opt_map{$1}) &&
2389 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2390 !$opts_opt_cmdonly{$1} &&
2391 ($om = $opts_opt_map{$1})) {
2394 } elsif (m/^--existing-package=(.*)/s) {
2396 $existing_package = $1;
2397 } elsif (m/^--initiator-tempdir=(.*)/s) {
2398 $initiator_tempdir = $1;
2399 $initiator_tempdir =~ m#^/# or
2400 badusage "--initiator-tempdir must be used specify an".
2401 " absolute, not relative, directory."
2402 } elsif (m/^--distro=(.*)/s) {
2405 } elsif (m/^--build-products-dir=(.*)/s) {
2407 $buildproductsdir = $1;
2408 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2411 } elsif (m/^--clean=(.*)$/s) {
2412 badusage "unknown cleaning mode \`$1'";
2413 } elsif (m/^--ignore-dirty$/s) {
2416 } elsif (m/^--no-quilt-fixup$/s) {
2419 } elsif (m/^--no-rm-on-error$/s) {
2423 badusage "unknown long option \`$_'";
2430 } elsif (s/^-L/-/) {
2433 } elsif (s/^-h/-/) {
2435 } elsif (s/^-D/-/) {
2437 open DEBUG, ">&STDERR" or die $!;
2440 } elsif (s/^-N/-/) {
2443 } elsif (s/^-v([^_]+|_)$//s) {
2445 $changes_since_version = $1;
2448 push @changesopts, $_;
2450 } elsif (s/^-c(.*=.*)//s) {
2452 push @git, '-c', $1;
2453 } elsif (s/^-d(.*)//s) {
2456 } elsif (s/^-C(.*)//s) {
2459 if ($changesfile =~ s#^(.*)/##) {
2460 $buildproductsdir = $1;
2462 } elsif (s/^-k(.*)//s) {
2464 } elsif (s/^-wn//s) {
2466 $cleanmode = 'none';
2467 } elsif (s/^-wg//s) {
2470 } elsif (s/^-wd//s) {
2472 $cleanmode = 'dpkg-source';
2474 badusage "unknown short option \`$_'";
2481 if ($ENV{$fakeeditorenv}) {
2482 quilt_fixup_editor();
2486 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2487 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2488 if $dryrun_level == 1;
2490 print STDERR $helpmsg or die $!;
2493 my $cmd = shift @ARGV;
2496 my $fn = ${*::}{"cmd_$cmd"};
2497 $fn or badusage "unknown operation $cmd";