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 $!; }
167 my $prefix = $us.($we_are_responder ? " (build host)" : "").": ";
168 $s =~ s/^/$prefix/gm;
172 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
174 sub no_such_package () {
175 print STDERR "$us: package $package does not exist in suite $isuite\n";
181 return "+".rrref().":".lrref();
186 printdebug "CD $newdir\n";
187 chdir $newdir or die "chdir: $newdir: $!";
190 sub stat_exists ($) {
193 return 0 if $!==&ENOENT;
197 #---------- remote protocol support, common ----------
199 # remote push initiator/responder protocol:
200 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
202 # > file parsed-changelog
203 # [indicates that output of dpkg-parsechangelog follows]
204 # > data-block NBYTES
205 # > [NBYTES bytes of data (no newline)]
206 # [maybe some more blocks]
218 # [indicates that signed tag is wanted]
219 # < data-block NBYTES
220 # < [NBYTES bytes of data (no newline)]
221 # [maybe some more blocks]
225 # > want signed-dsc-changes
226 # < data-block NBYTES [transfer of signed dsc]
228 # < data-block NBYTES [transfer of signed changes]
236 sub i_child_report () {
237 # Sees if our child has died, and reap it if so. Returns a string
238 # describing how it died if it failed, or undef otherwise.
239 return undef unless $i_child_pid;
240 my $got = waitpid $i_child_pid, WNOHANG;
241 return undef if $got <= 0;
242 die unless $got == $i_child_pid;
243 $i_child_pid = undef;
244 return undef unless $?;
245 return "build host child ".waitstatusmsg();
250 fail "connection lost: $!" if $fh->error;
251 fail "protocol violation; $m not expected";
254 sub badproto_badread ($$) {
256 fail "connection lost: $!" if $!;
257 my $report = i_child_report();
258 fail $report if defined $report;
259 badproto $fh, "eof (reading $wh)";
262 sub protocol_expect (&$) {
263 my ($match, $fh) = @_;
266 defined && chomp or badproto_badread $fh, "protocol message";
274 badproto $fh, "\`$_'";
277 sub protocol_send_file ($$) {
278 my ($fh, $ourfn) = @_;
279 open PF, "<", $ourfn or die "$ourfn: $!";
282 my $got = read PF, $d, 65536;
283 die "$ourfn: $!" unless defined $got;
285 print $fh "data-block ".length($d)."\n" or die $!;
286 print $fh $d or die $!;
288 PF->error and die "$ourfn $!";
289 print $fh "data-end\n" or die $!;
293 sub protocol_read_bytes ($$) {
294 my ($fh, $nbytes) = @_;
295 $nbytes =~ m/^[1-9]\d{0,5}$/ or badproto \*RO, "bad byte count";
297 my $got = read $fh, $d, $nbytes;
298 $got==$nbytes or badproto_badread $fh, "data block";
302 sub protocol_receive_file ($$) {
303 my ($fh, $ourfn) = @_;
304 printdebug "() $ourfn\n";
305 open PF, ">", $ourfn or die "$ourfn: $!";
307 my ($y,$l) = protocol_expect {
308 m/^data-block (.*)$/ ? (1,$1) :
309 m/^data-end$/ ? (0,) :
313 my $d = protocol_read_bytes $fh, $l;
314 print PF $d or die $!;
319 #---------- remote protocol support, responder ----------
321 sub responder_send_command ($) {
323 return unless $we_are_responder;
324 # called even without $we_are_responder
325 printdebug ">> $command\n";
326 print PO $command, "\n" or die $!;
329 sub responder_send_file ($$) {
330 my ($keyword, $ourfn) = @_;
331 return unless $we_are_responder;
332 printdebug "]] $keyword $ourfn\n";
333 responder_send_command "file $keyword";
334 protocol_send_file \*PO, $ourfn;
337 sub responder_receive_files ($@) {
338 my ($keyword, @ourfns) = @_;
339 die unless $we_are_responder;
340 printdebug "[[ $keyword @ourfns\n";
341 responder_send_command "want $keyword";
342 foreach my $fn (@ourfns) {
343 protocol_receive_file \*PI, $fn;
346 protocol_expect { m/^files-end$/ } \*PI;
349 #---------- remote protocol support, initiator ----------
351 sub initiator_expect (&) {
353 protocol_expect { &$match } \*RO;
356 #---------- end remote code ----------
359 if ($we_are_responder) {
361 responder_send_command "progress ".length($m) or die $!;
362 print PO $m or die $!;
372 $ua = LWP::UserAgent->new();
376 progress "downloading $what...";
377 my $r = $ua->get(@_) or die $!;
378 return undef if $r->code == 404;
379 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
380 return $r->decoded_content(charset => 'none');
383 our ($dscdata,$dscurl,$dsc,$dsc_checked,$skew_warning_vsn);
390 if (m{[^-=_./0-9a-z]}i) {
397 return join ' ', @out;
402 my $intro = shift @_;
403 print $fh $intro," " or die $!;
404 print $fh shellquote @_ or die $!;
405 print $fh "\n" or die $!;
409 { local ($!); printcmd \*STDERR, "$us: failed command:", @_ or die $!; };
411 fail "failed to fork/exec: $!";
413 fail "subprocess ".waitstatusmsg();
415 fail "subprocess produced invalid output";
420 printcmd(\*DEBUG,$debugprefix."+",@_) if $debug>0;
422 failedcmd @_ if system @_;
425 sub act_local () { return $dryrun_level <= 1; }
426 sub act_scary () { return !$dryrun_level; }
429 if (!$dryrun_level) {
430 progress "dgit ok: @_";
432 progress "would be ok: @_ (but dry run only)";
436 sub cmdoutput_errok {
437 die Dumper(\@_)." ?" if grep { !defined } @_;
438 printcmd(\*DEBUG,$debugprefix."|",@_) if $debug>0;
439 open P, "-|", @_ or die $!;
442 { local $/ = undef; $d = <P>; }
444 if (!close P) { printdebug "=>!$?\n" if $debug>0; return undef; }
447 printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
452 my $d = cmdoutput_errok @_;
453 defined $d or failedcmd @_;
458 printcmd(\*STDERR,$debugprefix."#",@_);
461 sub runcmd_ordryrun {
469 sub runcmd_ordryrun_local {
478 my ($first_shell, @cmd) = @_;
479 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
482 our $helpmsg = <<END;
484 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
485 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
486 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
487 dgit [dgit-opts] push [dgit-opts] [suite]
488 dgit [dgit-opts] rpush build-host:build-dir ...
489 important dgit options:
490 -k<keyid> sign tag and package with <keyid> instead of default
491 --dry-run -n do not change anything, but go through the motions
492 --damp-run -L like --dry-run but make local changes, without signing
493 --new -N allow introducing a new package
494 --debug -D increase debug level
495 -c<name>=<value> set git config option (used directly by dgit too)
498 our $later_warning_msg = <<END;
499 Perhaps the upload is stuck in incoming. Using the version from git.
503 print STDERR "$us: @_\n", $helpmsg or die $!;
508 @ARGV or badusage "too few arguments";
509 return scalar shift @ARGV;
513 print $helpmsg or die $!;
517 our $td = $ENV{DGIT_TEST_DUMMY_DIR} || "DGIT_TEST_DUMMY_DIR-unset";
519 our %defcfg = ('dgit.default.distro' => 'debian',
520 'dgit.default.username' => '',
521 'dgit.default.archive-query-default-component' => 'main',
522 'dgit.default.ssh' => 'ssh',
523 'dgit.default.archive-query' => 'madison:',
524 'dgit.default.sshpsql-dbname' => 'service=projectb',
525 'dgit-distro.debian.archive-query' => 'sshpsql:',
526 'dgit-distro.debian.git-host' => 'dgit-git.debian.net',
527 'dgit-distro.debian.git-user-force' => 'dgit',
528 'dgit-distro.debian.git-proto' => 'git+ssh://',
529 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
530 'dgit-distro.debian.diverts.alioth' => '/alioth',
531 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
532 'dgit-distro.debian/alioth.git-user-force' => '',
533 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
534 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
535 'dgit-distro.debian.git-check' => 'ssh-cmd',
536 'dgit-distro.debian.git-create' => 'ssh-cmd',
537 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
538 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
539 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
540 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
541 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
542 'dgit-distro.ubuntu.git-check' => 'false',
543 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
544 'dgit-distro.test-dummy.ssh' => "$td/ssh",
545 'dgit-distro.test-dummy.username' => "alice",
546 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
547 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
548 'dgit-distro.test-dummy.git-url' => "$td/git",
549 'dgit-distro.test-dummy.git-host' => "git",
550 'dgit-distro.test-dummy.git-path' => "$td/git",
551 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
552 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
553 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
558 return undef if $c =~ /RETURN-UNDEF/;
559 my @cmd = (@git, qw(config --), $c);
562 local ($debug) = $debug-1;
563 $v = cmdoutput_errok @cmd;
570 my $dv = $defcfg{$c};
571 return $dv if defined $dv;
573 badcfg "need value for one of: @_\n".
574 "$us: distro or suite appears not to be (properly) supported";
577 sub access_basedistro () {
578 if (defined $idistro) {
581 return cfg("dgit-suite.$isuite.distro",
582 "dgit.default.distro");
586 sub access_quirk () {
587 # returns (quirk name, distro to use instead or undef, quirk-specific info)
588 my $basedistro = access_basedistro();
589 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
591 if (defined $backports_quirk) {
592 my $re = $backports_quirk;
593 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
595 $re =~ s/\%/([-0-9a-z_]+)/
596 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
597 if ($isuite =~ m/^$re$/) {
598 return ('backports',"$basedistro-backports",$1);
601 return ('none',undef);
604 sub access_distros () {
605 # Returns list of distros to try, in order
608 # 0. `instead of' distro name(s) we have been pointed to
609 # 1. the access_quirk distro, if any
610 # 2a. the user's specified distro, or failing that } basedistro
611 # 2b. the distro calculated from the suite }
612 my @l = access_basedistro();
614 my (undef,$quirkdistro) = access_quirk();
615 unshift @l, $quirkdistro;
616 unshift @l, $instead_distro;
617 return grep { defined } @l;
623 # The nesting of these loops determines the search order. We put
624 # the key loop on the outside so that we search all the distros
625 # for each key, before going on to the next key. That means that
626 # if access_cfg is called with a more specific, and then a less
627 # specific, key, an earlier distro can override the less specific
628 # without necessarily overriding any more specific keys. (If the
629 # distro wants to override the more specific keys it can simply do
630 # so; whereas if we did the loop the other way around, it would be
631 # impossible to for an earlier distro to override a less specific
632 # key but not the more specific ones without restating the unknown
633 # values of the more specific keys.
636 # We have to deal with RETURN-UNDEF specially, so that we don't
637 # terminate the search prematurely.
639 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
642 foreach my $d (access_distros()) {
643 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
645 push @cfgs, map { "dgit.default.$_" } @realkeys;
647 my $value = cfg(@cfgs);
651 sub string_to_ssh ($) {
653 if ($spec =~ m/\s/) {
654 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
660 sub access_cfg_ssh () {
661 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
662 if (!defined $gitssh) {
665 return string_to_ssh $gitssh;
669 sub access_runeinfo ($) {
671 return ": dgit ".access_basedistro()." $info ;";
674 sub access_someuserhost ($) {
676 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
677 defined($user) && length($user) or
678 $user = access_cfg("$some-user",'username');
679 my $host = access_cfg("$some-host");
680 return length($user) ? "$user\@$host" : $host;
683 sub access_gituserhost () {
684 return access_someuserhost('git');
687 sub access_giturl (;$) {
689 my $url = access_cfg('git-url','RETURN-UNDEF');
691 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
692 return undef unless defined $proto;
695 access_gituserhost().
696 access_cfg('git-path');
698 return "$url/$package.git";
701 sub parsecontrolfh ($$;$) {
702 my ($fh, $desc, $allowsigned) = @_;
703 our $dpkgcontrolhash_noissigned;
706 my %opts = ('name' => $desc);
707 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
708 $c = Dpkg::Control::Hash->new(%opts);
709 $c->parse($fh,$desc) or die "parsing of $desc failed";
710 last if $allowsigned;
711 last if $dpkgcontrolhash_noissigned;
712 my $issigned= $c->get_option('is_pgp_signed');
713 if (!defined $issigned) {
714 $dpkgcontrolhash_noissigned= 1;
715 seek $fh, 0,0 or die "seek $desc: $!";
716 } elsif ($issigned) {
717 fail "control file $desc is (already) PGP-signed. ".
718 " Note that dgit push needs to modify the .dsc and then".
719 " do the signature itself";
728 my ($file, $desc) = @_;
729 my $fh = new IO::Handle;
730 open $fh, '<', $file or die "$file: $!";
731 my $c = parsecontrolfh($fh,$desc);
732 $fh->error and die $!;
738 my ($dctrl,$field) = @_;
739 my $v = $dctrl->{$field};
740 return $v if defined $v;
741 fail "missing field $field in ".$v->get_option('name');
745 my $c = Dpkg::Control::Hash->new();
746 my $p = new IO::Handle;
747 my @cmd = (qw(dpkg-parsechangelog), @_);
748 open $p, '-|', @cmd or die $!;
750 $?=0; $!=0; close $p or failedcmd @cmd;
754 sub git_get_ref ($) {
756 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
758 $?==256 or fail "git show-ref failed (status $?)";
759 printdebug "ref $refname= [show-ref exited 1]\n";
762 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
763 printdebug "ref $refname=$1\n";
766 printdebug "ref $refname= [no match]\n";
773 defined $d or fail "getcwd failed: $!";
779 sub archive_query ($) {
781 my $query = access_cfg('archive-query','RETURN-UNDEF');
782 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
785 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
788 sub pool_dsc_subpath ($$) {
789 my ($vsn,$component) = @_; # $package is implict arg
790 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
791 return "/pool/$component/$prefix/$package/".dscfn($vsn);
794 sub archive_query_madison {
795 return map { [ @$_[0..1] ] } madison_get_parse(@_);
798 sub madison_get_parse {
799 my ($proto,$data) = @_;
800 die unless $proto eq 'madison';
802 $data= access_cfg('madison-distro','RETURN-UNDEF');
803 $data //= access_basedistro();
805 $rmad{$proto,$data,$package} ||= cmdoutput
806 qw(rmadison -asource),"-s$isuite","-u$data",$package;
807 my $rmad = $rmad{$proto,$data,$package};
810 foreach my $l (split /\n/, $rmad) {
811 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
812 \s*( [^ \t|]+ )\s* \|
813 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
814 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
815 $1 eq $package or die "$rmad $package ?";
822 $component = access_cfg('archive-query-default-component');
824 $5 eq 'source' or die "$rmad ?";
825 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
827 return sort { -version_compare($a->[0],$b->[0]); } @out;
830 sub canonicalise_suite_madison {
831 # madison canonicalises for us
832 my @r = madison_get_parse(@_);
834 "unable to canonicalise suite using package $package".
835 " which does not appear to exist in suite $isuite;".
836 " --existing-package may help";
841 my ($data,$runeinfo,$sql) = @_;
843 $data= access_someuserhost('sshpsql').':'.
844 access_cfg('sshpsql-dbname');
846 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
847 my ($userhost,$dbname) = ($`,$'); #';
849 my @cmd = (access_cfg_ssh, $userhost,
850 access_runeinfo("ssh-psql $runeinfo").
852 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
853 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
854 open P, "-|", @cmd or die $!;
857 printdebug("$debugprefix>|$_|\n");
860 $!=0; $?=0; close P or failedcmd @cmd;
862 my $nrows = pop @rows;
863 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
864 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
865 @rows = map { [ split /\|/, $_ ] } @rows;
866 my $ncols = scalar @{ shift @rows };
867 die if grep { scalar @$_ != $ncols } @rows;
871 sub sql_injection_check {
872 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
875 sub archive_query_sshpsql ($$) {
876 my ($proto,$data) = @_;
877 sql_injection_check $isuite, $package;
878 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
879 SELECT source.version, component.name, files.filename, files.sha256sum
881 JOIN src_associations ON source.id = src_associations.source
882 JOIN suite ON suite.id = src_associations.suite
883 JOIN dsc_files ON dsc_files.source = source.id
884 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
885 JOIN component ON component.id = files_archive_map.component_id
886 JOIN files ON files.id = dsc_files.file
887 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
888 AND source.source='$package'
889 AND files.filename LIKE '%.dsc';
891 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
892 my $digester = Digest::SHA->new(256);
894 my ($vsn,$component,$filename,$sha256sum) = @$_;
895 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
900 sub canonicalise_suite_sshpsql ($$) {
901 my ($proto,$data) = @_;
902 sql_injection_check $isuite;
903 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
904 SELECT suite.codename
905 FROM suite where suite_name='$isuite' or codename='$isuite';
907 @rows = map { $_->[0] } @rows;
908 fail "unknown suite $isuite" unless @rows;
909 die "ambiguous $isuite: @rows ?" if @rows>1;
913 sub canonicalise_suite_dummycat ($$) {
914 my ($proto,$data) = @_;
915 my $dpath = "$data/suite.$isuite";
916 if (!open C, "<", $dpath) {
917 $!==ENOENT or die "$dpath: $!";
918 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
922 chomp or die "$dpath: $!";
924 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
928 sub archive_query_dummycat ($$) {
929 my ($proto,$data) = @_;
930 canonicalise_suite();
931 my $dpath = "$data/package.$csuite.$package";
932 if (!open C, "<", $dpath) {
933 $!==ENOENT or die "$dpath: $!";
934 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
942 printdebug "dummycat query $csuite $package $dpath | $_\n";
943 my @row = split /\s+/, $_;
944 @row==2 or die "$dpath: $_ ?";
947 C->error and die "$dpath: $!";
949 return sort { -version_compare($a->[0],$b->[0]); } @rows;
952 sub canonicalise_suite () {
953 return if defined $csuite;
954 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
955 $csuite = archive_query('canonicalise_suite');
956 if ($isuite ne $csuite) {
957 progress "canonical suite name for $isuite is $csuite";
961 sub get_archive_dsc () {
962 canonicalise_suite();
963 my @vsns = archive_query('archive_query');
964 foreach my $vinfo (@vsns) {
965 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
966 $dscurl = access_cfg('mirror').$subpath;
967 $dscdata = url_get($dscurl);
969 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
974 $digester->add($dscdata);
975 my $got = $digester->hexdigest();
977 fail "$dscurl has hash $got but".
978 " archive told us to expect $digest";
980 my $dscfh = new IO::File \$dscdata, '<' or die $!;
981 printdebug Dumper($dscdata) if $debug>1;
982 $dsc = parsecontrolfh($dscfh,$dscurl,1);
983 printdebug Dumper($dsc) if $debug>1;
984 my $fmt = getfield $dsc, 'Format';
985 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
986 $dsc_checked = !!$digester;
992 sub check_for_git ();
993 sub check_for_git () {
995 my $how = access_cfg('git-check');
996 if ($how eq 'ssh-cmd') {
998 (access_cfg_ssh, access_gituserhost(),
999 access_runeinfo("git-check $package").
1000 " set -e; cd ".access_cfg('git-path').";".
1001 " if test -d $package.git; then echo 1; else echo 0; fi");
1002 my $r= cmdoutput @cmd;
1003 if ($r =~ m/^divert (\w+)$/) {
1005 my ($usedistro,) = access_distros();
1006 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1007 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1008 printdebug "diverting $divert so using distro $instead_distro\n";
1009 return check_for_git();
1011 failedcmd @cmd unless $r =~ m/^[01]$/;
1013 } elsif ($how eq 'true') {
1015 } elsif ($how eq 'false') {
1018 badcfg "unknown git-check \`$how'";
1022 sub create_remote_git_repo () {
1023 my $how = access_cfg('git-create');
1024 if ($how eq 'ssh-cmd') {
1026 (access_cfg_ssh, access_gituserhost(),
1027 access_runeinfo("git-create $package").
1028 "set -e; cd ".access_cfg('git-path').";".
1029 " cp -a _template $package.git");
1030 } elsif ($how eq 'true') {
1033 badcfg "unknown git-create \`$how'";
1037 our ($dsc_hash,$lastpush_hash);
1039 our $ud = '.git/dgit/unpack';
1044 mkdir $ud or die $!;
1047 sub mktree_in_ud_here () {
1048 runcmd qw(git init -q);
1049 rmtree('.git/objects');
1050 symlink '../../../../objects','.git/objects' or die $!;
1053 sub git_write_tree () {
1054 my $tree = cmdoutput @git, qw(write-tree);
1055 $tree =~ m/^\w+$/ or die "$tree ?";
1059 sub mktree_in_ud_from_only_subdir () {
1060 # changes into the subdir
1062 die unless @dirs==1;
1063 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1066 fail "source package contains .git directory" if stat_exists '.git';
1067 mktree_in_ud_here();
1068 my $format=get_source_format();
1069 if (madformat($format)) {
1072 runcmd @git, qw(add -Af);
1073 my $tree=git_write_tree();
1074 return ($tree,$dir);
1077 sub dsc_files_info () {
1078 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1079 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1080 ['Files', 'Digest::MD5', 'new()']) {
1081 my ($fname, $module, $method) = @$csumi;
1082 my $field = $dsc->{$fname};
1083 next unless defined $field;
1084 eval "use $module; 1;" or die $@;
1086 foreach (split /\n/, $field) {
1088 m/^(\w+) (\d+) (\S+)$/ or
1089 fail "could not parse .dsc $fname line \`$_'";
1090 my $digester = eval "$module"."->$method;" or die $@;
1095 Digester => $digester,
1100 fail "missing any supported Checksums-* or Files field in ".
1101 $dsc->get_option('name');
1105 map { $_->{Filename} } dsc_files_info();
1108 sub is_orig_file ($;$) {
1111 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1112 defined $base or return 1;
1116 sub make_commit ($) {
1118 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1121 sub clogp_authline ($) {
1123 my $author = getfield $clogp, 'Maintainer';
1124 $author =~ s#,.*##ms;
1125 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1126 my $authline = "$author $date";
1127 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1128 fail "unexpected commit author line format \`$authline'".
1129 " (was generated from changelog Maintainer field)";
1133 sub generate_commit_from_dsc () {
1137 foreach my $fi (dsc_files_info()) {
1138 my $f = $fi->{Filename};
1139 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1141 link "../../../$f", $f
1145 complete_file_from_dsc('.', $fi);
1147 if (is_orig_file($f)) {
1148 link $f, "../../../../$f"
1154 my $dscfn = "$package.dsc";
1156 open D, ">", $dscfn or die "$dscfn: $!";
1157 print D $dscdata or die "$dscfn: $!";
1158 close D or die "$dscfn: $!";
1159 my @cmd = qw(dpkg-source);
1160 push @cmd, '--no-check' if $dsc_checked;
1161 push @cmd, qw(-x --), $dscfn;
1164 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1165 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1166 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1167 my $authline = clogp_authline $clogp;
1168 my $changes = getfield $clogp, 'Changes';
1169 open C, ">../commit.tmp" or die $!;
1170 print C <<END or die $!;
1177 # imported from the archive
1180 my $outputhash = make_commit qw(../commit.tmp);
1181 my $cversion = getfield $clogp, 'Version';
1182 progress "synthesised git commit from .dsc $cversion";
1183 if ($lastpush_hash) {
1184 runcmd @git, qw(reset --hard), $lastpush_hash;
1185 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1186 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1187 my $oversion = getfield $oldclogp, 'Version';
1189 version_compare($oversion, $cversion);
1191 # git upload/ is earlier vsn than archive, use archive
1192 open C, ">../commit2.tmp" or die $!;
1193 print C <<END or die $!;
1195 parent $lastpush_hash
1200 Record $package ($cversion) in archive suite $csuite
1202 $outputhash = make_commit qw(../commit2.tmp);
1203 } elsif ($vcmp > 0) {
1204 print STDERR <<END or die $!;
1206 Version actually in archive: $cversion (older)
1207 Last allegedly pushed/uploaded: $oversion (newer or same)
1210 $outputhash = $lastpush_hash;
1212 $outputhash = $lastpush_hash;
1215 changedir '../../../..';
1216 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1217 'DGIT_ARCHIVE', $outputhash;
1218 cmdoutput @git, qw(log -n2), $outputhash;
1219 # ... gives git a chance to complain if our commit is malformed
1224 sub complete_file_from_dsc ($$) {
1225 our ($dstdir, $fi) = @_;
1226 # Ensures that we have, in $dir, the file $fi, with the correct
1227 # contents. (Downloading it from alongside $dscurl if necessary.)
1229 my $f = $fi->{Filename};
1230 my $tf = "$dstdir/$f";
1233 if (stat_exists $tf) {
1234 progress "using existing $f";
1237 $furl =~ s{/[^/]+$}{};
1239 die "$f ?" unless $f =~ m/^${package}_/;
1240 die "$f ?" if $f =~ m#/#;
1241 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1242 next if !act_local();
1246 open F, "<", "$tf" or die "$tf: $!";
1247 $fi->{Digester}->reset();
1248 $fi->{Digester}->addfile(*F);
1249 F->error and die $!;
1250 my $got = $fi->{Digester}->hexdigest();
1251 $got eq $fi->{Hash} or
1252 fail "file $f has hash $got but .dsc".
1253 " demands hash $fi->{Hash} ".
1254 ($downloaded ? "(got wrong file from archive!)"
1255 : "(perhaps you should delete this file?)");
1258 sub ensure_we_have_orig () {
1259 foreach my $fi (dsc_files_info()) {
1260 my $f = $fi->{Filename};
1261 next unless is_orig_file($f);
1262 complete_file_from_dsc('..', $fi);
1267 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1270 sub is_fast_fwd ($$) {
1271 my ($ancestor,$child) = @_;
1272 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1273 my $mb = cmdoutput_errok @cmd;
1275 return rev_parse($mb) eq rev_parse($ancestor);
1277 $?==256 or failedcmd @cmd;
1282 sub git_fetch_us () {
1283 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1286 sub fetch_from_archive () {
1287 # ensures that lrref() is what is actually in the archive,
1288 # one way or another
1292 foreach my $field (@ourdscfield) {
1293 $dsc_hash = $dsc->{$field};
1294 last if defined $dsc_hash;
1296 if (defined $dsc_hash) {
1297 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1299 progress "last upload to archive specified git hash";
1301 progress "last upload to archive has NO git hash";
1304 progress "no version available from the archive";
1307 $lastpush_hash = git_get_ref(lrref());
1308 printdebug "previous reference hash=$lastpush_hash\n";
1310 if (defined $dsc_hash) {
1311 fail "missing remote git history even though dsc has hash -".
1312 " could not find ref ".lrref().
1313 " (should have been fetched from ".access_giturl()."#".rrref().")"
1314 unless $lastpush_hash;
1316 ensure_we_have_orig();
1317 if ($dsc_hash eq $lastpush_hash) {
1318 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1319 print STDERR <<END or die $!;
1321 Git commit in archive is behind the last version allegedly pushed/uploaded.
1322 Commit referred to by archive: $dsc_hash
1323 Last allegedly pushed/uploaded: $lastpush_hash
1326 $hash = $lastpush_hash;
1328 fail "archive's .dsc refers to ".$dsc_hash.
1329 " but this is an ancestor of ".$lastpush_hash;
1332 $hash = generate_commit_from_dsc();
1333 } elsif ($lastpush_hash) {
1334 # only in git, not in the archive yet
1335 $hash = $lastpush_hash;
1336 print STDERR <<END or die $!;
1338 Package not found in the archive, but has allegedly been pushed using dgit.
1342 printdebug "nothing found!\n";
1343 if (defined $skew_warning_vsn) {
1344 print STDERR <<END or die $!;
1346 Warning: relevant archive skew detected.
1347 Archive allegedly contains $skew_warning_vsn
1348 But we were not able to obtain any version from the archive or git.
1354 printdebug "current hash=$hash\n";
1355 if ($lastpush_hash) {
1356 fail "not fast forward on last upload branch!".
1357 " (archive's version left in DGIT_ARCHIVE)"
1358 unless is_fast_fwd($lastpush_hash, $hash);
1360 if (defined $skew_warning_vsn) {
1362 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1363 my $clogf = ".git/dgit/changelog.tmp";
1364 runcmd shell_cmd "exec >$clogf",
1365 @git, qw(cat-file blob), "$hash:debian/changelog";
1366 my $gotclogp = parsechangelog("-l$clogf");
1367 my $got_vsn = getfield $gotclogp, 'Version';
1368 printdebug "SKEW CHECK GOT $got_vsn\n";
1369 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1370 print STDERR <<END or die $!;
1372 Warning: archive skew detected. Using the available version:
1373 Archive allegedly contains $skew_warning_vsn
1374 We were able to obtain only $got_vsn
1379 if ($lastpush_hash ne $hash) {
1380 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1384 dryrun_report @upd_cmd;
1392 canonicalise_suite();
1393 badusage "dry run makes no sense with clone" unless act_local();
1394 my $hasgit = check_for_git();
1395 mkdir $dstdir or die "$dstdir $!";
1397 runcmd @git, qw(init -q);
1398 my $giturl = access_giturl(1);
1399 if (defined $giturl) {
1400 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1401 open H, "> .git/HEAD" or die $!;
1402 print H "ref: ".lref()."\n" or die $!;
1404 runcmd @git, qw(remote add), 'origin', $giturl;
1407 progress "fetching existing git history";
1409 runcmd_ordryrun_local @git, qw(fetch origin);
1411 progress "starting new git history";
1413 fetch_from_archive() or no_such_package;
1414 my $vcsgiturl = $dsc->{'Vcs-Git'};
1415 if (length $vcsgiturl) {
1416 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1418 runcmd @git, qw(reset --hard), lrref();
1419 printdone "ready for work in $dstdir";
1423 if (check_for_git()) {
1426 fetch_from_archive() or no_such_package();
1427 printdone "fetched into ".lrref();
1432 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1434 printdone "fetched to ".lrref()." and merged into HEAD";
1437 sub check_not_dirty () {
1438 return if $ignoredirty;
1439 my @cmd = (@git, qw(diff --quiet HEAD));
1440 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1441 $!=0; $?=0; system @cmd;
1442 return if !$! && !$?;
1443 if (!$! && $?==256) {
1444 fail "working tree is dirty (does not match HEAD)";
1450 sub commit_admin ($) {
1453 runcmd_ordryrun_local @git, qw(commit -m), $m;
1456 sub commit_quilty_patch () {
1457 my $output = cmdoutput @git, qw(status --porcelain);
1459 foreach my $l (split /\n/, $output) {
1460 next unless $l =~ m/\S/;
1461 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1465 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1467 progress "nothing quilty to commit, ok.";
1470 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1471 commit_admin "Commit Debian 3.0 (quilt) metadata";
1474 sub get_source_format () {
1475 if (!open F, "debian/source/format") {
1476 die $! unless $!==&ENOENT;
1480 F->error and die $!;
1487 return 0 unless $format eq '3.0 (quilt)';
1489 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1492 progress "Format \`$format', checking/updating patch stack";
1496 sub push_parse_changelog ($) {
1499 my $clogp = Dpkg::Control::Hash->new();
1500 $clogp->load($clogpfn) or die;
1502 $package = getfield $clogp, 'Source';
1503 my $cversion = getfield $clogp, 'Version';
1504 my $tag = debiantag($cversion);
1505 runcmd @git, qw(check-ref-format), $tag;
1507 my $dscfn = dscfn($cversion);
1509 return ($clogp, $cversion, $tag, $dscfn);
1512 sub push_parse_dsc ($$$) {
1513 my ($dscfn,$dscfnwhat, $cversion) = @_;
1514 $dsc = parsecontrol($dscfn,$dscfnwhat);
1515 my $dversion = getfield $dsc, 'Version';
1516 my $dscpackage = getfield $dsc, 'Source';
1517 ($dscpackage eq $package && $dversion eq $cversion) or
1518 fail "$dscfn is for $dscpackage $dversion".
1519 " but debian/changelog is for $package $cversion";
1522 sub push_mktag ($$$$$$$) {
1523 my ($head,$clogp,$tag,
1525 $changesfile,$changesfilewhat,
1528 $dsc->{$ourdscfield[0]} = $head;
1529 $dsc->save("$dscfn.tmp") or die $!;
1531 my $changes = parsecontrol($changesfile,$changesfilewhat);
1532 foreach my $field (qw(Source Distribution Version)) {
1533 $changes->{$field} eq $clogp->{$field} or
1534 fail "changes field $field \`$changes->{$field}'".
1535 " does not match changelog \`$clogp->{$field}'";
1538 my $cversion = getfield $clogp, 'Version';
1539 my $clogsuite = getfield $clogp, 'Distribution';
1541 # We make the git tag by hand because (a) that makes it easier
1542 # to control the "tagger" (b) we can do remote signing
1543 my $authline = clogp_authline $clogp;
1544 open TO, '>', $tfn->('.tmp') or die $!;
1545 print TO <<END or die $!;
1551 $package release $cversion for $clogsuite ($csuite) [dgit]
1555 my $tagobjfn = $tfn->('.tmp');
1557 if (!defined $keyid) {
1558 $keyid = access_cfg('keyid','RETURN-UNDEF');
1560 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1561 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1562 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1563 push @sign_cmd, $tfn->('.tmp');
1564 runcmd_ordryrun @sign_cmd;
1566 $tagobjfn = $tfn->('.signed.tmp');
1567 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1568 $tfn->('.tmp'), $tfn->('.tmp.asc');
1575 sub sign_changes ($) {
1576 my ($changesfile) = @_;
1578 my @debsign_cmd = @debsign;
1579 push @debsign_cmd, "-k$keyid" if defined $keyid;
1580 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1581 push @debsign_cmd, $changesfile;
1582 runcmd_ordryrun @debsign_cmd;
1587 printdebug "actually entering push\n";
1590 access_giturl(); # check that success is vaguely likely
1592 my $clogpfn = ".git/dgit/changelog.822.tmp";
1593 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1595 responder_send_file('parsed-changelog', $clogpfn);
1597 my ($clogp, $cversion, $tag, $dscfn) =
1598 push_parse_changelog("$clogpfn");
1600 my $dscpath = "$buildproductsdir/$dscfn";
1601 stat_exists $dscpath or
1602 fail "looked for .dsc $dscfn, but $!;".
1603 " maybe you forgot to build";
1605 responder_send_file('dsc', $dscpath);
1607 push_parse_dsc($dscpath, $dscfn, $cversion);
1609 my $format = getfield $dsc, 'Format';
1610 printdebug "format $format\n";
1611 if (madformat($format)) {
1612 commit_quilty_patch();
1616 progress "checking that $dscfn corresponds to HEAD";
1617 runcmd qw(dpkg-source -x --),
1618 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1619 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1620 changedir '../../../..';
1621 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1622 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1623 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1625 my $r = system @diffcmd;
1628 fail "$dscfn specifies a different tree to your HEAD commit;".
1629 " perhaps you forgot to build".
1630 ($diffopt eq '--exit-code' ? "" :
1631 " (run with -D to see full diff output)");
1637 #do fast forward check and maybe fake merge
1638 # if (!is_fast_fwd(mainbranch
1639 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1640 # map { lref($_).":".rref($_) }
1642 my $head = rev_parse('HEAD');
1643 if (!$changesfile) {
1644 my $multi = "$buildproductsdir/".
1645 "${package}_".(stripepoch $cversion)."_multi.changes";
1646 if (stat_exists "$multi") {
1647 $changesfile = $multi;
1649 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1650 my @cs = glob "$buildproductsdir/$pat";
1651 fail "failed to find unique changes file".
1652 " (looked for $pat in $buildproductsdir, or $multi);".
1653 " perhaps you need to use dgit -C"
1655 ($changesfile) = @cs;
1658 $changesfile = "$buildproductsdir/$changesfile";
1661 responder_send_file('changes',$changesfile);
1662 responder_send_command("param head $head");
1663 responder_send_command("param csuite $csuite");
1665 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1668 if ($we_are_responder) {
1669 $tagobjfn = $tfn->('.signed.tmp');
1670 responder_receive_files('signed-tag', $tagobjfn);
1673 push_mktag($head,$clogp,$tag,
1675 $changesfile,$changesfile,
1679 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1680 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1681 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1682 runcmd_ordryrun @git, qw(tag -v --), $tag;
1684 if (!check_for_git()) {
1685 create_remote_git_repo();
1687 runcmd_ordryrun @git, qw(push),access_giturl(),
1688 "HEAD:".rrref(), "refs/tags/$tag";
1689 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1691 if ($we_are_responder) {
1692 my $dryrunsuffix = act_local() ? "" : ".tmp";
1693 responder_receive_files('signed-dsc-changes',
1694 "$dscpath$dryrunsuffix",
1695 "$changesfile$dryrunsuffix");
1698 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1700 progress "[new .dsc left in $dscpath.tmp]";
1702 sign_changes $changesfile;
1705 my $host = access_cfg('upload-host','RETURN-UNDEF');
1706 my @hostarg = defined($host) ? ($host,) : ();
1707 runcmd_ordryrun @dput, @hostarg, $changesfile;
1708 printdone "pushed and uploaded $cversion";
1710 responder_send_command("complete");
1716 badusage "-p is not allowed with clone; specify as argument instead"
1717 if defined $package;
1720 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1721 ($package,$isuite) = @ARGV;
1722 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1723 ($package,$dstdir) = @ARGV;
1724 } elsif (@ARGV==3) {
1725 ($package,$isuite,$dstdir) = @ARGV;
1727 badusage "incorrect arguments to dgit clone";
1729 $dstdir ||= "$package";
1731 if (stat_exists $dstdir) {
1732 fail "$dstdir already exists";
1736 if ($rmonerror && !$dryrun_level) {
1737 $cwd_remove= getcwd();
1739 return unless defined $cwd_remove;
1740 if (!chdir "$cwd_remove") {
1741 return if $!==&ENOENT;
1742 die "chdir $cwd_remove: $!";
1744 rmtree($dstdir) or die "remove $dstdir: $!\n";
1749 $cwd_remove = undef;
1752 sub branchsuite () {
1753 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1754 if ($branch =~ m#$lbranch_re#o) {
1761 sub fetchpullargs () {
1762 if (!defined $package) {
1763 my $sourcep = parsecontrol('debian/control','debian/control');
1764 $package = getfield $sourcep, 'Source';
1767 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1769 my $clogp = parsechangelog();
1770 $isuite = getfield $clogp, 'Distribution';
1772 canonicalise_suite();
1773 progress "fetching from suite $csuite";
1774 } elsif (@ARGV==1) {
1776 canonicalise_suite();
1778 badusage "incorrect arguments to dgit fetch or dgit pull";
1796 badusage "-p is not allowed with dgit push" if defined $package;
1798 my $clogp = parsechangelog();
1799 $package = getfield $clogp, 'Source';
1802 } elsif (@ARGV==1) {
1803 ($specsuite) = (@ARGV);
1805 badusage "incorrect arguments to dgit push";
1807 $isuite = getfield $clogp, 'Distribution';
1809 local ($package) = $existing_package; # this is a hack
1810 canonicalise_suite();
1812 if (defined $specsuite && $specsuite ne $isuite) {
1813 canonicalise_suite();
1814 $csuite eq $specsuite or
1815 fail "dgit push: changelog specifies $isuite ($csuite)".
1816 " but command line specifies $specsuite";
1818 if (check_for_git()) {
1821 if (fetch_from_archive()) {
1822 is_fast_fwd(lrref(), 'HEAD') or
1823 fail "dgit push: HEAD is not a descendant".
1824 " of the archive's version.\n".
1825 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1828 fail "package appears to be new in this suite;".
1829 " if this is intentional, use --new";
1834 #---------- remote commands' implementation ----------
1836 sub cmd_remote_push_build_host {
1837 my ($nrargs) = shift @ARGV;
1838 my (@rargs) = @ARGV[0..$nrargs-1];
1839 @ARGV = @ARGV[$nrargs..$#ARGV];
1841 my ($dir,$vsnwant) = @rargs;
1842 # vsnwant is a comma-separated list; we report which we have
1843 # chosen in our ready response (so other end can tell if they
1846 $we_are_responder = 1;
1848 open PI, "<&STDIN" or die $!;
1849 open STDIN, "/dev/null" or die $!;
1850 open PO, ">&STDOUT" or die $!;
1852 open STDOUT, ">&STDERR" or die $!;
1856 fail "build host has dgit rpush protocol version".
1857 " $rpushprotovsn but invocation host has $vsnwant"
1858 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1860 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1866 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1867 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1868 # a good error message)
1874 my $report = i_child_report();
1875 if (defined $report) {
1876 printdebug "($report)\n";
1877 } elsif ($i_child_pid) {
1878 printdebug "(killing build host child $i_child_pid)\n";
1879 kill 15, $i_child_pid;
1881 if (defined $i_tmp && !defined $initiator_tempdir) {
1883 eval { rmtree $i_tmp; };
1887 END { i_cleanup(); }
1890 my ($base,$selector,@args) = @_;
1891 $selector =~ s/\-/_/g;
1892 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1898 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1905 my @rargs = ($dir,$rpushprotovsn);
1908 push @rdgit, @ropts;
1909 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1911 my @cmd = (@ssh, $host, shellquote @rdgit);
1912 printcmd \*DEBUG,$debugprefix."+",@cmd;
1914 if (defined $initiator_tempdir) {
1915 rmtree $initiator_tempdir;
1916 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1917 $i_tmp = $initiator_tempdir;
1921 $i_child_pid = open2(\*RO, \*RI, @cmd);
1923 initiator_expect { m/^dgit-remote-push-ready/ };
1925 my ($icmd,$iargs) = initiator_expect {
1926 m/^(\S+)(?: (.*))?$/;
1929 i_method "i_resp", $icmd, $iargs;
1933 sub i_resp_progress ($) {
1935 my $msg = protocol_read_bytes \*RO, $rhs;
1939 sub i_resp_complete {
1940 my $pid = $i_child_pid;
1941 $i_child_pid = undef; # prevents killing some other process with same pid
1942 printdebug "waiting for build host child $pid...\n";
1943 my $got = waitpid $pid, 0;
1944 die $! unless $got == $pid;
1945 die "build host child failed $?" if $?;
1948 printdebug "all done\n";
1952 sub i_resp_file ($) {
1954 my $localname = i_method "i_localname", $keyword;
1955 my $localpath = "$i_tmp/$localname";
1956 stat_exists $localpath and
1957 badproto \*RO, "file $keyword ($localpath) twice";
1958 protocol_receive_file \*RO, $localpath;
1959 i_method "i_file", $keyword;
1964 sub i_resp_param ($) {
1965 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1971 sub i_resp_want ($) {
1973 die "$keyword ?" if $i_wanted{$keyword}++;
1974 my @localpaths = i_method "i_want", $keyword;
1975 printdebug "[[ $keyword @localpaths\n";
1976 foreach my $localpath (@localpaths) {
1977 protocol_send_file \*RI, $localpath;
1979 print RI "files-end\n" or die $!;
1982 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1984 sub i_localname_parsed_changelog {
1985 return "remote-changelog.822";
1987 sub i_file_parsed_changelog {
1988 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1989 push_parse_changelog "$i_tmp/remote-changelog.822";
1990 die if $i_dscfn =~ m#/|^\W#;
1993 sub i_localname_dsc {
1994 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1999 sub i_localname_changes {
2000 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
2001 $i_changesfn = $i_dscfn;
2002 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
2003 return $i_changesfn;
2005 sub i_file_changes { }
2007 sub i_want_signed_tag {
2008 printdebug Dumper(\%i_param, $i_dscfn);
2009 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2010 && defined $i_param{'csuite'}
2011 or badproto \*RO, "premature desire for signed-tag";
2012 my $head = $i_param{'head'};
2013 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2015 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2017 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2020 push_mktag $head, $i_clogp, $i_tag,
2022 $i_changesfn, 'remote changes',
2023 sub { "tag$_[0]"; };
2028 sub i_want_signed_dsc_changes {
2029 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2030 sign_changes $i_changesfn;
2031 return ($i_dscfn, $i_changesfn);
2034 #---------- building etc. ----------
2040 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2042 sub quiltify_dpkg_commit ($$$;$) {
2043 my ($patchname,$author,$msg, $xinfo) = @_;
2047 my $descfn = ".git/dgit/quilt-description.tmp";
2048 open O, '>', $descfn or die "$descfn: $!";
2051 $msg =~ s/^\s+$/ ./mg;
2052 print O <<END or die $!;
2062 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2063 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2064 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2065 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2070 my ($clogp,$headref) = @_;
2074 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2076 quiltify_dpkg_commit "auto-$version-$headref-$time",
2077 (getfield $clogp, 'Maintainer'),
2078 "Automatically generated patch ($clogp->{Version})\n".
2079 "Last (up to) $ncommits git changes, FYI:\n\n". $msg;
2082 sub build_maybe_quilt_fixup () {
2083 my $format=get_source_format;
2084 return unless madformat $format;
2088 # - honour any existing .pc in case it has any strangeness
2089 # - determine the git commit corresponding to the tip of
2090 # the patch stack (if there is one)
2091 # - if there is such a git commit, convert each subsequent
2092 # git commit into a quilt patch with dpkg-source --commit
2093 # - otherwise convert all the differences in the tree into
2094 # a single git commit
2098 # Our git tree doesn't necessarily contain .pc. (Some versions of
2099 # dgit would include the .pc in the git tree.) If there isn't
2100 # one, we need to generate one by unpacking the patches that we
2103 # We first look for a .pc in the git tree. If there is one, we
2104 # will use it. (This is not the normal case.)
2106 # Otherwise need to regenerate .pc so that dpkg-source --commit
2107 # can work. We do this as follows:
2108 # 1. Collect all relevant .orig from parent directory
2109 # 2. Generate a debian.tar.gz out of
2110 # debian/{patches,rules,source/format}
2111 # 3. Generate a fake .dsc containing just these fields:
2112 # Format Source Version Files
2113 # 4. Extract the fake .dsc
2114 # Now the fake .dsc has a .pc directory.
2115 # (In fact we do this in every case, because in future we will
2116 # want to search for a good base commit for generating patches.)
2118 # Then we can actually do the dpkg-source --commit
2119 # 1. Make a new working tree with the same object
2120 # store as our main tree and check out the main
2122 # 2. Copy .pc from the fake's extraction, if necessary
2123 # 3. Run dpkg-source --commit
2124 # 4. If the result has changes to debian/, then
2125 # - git-add them them
2126 # - git-add .pc if we had a .pc in-tree
2128 # 5. If we had a .pc in-tree, delete it, and git-commit
2129 # 6. Back in the main tree, fast forward to the new HEAD
2131 my $clogp = parsechangelog();
2132 my $headref = rev_parse('HEAD');
2137 my $upstreamversion=$version;
2138 $upstreamversion =~ s/-[^-]*$//;
2140 my $fakeversion="$upstreamversion-~~DGITFAKE";
2142 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2143 print $fakedsc <<END or die $!;
2146 Version: $fakeversion
2150 my $dscaddfile=sub {
2153 my $md = new Digest::MD5;
2155 my $fh = new IO::File $b, '<' or die "$b $!";
2160 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2163 foreach my $f (<../../../../*>) { #/){
2164 my $b=$f; $b =~ s{.*/}{};
2165 next unless is_orig_file $b, srcfn $upstreamversion,'';
2166 link $f, $b or die "$b $!";
2170 my @files=qw(debian/source/format debian/rules);
2171 if (stat_exists '../../../debian/patches') {
2172 push @files, 'debian/patches';
2175 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2176 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2178 $dscaddfile->($debtar);
2179 close $fakedsc or die $!;
2181 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2183 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2184 rename $fakexdir, "fake" or die "$fakexdir $!";
2186 mkdir "work" or die $!;
2188 mktree_in_ud_here();
2189 runcmd @git, qw(reset --hard), $headref;
2192 if (stat_exists ".pc") {
2194 progress "Tree already contains .pc - will use it then delete it.";
2197 rename '../fake/.pc','.pc' or die $!;
2200 quiltify($clogp,$headref);
2202 if (!open P, '>>', ".pc/applied-patches") {
2203 $!==&ENOENT or die $!;
2208 commit_quilty_patch();
2210 if ($mustdeletepc) {
2211 runcmd @git, qw(rm -rq .pc);
2212 commit_admin "Commit removal of .pc (quilt series tracking data)";
2215 changedir '../../../..';
2216 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2219 sub quilt_fixup_editor () {
2220 my $descfn = $ENV{$fakeeditorenv};
2221 my $editing = $ARGV[$#ARGV];
2222 open I1, '<', $descfn or die "$descfn: $!";
2223 open I2, '<', $editing or die "$editing: $!";
2224 unlink $editing or die "$editing: $!";
2225 open O, '>', $editing or die "$editing: $!";
2226 while (<I1>) { print O or die $!; } I1->error and die $!;
2229 $copying ||= m/^\-\-\- /;
2230 next unless $copying;
2233 I2->error and die $!;
2239 if ($cleanmode eq 'dpkg-source') {
2240 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2241 } elsif ($cleanmode eq 'git') {
2242 runcmd_ordryrun_local @git, qw(clean -xdf);
2243 } elsif ($cleanmode eq 'none') {
2250 badusage "clean takes no additional arguments" if @ARGV;
2255 badusage "-p is not allowed when building" if defined $package;
2258 my $clogp = parsechangelog();
2259 $isuite = getfield $clogp, 'Distribution';
2260 $package = getfield $clogp, 'Source';
2261 $version = getfield $clogp, 'Version';
2262 build_maybe_quilt_fixup();
2265 sub changesopts () {
2266 my @opts =@changesopts[1..$#changesopts];
2267 if (!defined $changes_since_version) {
2268 my @vsns = archive_query('archive_query');
2269 my @quirk = access_quirk();
2270 if ($quirk[0] eq 'backports') {
2271 local $isuite = $quirk[2];
2273 canonicalise_suite();
2274 push @vsns, archive_query('archive_query');
2277 @vsns = map { $_->[0] } @vsns;
2278 @vsns = sort { -version_compare($a, $b) } @vsns;
2279 $changes_since_version = $vsns[0];
2280 progress "changelog will contain changes since $vsns[0]";
2282 $changes_since_version = '_';
2283 progress "package seems new, not specifying -v<version>";
2286 if ($changes_since_version ne '_') {
2287 unshift @opts, "-v$changes_since_version";
2294 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2295 printdone "build successful\n";
2301 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2302 "--git-builder=@dpkgbuildpackage");
2303 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2304 canonicalise_suite();
2305 push @cmd, "--git-debian-branch=".lbranch();
2307 push @cmd, changesopts();
2308 runcmd_ordryrun_local @cmd, @ARGV;
2309 printdone "build successful\n";
2314 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2315 $dscfn = dscfn($version);
2316 if ($cleanmode eq 'dpkg-source') {
2317 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2320 my $pwd = must_getcwd();
2321 my $leafdir = basename $pwd;
2323 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2325 runcmd_ordryrun_local qw(sh -ec),
2326 'exec >$1; shift; exec "$@"','x',
2327 "../$sourcechanges",
2328 @dpkggenchanges, qw(-S), changesopts();
2332 sub cmd_build_source {
2333 badusage "build-source takes no additional arguments" if @ARGV;
2335 printdone "source built, results in $dscfn and $sourcechanges";
2341 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2343 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2344 stat_exists $sourcechanges
2345 or fail "$sourcechanges (in parent directory): $!";
2346 foreach my $cf (glob $pat) {
2347 next if $cf eq $sourcechanges;
2348 unlink $cf or fail "remove $cf: $!";
2351 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2352 my @changesfiles = glob $pat;
2353 @changesfiles = sort {
2354 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2357 fail "wrong number of different changes files (@changesfiles)"
2358 unless @changesfiles;
2359 runcmd_ordryrun_local @mergechanges, @changesfiles;
2360 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2362 stat_exists $multichanges or fail "$multichanges: $!";
2364 printdone "build successful, results in $multichanges\n" or die $!;
2367 sub cmd_quilt_fixup {
2368 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2369 my $clogp = parsechangelog();
2370 $version = getfield $clogp, 'Version';
2371 $package = getfield $clogp, 'Source';
2372 build_maybe_quilt_fixup();
2375 #---------- argument parsing and main program ----------
2378 print "dgit version $our_version\n" or die $!;
2385 if (defined $ENV{'DGIT_SSH'}) {
2386 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2387 } elsif (defined $ENV{'GIT_SSH'}) {
2388 @ssh = ($ENV{'GIT_SSH'});
2392 last unless $ARGV[0] =~ m/^-/;
2396 if (m/^--dry-run$/) {
2399 } elsif (m/^--damp-run$/) {
2402 } elsif (m/^--no-sign$/) {
2405 } elsif (m/^--help$/) {
2407 } elsif (m/^--version$/) {
2409 } elsif (m/^--new$/) {
2412 } elsif (m/^--since-version=([^_]+|_)$/) {
2414 $changes_since_version = $1;
2415 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2416 ($om = $opts_opt_map{$1}) &&
2420 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2421 !$opts_opt_cmdonly{$1} &&
2422 ($om = $opts_opt_map{$1})) {
2425 } elsif (m/^--existing-package=(.*)/s) {
2427 $existing_package = $1;
2428 } elsif (m/^--initiator-tempdir=(.*)/s) {
2429 $initiator_tempdir = $1;
2430 $initiator_tempdir =~ m#^/# or
2431 badusage "--initiator-tempdir must be used specify an".
2432 " absolute, not relative, directory."
2433 } elsif (m/^--distro=(.*)/s) {
2436 } elsif (m/^--build-products-dir=(.*)/s) {
2438 $buildproductsdir = $1;
2439 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2442 } elsif (m/^--clean=(.*)$/s) {
2443 badusage "unknown cleaning mode \`$1'";
2444 } elsif (m/^--ignore-dirty$/s) {
2447 } elsif (m/^--no-quilt-fixup$/s) {
2450 } elsif (m/^--no-rm-on-error$/s) {
2454 badusage "unknown long option \`$_'";
2461 } elsif (s/^-L/-/) {
2464 } elsif (s/^-h/-/) {
2466 } elsif (s/^-D/-/) {
2468 open DEBUG, ">&STDERR" or die $!;
2471 } elsif (s/^-N/-/) {
2474 } elsif (s/^-v([^_]+|_)$//s) {
2476 $changes_since_version = $1;
2479 push @changesopts, $_;
2481 } elsif (s/^-c(.*=.*)//s) {
2483 push @git, '-c', $1;
2484 } elsif (s/^-d(.*)//s) {
2487 } elsif (s/^-C(.*)//s) {
2490 if ($changesfile =~ s#^(.*)/##) {
2491 $buildproductsdir = $1;
2493 } elsif (s/^-k(.*)//s) {
2495 } elsif (s/^-wn//s) {
2497 $cleanmode = 'none';
2498 } elsif (s/^-wg//s) {
2501 } elsif (s/^-wd//s) {
2503 $cleanmode = 'dpkg-source';
2505 badusage "unknown short option \`$_'";
2512 if ($ENV{$fakeeditorenv}) {
2513 quilt_fixup_editor();
2517 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2518 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2519 if $dryrun_level == 1;
2521 print STDERR $helpmsg or die $!;
2524 my $cmd = shift @ARGV;
2527 my $fn = ${*::}{"cmd_$cmd"};
2528 $fn or badusage "unknown operation $cmd";