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' => 'dgit-git.debian.net',
524 'dgit-distro.debian.git-user-force' => 'dgit',
525 'dgit-distro.debian.git-proto' => 'git+ssh://',
526 'dgit-distro.debian.git-path' => '/dgit/debian/repos',
527 'dgit-distro.debian.diverts.alioth' => '/alioth',
528 'dgit-distro.debian/alioth.git-host' => 'git.debian.org',
529 'dgit-distro.debian/alioth.git-user-force' => '',
530 'dgit-distro.debian/alioth.git-proto' => 'git+ssh://',
531 'dgit-distro.debian/alioth.git-path' => '/git/dgit-repos/repos',
532 'dgit-distro.debian.git-check' => 'ssh-cmd',
533 'dgit-distro.debian.git-create' => 'ssh-cmd',
534 'dgit-distro.debian.sshpsql-host' => 'mirror.ftp-master.debian.org',
535 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
536 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/',
537 'dgit-distro.debian.backports-quirk' => '(squeeze)-backports*',
538 'dgit-distro.debian-backports.mirror' => 'http://backports.debian.org/debian-backports/',
539 'dgit-distro.ubuntu.git-check' => 'false',
540 'dgit-distro.ubuntu.mirror' => 'http://archive.ubuntu.com/ubuntu',
541 'dgit-distro.test-dummy.ssh' => "$td/ssh",
542 'dgit-distro.test-dummy.username' => "alice",
543 'dgit-distro.test-dummy.git-check' => "ssh-cmd",
544 'dgit-distro.test-dummy.git-create' => "ssh-cmd",
545 'dgit-distro.test-dummy.git-url' => "$td/git",
546 'dgit-distro.test-dummy.git-host' => "git",
547 'dgit-distro.test-dummy.git-path' => "$td/git",
548 'dgit-distro.test-dummy.archive-query' => "dummycat:$td/aq",
549 'dgit-distro.test-dummy.mirror' => "file://$td/mirror/",
550 'dgit-distro.test-dummy.upload-host' => 'test-dummy',
555 return undef if $c =~ /RETURN-UNDEF/;
556 my @cmd = (@git, qw(config --), $c);
559 local ($debug) = $debug-1;
560 $v = cmdoutput_errok @cmd;
567 my $dv = $defcfg{$c};
568 return $dv if defined $dv;
570 badcfg "need value for one of: @_\n".
571 "$us: distro or suite appears not to be (properly) supported";
574 sub access_basedistro () {
575 if (defined $idistro) {
578 return cfg("dgit-suite.$isuite.distro",
579 "dgit.default.distro");
583 sub access_quirk () {
584 # returns (quirk name, distro to use instead or undef, quirk-specific info)
585 my $basedistro = access_basedistro();
586 my $backports_quirk = cfg("dgit-distro.$basedistro.backports-quirk",
588 if (defined $backports_quirk) {
589 my $re = $backports_quirk;
590 $re =~ s/[^-0-9a-z_\%*()]/\\$&/ig;
592 $re =~ s/\%/([-0-9a-z_]+)/
593 or $re =~ m/[()]/ or badcfg "backports-quirk needs \% or ( )";
594 if ($isuite =~ m/^$re$/) {
595 return ('backports',"$basedistro-backports",$1);
598 return ('none',undef);
601 sub access_distros () {
602 # Returns list of distros to try, in order
605 # 0. `instead of' distro name(s) we have been pointed to
606 # 1. the access_quirk distro, if any
607 # 2a. the user's specified distro, or failing that } basedistro
608 # 2b. the distro calculated from the suite }
609 my @l = access_basedistro();
611 my (undef,$quirkdistro) = access_quirk();
612 unshift @l, $quirkdistro;
613 unshift @l, $instead_distro;
614 return grep { defined } @l;
620 # The nesting of these loops determines the search order. We put
621 # the key loop on the outside so that we search all the distros
622 # for each key, before going on to the next key. That means that
623 # if access_cfg is called with a more specific, and then a less
624 # specific, key, an earlier distro can override the less specific
625 # without necessarily overriding any more specific keys. (If the
626 # distro wants to override the more specific keys it can simply do
627 # so; whereas if we did the loop the other way around, it would be
628 # impossible to for an earlier distro to override a less specific
629 # key but not the more specific ones without restating the unknown
630 # values of the more specific keys.
633 # We have to deal with RETURN-UNDEF specially, so that we don't
634 # terminate the search prematurely.
636 if (m/RETURN-UNDEF/) { push @rundef, $_; last; }
639 foreach my $d (access_distros()) {
640 push @cfgs, map { "dgit-distro.$d.$_" } @realkeys;
642 push @cfgs, map { "dgit.default.$_" } @realkeys;
644 my $value = cfg(@cfgs);
648 sub string_to_ssh ($) {
650 if ($spec =~ m/\s/) {
651 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
657 sub access_cfg_ssh () {
658 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
659 if (!defined $gitssh) {
662 return string_to_ssh $gitssh;
666 sub access_runeinfo ($) {
668 return ": dgit ".access_basedistro()." $info ;";
671 sub access_someuserhost ($) {
673 my $user = access_cfg("$some-user-force", 'RETURN-UNDEF');
674 defined($user) && length($user) or
675 $user = access_cfg("$some-user",'username');
676 my $host = access_cfg("$some-host");
677 return length($user) ? "$user\@$host" : $host;
680 sub access_gituserhost () {
681 return access_someuserhost('git');
684 sub access_giturl (;$) {
686 my $url = access_cfg('git-url','RETURN-UNDEF');
688 my $proto = access_cfg('git-proto', 'RETURN-UNDEF');
689 return undef unless defined $proto;
692 access_gituserhost().
693 access_cfg('git-path');
695 return "$url/$package.git";
698 sub parsecontrolfh ($$;$) {
699 my ($fh, $desc, $allowsigned) = @_;
700 our $dpkgcontrolhash_noissigned;
703 my %opts = ('name' => $desc);
704 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
705 $c = Dpkg::Control::Hash->new(%opts);
706 $c->parse($fh,$desc) or die "parsing of $desc failed";
707 last if $allowsigned;
708 last if $dpkgcontrolhash_noissigned;
709 my $issigned= $c->get_option('is_pgp_signed');
710 if (!defined $issigned) {
711 $dpkgcontrolhash_noissigned= 1;
712 seek $fh, 0,0 or die "seek $desc: $!";
713 } elsif ($issigned) {
714 fail "control file $desc is (already) PGP-signed. ".
715 " Note that dgit push needs to modify the .dsc and then".
716 " do the signature itself";
725 my ($file, $desc) = @_;
726 my $fh = new IO::Handle;
727 open $fh, '<', $file or die "$file: $!";
728 my $c = parsecontrolfh($fh,$desc);
729 $fh->error and die $!;
735 my ($dctrl,$field) = @_;
736 my $v = $dctrl->{$field};
737 return $v if defined $v;
738 fail "missing field $field in ".$v->get_option('name');
742 my $c = Dpkg::Control::Hash->new();
743 my $p = new IO::Handle;
744 my @cmd = (qw(dpkg-parsechangelog), @_);
745 open $p, '-|', @cmd or die $!;
747 $?=0; $!=0; close $p or failedcmd @cmd;
751 sub git_get_ref ($) {
753 my $got = cmdoutput_errok @git, qw(show-ref --), $refname;
755 $?==256 or fail "git show-ref failed (status $?)";
756 printdebug "ref $refname= [show-ref exited 1]\n";
759 if ($got =~ m/^(\w+) \Q$refname\E$/m) {
760 printdebug "ref $refname=$1\n";
763 printdebug "ref $refname= [no match]\n";
770 defined $d or fail "getcwd failed: $!";
776 sub archive_query ($) {
778 my $query = access_cfg('archive-query','RETURN-UNDEF');
779 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
782 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
785 sub pool_dsc_subpath ($$) {
786 my ($vsn,$component) = @_; # $package is implict arg
787 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
788 return "/pool/$component/$prefix/$package/".dscfn($vsn);
791 sub archive_query_madison {
792 return map { [ @$_[0..1] ] } madison_get_parse(@_);
795 sub madison_get_parse {
796 my ($proto,$data) = @_;
797 die unless $proto eq 'madison';
799 $data= access_cfg('madison-distro','RETURN-UNDEF');
800 $data //= access_basedistro();
802 $rmad{$proto,$data,$package} ||= cmdoutput
803 qw(rmadison -asource),"-s$isuite","-u$data",$package;
804 my $rmad = $rmad{$proto,$data,$package};
807 foreach my $l (split /\n/, $rmad) {
808 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
809 \s*( [^ \t|]+ )\s* \|
810 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
811 \s*( [^ \t|]+ )\s* }x or die "$rmad ?";
812 $1 eq $package or die "$rmad $package ?";
819 $component = access_cfg('archive-query-default-component');
821 $5 eq 'source' or die "$rmad ?";
822 push @out, [$vsn,pool_dsc_subpath($vsn,$component),$newsuite];
824 return sort { -version_compare($a->[0],$b->[0]); } @out;
827 sub canonicalise_suite_madison {
828 # madison canonicalises for us
829 my @r = madison_get_parse(@_);
831 "unable to canonicalise suite using package $package".
832 " which does not appear to exist in suite $isuite;".
833 " --existing-package may help";
838 my ($data,$runeinfo,$sql) = @_;
840 $data= access_someuserhost('sshpsql').':'.
841 access_cfg('sshpsql-dbname');
843 $data =~ m/:/ or badcfg "invalid sshpsql method string \`$data'";
844 my ($userhost,$dbname) = ($`,$'); #';
846 my @cmd = (access_cfg_ssh, $userhost,
847 access_runeinfo("ssh-psql $runeinfo").
849 " ".shellquote qw(psql -A), $dbname, qw(-c), $sql);
850 printcmd(\*DEBUG,$debugprefix."|",@cmd) if $debug>0;
851 open P, "-|", @cmd or die $!;
854 printdebug("$debugprefix>|$_|\n");
857 $!=0; $?=0; close P or failedcmd @cmd;
859 my $nrows = pop @rows;
860 $nrows =~ s/^\((\d+) rows?\)$/$1/ or die "$nrows ?";
861 @rows == $nrows+1 or die "$nrows ".(scalar @rows)." ?";
862 @rows = map { [ split /\|/, $_ ] } @rows;
863 my $ncols = scalar @{ shift @rows };
864 die if grep { scalar @$_ != $ncols } @rows;
868 sub sql_injection_check {
869 foreach (@_) { die "$_ $& ?" if m{[^-+=:_.,/0-9a-zA-Z]}; }
872 sub archive_query_sshpsql ($$) {
873 my ($proto,$data) = @_;
874 sql_injection_check $isuite, $package;
875 my @rows = sshpsql($data, "archive-query $isuite $package", <<END);
876 SELECT source.version, component.name, files.filename, files.sha256sum
878 JOIN src_associations ON source.id = src_associations.source
879 JOIN suite ON suite.id = src_associations.suite
880 JOIN dsc_files ON dsc_files.source = source.id
881 JOIN files_archive_map ON files_archive_map.file_id = dsc_files.file
882 JOIN component ON component.id = files_archive_map.component_id
883 JOIN files ON files.id = dsc_files.file
884 WHERE ( suite.suite_name='$isuite' OR suite.codename='$isuite' )
885 AND source.source='$package'
886 AND files.filename LIKE '%.dsc';
888 @rows = sort { -version_compare($a->[0],$b->[0]) } @rows;
889 my $digester = Digest::SHA->new(256);
891 my ($vsn,$component,$filename,$sha256sum) = @$_;
892 [ $vsn, "/pool/$component/$filename",$digester,$sha256sum ];
897 sub canonicalise_suite_sshpsql ($$) {
898 my ($proto,$data) = @_;
899 sql_injection_check $isuite;
900 my @rows = sshpsql($data, "canonicalise-suite $isuite", <<END);
901 SELECT suite.codename
902 FROM suite where suite_name='$isuite' or codename='$isuite';
904 @rows = map { $_->[0] } @rows;
905 fail "unknown suite $isuite" unless @rows;
906 die "ambiguous $isuite: @rows ?" if @rows>1;
910 sub canonicalise_suite_dummycat ($$) {
911 my ($proto,$data) = @_;
912 my $dpath = "$data/suite.$isuite";
913 if (!open C, "<", $dpath) {
914 $!==ENOENT or die "$dpath: $!";
915 printdebug "dummycat canonicalise_suite $isuite $dpath ENOENT\n";
919 chomp or die "$dpath: $!";
921 printdebug "dummycat canonicalise_suite $isuite $dpath = $_\n";
925 sub archive_query_dummycat ($$) {
926 my ($proto,$data) = @_;
927 canonicalise_suite();
928 my $dpath = "$data/package.$csuite.$package";
929 if (!open C, "<", $dpath) {
930 $!==ENOENT or die "$dpath: $!";
931 printdebug "dummycat query $csuite $package $dpath ENOENT\n";
939 printdebug "dummycat query $csuite $package $dpath | $_\n";
940 my @row = split /\s+/, $_;
941 @row==2 or die "$dpath: $_ ?";
944 C->error and die "$dpath: $!";
946 return sort { -version_compare($a->[0],$b->[0]); } @rows;
949 sub canonicalise_suite () {
950 return if defined $csuite;
951 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
952 $csuite = archive_query('canonicalise_suite');
953 if ($isuite ne $csuite) {
954 progress "canonical suite name for $isuite is $csuite";
958 sub get_archive_dsc () {
959 canonicalise_suite();
960 my @vsns = archive_query('archive_query');
961 foreach my $vinfo (@vsns) {
962 my ($vsn,$subpath,$digester,$digest) = @$vinfo;
963 $dscurl = access_cfg('mirror').$subpath;
964 $dscdata = url_get($dscurl);
966 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
971 $digester->add($dscdata);
972 my $got = $digester->hexdigest();
974 fail "$dscurl has hash $got but".
975 " archive told us to expect $digest";
977 my $dscfh = new IO::File \$dscdata, '<' or die $!;
978 printdebug Dumper($dscdata) if $debug>1;
979 $dsc = parsecontrolfh($dscfh,$dscurl,1);
980 printdebug Dumper($dsc) if $debug>1;
981 my $fmt = getfield $dsc, 'Format';
982 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
983 $dsc_checked = !!$digester;
989 sub check_for_git ();
990 sub check_for_git () {
992 my $how = access_cfg('git-check');
993 if ($how eq 'ssh-cmd') {
995 (access_cfg_ssh, access_gituserhost(),
996 access_runeinfo("git-check $package").
997 " set -e; cd ".access_cfg('git-path').";".
998 " if test -d $package.git; then echo 1; else echo 0; fi");
999 my $r= cmdoutput @cmd;
1000 if ($r =~ m/^divert (\w+)$/) {
1002 my ($usedistro,) = access_distros();
1003 $instead_distro= cfg("dgit-distro.$usedistro.diverts.$divert");
1004 $instead_distro =~ s{^/}{ access_basedistro()."/" }e;
1005 printdebug "diverting $divert so using distro $instead_distro\n";
1006 return check_for_git();
1008 failedcmd @cmd unless $r =~ m/^[01]$/;
1010 } elsif ($how eq 'true') {
1012 } elsif ($how eq 'false') {
1015 badcfg "unknown git-check \`$how'";
1019 sub create_remote_git_repo () {
1020 my $how = access_cfg('git-create');
1021 if ($how eq 'ssh-cmd') {
1023 (access_cfg_ssh, access_gituserhost(),
1024 access_runeinfo("git-create $package").
1025 "set -e; cd ".access_cfg('git-path').";".
1026 " cp -a _template $package.git");
1027 } elsif ($how eq 'true') {
1030 badcfg "unknown git-create \`$how'";
1034 our ($dsc_hash,$lastpush_hash);
1036 our $ud = '.git/dgit/unpack';
1041 mkdir $ud or die $!;
1044 sub mktree_in_ud_here () {
1045 runcmd qw(git init -q);
1046 rmtree('.git/objects');
1047 symlink '../../../../objects','.git/objects' or die $!;
1050 sub mktree_in_ud_from_only_subdir () {
1051 # changes into the subdir
1053 die unless @dirs==1;
1054 $dirs[0] =~ m#^([^/]+)/\.$# or die;
1057 fail "source package contains .git directory" if stat_exists '.git';
1058 mktree_in_ud_here();
1059 my $format=get_source_format();
1060 if (madformat($format)) {
1063 runcmd @git, qw(add -Af);
1064 my $tree = cmdoutput @git, qw(write-tree);
1065 $tree =~ m/^\w+$/ or die "$tree ?";
1066 return ($tree,$dir);
1069 sub dsc_files_info () {
1070 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
1071 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
1072 ['Files', 'Digest::MD5', 'new()']) {
1073 my ($fname, $module, $method) = @$csumi;
1074 my $field = $dsc->{$fname};
1075 next unless defined $field;
1076 eval "use $module; 1;" or die $@;
1078 foreach (split /\n/, $field) {
1080 m/^(\w+) (\d+) (\S+)$/ or
1081 fail "could not parse .dsc $fname line \`$_'";
1082 my $digester = eval "$module"."->$method;" or die $@;
1087 Digester => $digester,
1092 fail "missing any supported Checksums-* or Files field in ".
1093 $dsc->get_option('name');
1097 map { $_->{Filename} } dsc_files_info();
1100 sub is_orig_file ($;$) {
1103 m/\.orig(?:-\w+)?\.tar\.\w+$/ or return 0;
1104 defined $base or return 1;
1108 sub make_commit ($) {
1110 return cmdoutput @git, qw(hash-object -w -t commit), $file;
1113 sub clogp_authline ($) {
1115 my $author = getfield $clogp, 'Maintainer';
1116 $author =~ s#,.*##ms;
1117 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
1118 my $authline = "$author $date";
1119 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
1120 fail "unexpected commit author line format \`$authline'".
1121 " (was generated from changelog Maintainer field)";
1125 sub generate_commit_from_dsc () {
1129 foreach my $fi (dsc_files_info()) {
1130 my $f = $fi->{Filename};
1131 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
1133 link "../../../$f", $f
1137 complete_file_from_dsc('.', $fi);
1139 if (is_orig_file($f)) {
1140 link $f, "../../../../$f"
1146 my $dscfn = "$package.dsc";
1148 open D, ">", $dscfn or die "$dscfn: $!";
1149 print D $dscdata or die "$dscfn: $!";
1150 close D or die "$dscfn: $!";
1151 my @cmd = qw(dpkg-source);
1152 push @cmd, '--no-check' if $dsc_checked;
1153 push @cmd, qw(-x --), $dscfn;
1156 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1157 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
1158 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
1159 my $authline = clogp_authline $clogp;
1160 my $changes = getfield $clogp, 'Changes';
1161 open C, ">../commit.tmp" or die $!;
1162 print C <<END or die $!;
1169 # imported from the archive
1172 my $outputhash = make_commit qw(../commit.tmp);
1173 my $cversion = getfield $clogp, 'Version';
1174 progress "synthesised git commit from .dsc $cversion";
1175 if ($lastpush_hash) {
1176 runcmd @git, qw(reset --hard), $lastpush_hash;
1177 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
1178 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
1179 my $oversion = getfield $oldclogp, 'Version';
1181 version_compare($oversion, $cversion);
1183 # git upload/ is earlier vsn than archive, use archive
1184 open C, ">../commit2.tmp" or die $!;
1185 print C <<END or die $!;
1187 parent $lastpush_hash
1192 Record $package ($cversion) in archive suite $csuite
1194 $outputhash = make_commit qw(../commit2.tmp);
1195 } elsif ($vcmp > 0) {
1196 print STDERR <<END or die $!;
1198 Version actually in archive: $cversion (older)
1199 Last allegedly pushed/uploaded: $oversion (newer or same)
1202 $outputhash = $lastpush_hash;
1204 $outputhash = $lastpush_hash;
1207 changedir '../../../..';
1208 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
1209 'DGIT_ARCHIVE', $outputhash;
1210 cmdoutput @git, qw(log -n2), $outputhash;
1211 # ... gives git a chance to complain if our commit is malformed
1216 sub complete_file_from_dsc ($$) {
1217 our ($dstdir, $fi) = @_;
1218 # Ensures that we have, in $dir, the file $fi, with the correct
1219 # contents. (Downloading it from alongside $dscurl if necessary.)
1221 my $f = $fi->{Filename};
1222 my $tf = "$dstdir/$f";
1225 if (stat_exists $tf) {
1226 progress "using existing $f";
1229 $furl =~ s{/[^/]+$}{};
1231 die "$f ?" unless $f =~ m/^${package}_/;
1232 die "$f ?" if $f =~ m#/#;
1233 runcmd_ordryrun_local @curl,qw(-o),$tf,'--',"$furl";
1234 next if !act_local();
1238 open F, "<", "$tf" or die "$tf: $!";
1239 $fi->{Digester}->reset();
1240 $fi->{Digester}->addfile(*F);
1241 F->error and die $!;
1242 my $got = $fi->{Digester}->hexdigest();
1243 $got eq $fi->{Hash} or
1244 fail "file $f has hash $got but .dsc".
1245 " demands hash $fi->{Hash} ".
1246 ($downloaded ? "(got wrong file from archive!)"
1247 : "(perhaps you should delete this file?)");
1250 sub ensure_we_have_orig () {
1251 foreach my $fi (dsc_files_info()) {
1252 my $f = $fi->{Filename};
1253 next unless is_orig_file($f);
1254 complete_file_from_dsc('..', $fi);
1259 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
1262 sub is_fast_fwd ($$) {
1263 my ($ancestor,$child) = @_;
1264 my @cmd = (@git, qw(merge-base), $ancestor, $child);
1265 my $mb = cmdoutput_errok @cmd;
1267 return rev_parse($mb) eq rev_parse($ancestor);
1269 $?==256 or failedcmd @cmd;
1274 sub git_fetch_us () {
1275 runcmd_ordryrun_local @git, qw(fetch),access_giturl(),fetchspec();
1278 sub fetch_from_archive () {
1279 # ensures that lrref() is what is actually in the archive,
1280 # one way or another
1284 foreach my $field (@ourdscfield) {
1285 $dsc_hash = $dsc->{$field};
1286 last if defined $dsc_hash;
1288 if (defined $dsc_hash) {
1289 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
1291 progress "last upload to archive specified git hash";
1293 progress "last upload to archive has NO git hash";
1296 progress "no version available from the archive";
1299 $lastpush_hash = git_get_ref(lrref());
1300 printdebug "previous reference hash=$lastpush_hash\n";
1302 if (defined $dsc_hash) {
1303 fail "missing remote git history even though dsc has hash -".
1304 " could not find ref ".lrref().
1305 " (should have been fetched from ".access_giturl()."#".rrref().")"
1306 unless $lastpush_hash;
1308 ensure_we_have_orig();
1309 if ($dsc_hash eq $lastpush_hash) {
1310 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
1311 print STDERR <<END or die $!;
1313 Git commit in archive is behind the last version allegedly pushed/uploaded.
1314 Commit referred to by archive: $dsc_hash
1315 Last allegedly pushed/uploaded: $lastpush_hash
1318 $hash = $lastpush_hash;
1320 fail "archive's .dsc refers to ".$dsc_hash.
1321 " but this is an ancestor of ".$lastpush_hash;
1324 $hash = generate_commit_from_dsc();
1325 } elsif ($lastpush_hash) {
1326 # only in git, not in the archive yet
1327 $hash = $lastpush_hash;
1328 print STDERR <<END or die $!;
1330 Package not found in the archive, but has allegedly been pushed using dgit.
1334 printdebug "nothing found!\n";
1335 if (defined $skew_warning_vsn) {
1336 print STDERR <<END or die $!;
1338 Warning: relevant archive skew detected.
1339 Archive allegedly contains $skew_warning_vsn
1340 But we were not able to obtain any version from the archive or git.
1346 printdebug "current hash=$hash\n";
1347 if ($lastpush_hash) {
1348 fail "not fast forward on last upload branch!".
1349 " (archive's version left in DGIT_ARCHIVE)"
1350 unless is_fast_fwd($lastpush_hash, $hash);
1352 if (defined $skew_warning_vsn) {
1354 printdebug "SKEW CHECK WANT $skew_warning_vsn\n";
1355 my $clogf = ".git/dgit/changelog.tmp";
1356 runcmd shell_cmd "exec >$clogf",
1357 @git, qw(cat-file blob), "$hash:debian/changelog";
1358 my $gotclogp = parsechangelog("-l$clogf");
1359 my $got_vsn = getfield $gotclogp, 'Version';
1360 printdebug "SKEW CHECK GOT $got_vsn\n";
1361 if (version_compare($got_vsn, $skew_warning_vsn) < 0) {
1362 print STDERR <<END or die $!;
1364 Warning: archive skew detected. Using the available version:
1365 Archive allegedly contains $skew_warning_vsn
1366 We were able to obtain only $got_vsn
1371 if ($lastpush_hash ne $hash) {
1372 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
1376 dryrun_report @upd_cmd;
1384 canonicalise_suite();
1385 badusage "dry run makes no sense with clone" unless act_local();
1386 my $hasgit = check_for_git();
1387 mkdir $dstdir or die "$dstdir $!";
1389 runcmd @git, qw(init -q);
1390 my $giturl = access_giturl(1);
1391 if (defined $giturl) {
1392 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
1393 open H, "> .git/HEAD" or die $!;
1394 print H "ref: ".lref()."\n" or die $!;
1396 runcmd @git, qw(remote add), 'origin', $giturl;
1399 progress "fetching existing git history";
1401 runcmd_ordryrun_local @git, qw(fetch origin);
1403 progress "starting new git history";
1405 fetch_from_archive() or no_such_package;
1406 my $vcsgiturl = $dsc->{'Vcs-Git'};
1407 if (length $vcsgiturl) {
1408 runcmd @git, qw(remote add vcs-git), $vcsgiturl;
1410 runcmd @git, qw(reset --hard), lrref();
1411 printdone "ready for work in $dstdir";
1415 if (check_for_git()) {
1418 fetch_from_archive() or no_such_package();
1419 printdone "fetched into ".lrref();
1424 runcmd_ordryrun_local @git, qw(merge -m),"Merge from $csuite [dgit]",
1426 printdone "fetched to ".lrref()." and merged into HEAD";
1429 sub check_not_dirty () {
1430 return if $ignoredirty;
1431 my @cmd = (@git, qw(diff --quiet HEAD));
1432 printcmd(\*DEBUG,$debugprefix."+",@cmd) if $debug>0;
1433 $!=0; $?=0; system @cmd;
1434 return if !$! && !$?;
1435 if (!$! && $?==256) {
1436 fail "working tree is dirty (does not match HEAD)";
1442 sub commit_admin ($) {
1445 runcmd_ordryrun_local @git, qw(commit -m), $m;
1448 sub commit_quilty_patch () {
1449 my $output = cmdoutput @git, qw(status --porcelain);
1451 foreach my $l (split /\n/, $output) {
1452 next unless $l =~ m/\S/;
1453 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1457 delete $adds{'.pc'}; # if there wasn't one before, don't add it
1459 progress "nothing quilty to commit, ok.";
1462 runcmd_ordryrun_local @git, qw(add), sort keys %adds;
1463 commit_admin "Commit Debian 3.0 (quilt) metadata";
1466 sub get_source_format () {
1467 if (!open F, "debian/source/format") {
1468 die $! unless $!==&ENOENT;
1472 F->error and die $!;
1479 return 0 unless $format eq '3.0 (quilt)';
1481 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1484 progress "Format \`$format', checking/updating patch stack";
1488 sub push_parse_changelog ($) {
1491 my $clogp = Dpkg::Control::Hash->new();
1492 $clogp->load($clogpfn) or die;
1494 $package = getfield $clogp, 'Source';
1495 my $cversion = getfield $clogp, 'Version';
1496 my $tag = debiantag($cversion);
1497 runcmd @git, qw(check-ref-format), $tag;
1499 my $dscfn = dscfn($cversion);
1501 return ($clogp, $cversion, $tag, $dscfn);
1504 sub push_parse_dsc ($$$) {
1505 my ($dscfn,$dscfnwhat, $cversion) = @_;
1506 $dsc = parsecontrol($dscfn,$dscfnwhat);
1507 my $dversion = getfield $dsc, 'Version';
1508 my $dscpackage = getfield $dsc, 'Source';
1509 ($dscpackage eq $package && $dversion eq $cversion) or
1510 fail "$dscfn is for $dscpackage $dversion".
1511 " but debian/changelog is for $package $cversion";
1514 sub push_mktag ($$$$$$$) {
1515 my ($head,$clogp,$tag,
1517 $changesfile,$changesfilewhat,
1520 $dsc->{$ourdscfield[0]} = $head;
1521 $dsc->save("$dscfn.tmp") or die $!;
1523 my $changes = parsecontrol($changesfile,$changesfilewhat);
1524 foreach my $field (qw(Source Distribution Version)) {
1525 $changes->{$field} eq $clogp->{$field} or
1526 fail "changes field $field \`$changes->{$field}'".
1527 " does not match changelog \`$clogp->{$field}'";
1530 my $cversion = getfield $clogp, 'Version';
1531 my $clogsuite = getfield $clogp, 'Distribution';
1533 # We make the git tag by hand because (a) that makes it easier
1534 # to control the "tagger" (b) we can do remote signing
1535 my $authline = clogp_authline $clogp;
1536 open TO, '>', $tfn->('.tmp') or die $!;
1537 print TO <<END or die $!;
1543 $package release $cversion for $clogsuite ($csuite) [dgit]
1547 my $tagobjfn = $tfn->('.tmp');
1549 if (!defined $keyid) {
1550 $keyid = access_cfg('keyid','RETURN-UNDEF');
1552 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1553 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1554 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1555 push @sign_cmd, $tfn->('.tmp');
1556 runcmd_ordryrun @sign_cmd;
1558 $tagobjfn = $tfn->('.signed.tmp');
1559 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1560 $tfn->('.tmp'), $tfn->('.tmp.asc');
1567 sub sign_changes ($) {
1568 my ($changesfile) = @_;
1570 my @debsign_cmd = @debsign;
1571 push @debsign_cmd, "-k$keyid" if defined $keyid;
1572 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1573 push @debsign_cmd, $changesfile;
1574 runcmd_ordryrun @debsign_cmd;
1579 printdebug "actually entering push\n";
1582 access_giturl(); # check that success is vaguely likely
1584 my $clogpfn = ".git/dgit/changelog.822.tmp";
1585 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1587 responder_send_file('parsed-changelog', $clogpfn);
1589 my ($clogp, $cversion, $tag, $dscfn) =
1590 push_parse_changelog("$clogpfn");
1592 my $dscpath = "$buildproductsdir/$dscfn";
1593 stat_exists $dscpath or
1594 fail "looked for .dsc $dscfn, but $!;".
1595 " maybe you forgot to build";
1597 responder_send_file('dsc', $dscpath);
1599 push_parse_dsc($dscpath, $dscfn, $cversion);
1601 my $format = getfield $dsc, 'Format';
1602 printdebug "format $format\n";
1603 if (madformat($format)) {
1604 commit_quilty_patch();
1608 progress "checking that $dscfn corresponds to HEAD";
1609 runcmd qw(dpkg-source -x --),
1610 $dscpath =~ m#^/# ? $dscpath : "../../../$dscpath";
1611 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1612 changedir '../../../..';
1613 my $diffopt = $debug>0 ? '--exit-code' : '--quiet';
1614 my @diffcmd = (@git, qw(diff), $diffopt, $tree);
1615 printcmd \*DEBUG,$debugprefix."+",@diffcmd;
1617 my $r = system @diffcmd;
1620 fail "$dscfn specifies a different tree to your HEAD commit;".
1621 " perhaps you forgot to build".
1622 ($diffopt eq '--exit-code' ? "" :
1623 " (run with -D to see full diff output)");
1629 #do fast forward check and maybe fake merge
1630 # if (!is_fast_fwd(mainbranch
1631 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1632 # map { lref($_).":".rref($_) }
1634 my $head = rev_parse('HEAD');
1635 if (!$changesfile) {
1636 my $multi = "$buildproductsdir/".
1637 "${package}_".(stripepoch $cversion)."_multi.changes";
1638 if (stat_exists "$multi") {
1639 $changesfile = $multi;
1641 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1642 my @cs = glob "$buildproductsdir/$pat";
1643 fail "failed to find unique changes file".
1644 " (looked for $pat in $buildproductsdir, or $multi);".
1645 " perhaps you need to use dgit -C"
1647 ($changesfile) = @cs;
1650 $changesfile = "$buildproductsdir/$changesfile";
1653 responder_send_file('changes',$changesfile);
1654 responder_send_command("param head $head");
1655 responder_send_command("param csuite $csuite");
1657 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1660 if ($we_are_responder) {
1661 $tagobjfn = $tfn->('.signed.tmp');
1662 responder_receive_files('signed-tag', $tagobjfn);
1665 push_mktag($head,$clogp,$tag,
1667 $changesfile,$changesfile,
1671 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1672 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1673 runcmd_ordryrun_local @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1674 runcmd_ordryrun @git, qw(tag -v --), $tag;
1676 if (!check_for_git()) {
1677 create_remote_git_repo();
1679 runcmd_ordryrun @git, qw(push),access_giturl(),
1680 "HEAD:".rrref(), "refs/tags/$tag";
1681 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1683 if ($we_are_responder) {
1684 my $dryrunsuffix = act_local() ? "" : ".tmp";
1685 responder_receive_files('signed-dsc-changes',
1686 "$dscpath$dryrunsuffix",
1687 "$changesfile$dryrunsuffix");
1690 rename "$dscpath.tmp",$dscpath or die "$dscfn $!";
1692 progress "[new .dsc left in $dscpath.tmp]";
1694 sign_changes $changesfile;
1697 my $host = access_cfg('upload-host','RETURN-UNDEF');
1698 my @hostarg = defined($host) ? ($host,) : ();
1699 runcmd_ordryrun @dput, @hostarg, $changesfile;
1700 printdone "pushed and uploaded $cversion";
1702 responder_send_command("complete");
1708 badusage "-p is not allowed with clone; specify as argument instead"
1709 if defined $package;
1712 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1713 ($package,$isuite) = @ARGV;
1714 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1715 ($package,$dstdir) = @ARGV;
1716 } elsif (@ARGV==3) {
1717 ($package,$isuite,$dstdir) = @ARGV;
1719 badusage "incorrect arguments to dgit clone";
1721 $dstdir ||= "$package";
1723 if (stat_exists $dstdir) {
1724 fail "$dstdir already exists";
1728 if ($rmonerror && !$dryrun_level) {
1729 $cwd_remove= getcwd();
1731 return unless defined $cwd_remove;
1732 if (!chdir "$cwd_remove") {
1733 return if $!==&ENOENT;
1734 die "chdir $cwd_remove: $!";
1736 rmtree($dstdir) or die "remove $dstdir: $!\n";
1741 $cwd_remove = undef;
1744 sub branchsuite () {
1745 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1746 if ($branch =~ m#$lbranch_re#o) {
1753 sub fetchpullargs () {
1754 if (!defined $package) {
1755 my $sourcep = parsecontrol('debian/control','debian/control');
1756 $package = getfield $sourcep, 'Source';
1759 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1761 my $clogp = parsechangelog();
1762 $isuite = getfield $clogp, 'Distribution';
1764 canonicalise_suite();
1765 progress "fetching from suite $csuite";
1766 } elsif (@ARGV==1) {
1768 canonicalise_suite();
1770 badusage "incorrect arguments to dgit fetch or dgit pull";
1788 badusage "-p is not allowed with dgit push" if defined $package;
1790 my $clogp = parsechangelog();
1791 $package = getfield $clogp, 'Source';
1794 } elsif (@ARGV==1) {
1795 ($specsuite) = (@ARGV);
1797 badusage "incorrect arguments to dgit push";
1799 $isuite = getfield $clogp, 'Distribution';
1801 local ($package) = $existing_package; # this is a hack
1802 canonicalise_suite();
1804 if (defined $specsuite && $specsuite ne $isuite) {
1805 canonicalise_suite();
1806 $csuite eq $specsuite or
1807 fail "dgit push: changelog specifies $isuite ($csuite)".
1808 " but command line specifies $specsuite";
1810 if (check_for_git()) {
1813 if (fetch_from_archive()) {
1814 is_fast_fwd(lrref(), 'HEAD') or
1815 fail "dgit push: HEAD is not a descendant".
1816 " of the archive's version.\n".
1817 "$us: To overwrite it, use git merge -s ours ".lrref().".";
1820 fail "package appears to be new in this suite;".
1821 " if this is intentional, use --new";
1826 #---------- remote commands' implementation ----------
1828 sub cmd_remote_push_build_host {
1829 my ($nrargs) = shift @ARGV;
1830 my (@rargs) = @ARGV[0..$nrargs-1];
1831 @ARGV = @ARGV[$nrargs..$#ARGV];
1833 my ($dir,$vsnwant) = @rargs;
1834 # vsnwant is a comma-separated list; we report which we have
1835 # chosen in our ready response (so other end can tell if they
1838 $we_are_responder = 1;
1840 open PI, "<&STDIN" or die $!;
1841 open STDIN, "/dev/null" or die $!;
1842 open PO, ">&STDOUT" or die $!;
1844 open STDOUT, ">&STDERR" or die $!;
1848 fail "build host has dgit rpush protocol version".
1849 " $rpushprotovsn but invocation host has $vsnwant"
1850 unless grep { $rpushprotovsn eq $_ } split /,/, $vsnwant;
1852 responder_send_command("dgit-remote-push-ready $rpushprotovsn");
1858 sub cmd_remote_push_responder { cmd_remote_push_build_host(); }
1859 # ... for compatibility with proto vsn.1 dgit (just so that user gets
1860 # a good error message)
1866 my $report = i_child_report();
1867 if (defined $report) {
1868 printdebug "($report)\n";
1869 } elsif ($i_child_pid) {
1870 printdebug "(killing build host child $i_child_pid)\n";
1871 kill 15, $i_child_pid;
1873 if (defined $i_tmp && !defined $initiator_tempdir) {
1875 eval { rmtree $i_tmp; };
1879 END { i_cleanup(); }
1882 my ($base,$selector,@args) = @_;
1883 $selector =~ s/\-/_/g;
1884 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1890 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1897 my @rargs = ($dir,$rpushprotovsn);
1900 push @rdgit, @ropts;
1901 push @rdgit, qw(remote-push-build-host), (scalar @rargs), @rargs;
1903 my @cmd = (@ssh, $host, shellquote @rdgit);
1904 printcmd \*DEBUG,$debugprefix."+",@cmd;
1906 if (defined $initiator_tempdir) {
1907 rmtree $initiator_tempdir;
1908 mkdir $initiator_tempdir, 0700 or die "$initiator_tempdir: $!";
1909 $i_tmp = $initiator_tempdir;
1913 $i_child_pid = open2(\*RO, \*RI, @cmd);
1915 initiator_expect { m/^dgit-remote-push-ready/ };
1917 my ($icmd,$iargs) = initiator_expect {
1918 m/^(\S+)(?: (.*))?$/;
1921 i_method "i_resp", $icmd, $iargs;
1925 sub i_resp_progress ($) {
1927 my $msg = protocol_read_bytes \*RO, $rhs;
1931 sub i_resp_complete {
1932 my $pid = $i_child_pid;
1933 $i_child_pid = undef; # prevents killing some other process with same pid
1934 printdebug "waiting for build host child $pid...\n";
1935 my $got = waitpid $pid, 0;
1936 die $! unless $got == $pid;
1937 die "build host child failed $?" if $?;
1940 printdebug "all done\n";
1944 sub i_resp_file ($) {
1946 my $localname = i_method "i_localname", $keyword;
1947 my $localpath = "$i_tmp/$localname";
1948 stat_exists $localpath and
1949 badproto \*RO, "file $keyword ($localpath) twice";
1950 protocol_receive_file \*RO, $localpath;
1951 i_method "i_file", $keyword;
1956 sub i_resp_param ($) {
1957 $_[0] =~ m/^(\S+) (.*)$/ or badproto \*RO, "bad param spec";
1963 sub i_resp_want ($) {
1965 die "$keyword ?" if $i_wanted{$keyword}++;
1966 my @localpaths = i_method "i_want", $keyword;
1967 printdebug "[[ $keyword @localpaths\n";
1968 foreach my $localpath (@localpaths) {
1969 protocol_send_file \*RI, $localpath;
1971 print RI "files-end\n" or die $!;
1974 our ($i_clogp, $i_version, $i_tag, $i_dscfn, $i_changesfn);
1976 sub i_localname_parsed_changelog {
1977 return "remote-changelog.822";
1979 sub i_file_parsed_changelog {
1980 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1981 push_parse_changelog "$i_tmp/remote-changelog.822";
1982 die if $i_dscfn =~ m#/|^\W#;
1985 sub i_localname_dsc {
1986 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1991 sub i_localname_changes {
1992 defined $i_dscfn or badproto \*RO, "dsc (before parsed-changelog)";
1993 $i_changesfn = $i_dscfn;
1994 $i_changesfn =~ s/\.dsc$/_dgit.changes/ or die;
1995 return $i_changesfn;
1997 sub i_file_changes { }
1999 sub i_want_signed_tag {
2000 printdebug Dumper(\%i_param, $i_dscfn);
2001 defined $i_param{'head'} && defined $i_dscfn && defined $i_clogp
2002 && defined $i_param{'csuite'}
2003 or badproto \*RO, "premature desire for signed-tag";
2004 my $head = $i_param{'head'};
2005 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
2007 die unless $i_param{'csuite'} =~ m/^$suite_re$/;
2009 push_parse_dsc $i_dscfn, 'remote dsc', $i_version;
2012 push_mktag $head, $i_clogp, $i_tag,
2014 $i_changesfn, 'remote changes',
2015 sub { "tag$_[0]"; };
2020 sub i_want_signed_dsc_changes {
2021 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
2022 sign_changes $i_changesfn;
2023 return ($i_dscfn, $i_changesfn);
2026 #---------- building etc. ----------
2032 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
2034 sub build_maybe_quilt_fixup () {
2035 my $format=get_source_format;
2036 return unless madformat $format;
2040 # - honour any existing .pc in case it has any strangeness
2041 # - determine the git commit corresponding to the tip of
2042 # the patch stack (if there is one)
2043 # - if there is such a git commit, convert each subsequent
2044 # git commit into a quilt patch with dpkg-source --commit
2045 # - otherwise convert all the differences in the tree into
2046 # a single git commit
2050 # Our git tree doesn't necessarily contain .pc. (Some versions of
2051 # dgit would include the .pc in the git tree.) If there isn't
2052 # one, we need to generate one by unpacking the patches that we
2055 # We first look for a .pc in the git tree. If there is one, we
2056 # will use it. (This is not the normal case.)
2058 # Otherwise need to regenerate .pc so that dpkg-source --commit
2059 # can work. We do this as follows:
2060 # 1. Collect all relevant .orig from parent directory
2061 # 2. Generate a debian.tar.gz out of
2062 # debian/{patches,rules,source/format}
2063 # 3. Generate a fake .dsc containing just these fields:
2064 # Format Source Version Files
2065 # 4. Extract the fake .dsc
2066 # Now the fake .dsc has a .pc directory.
2067 # (In fact we do this in every case, because in future we will
2068 # want to search for a good base commit for generating patches.)
2070 # Then we can actually do the dpkg-source --commit
2071 # 1. Make a new working tree with the same object
2072 # store as our main tree and check out the main
2074 # 2. Copy .pc from the fake's extraction, if necessary
2075 # 3. Run dpkg-source --commit
2076 # 4. If the result has changes to debian/, then
2077 # - git-add them them
2078 # - git-add .pc if we had a .pc in-tree
2080 # 5. If we had a .pc in-tree, delete it, and git-commit
2081 # 6. Back in the main tree, fast forward to the new HEAD
2083 my $clogp = parsechangelog();
2084 my $headref = rev_parse('HEAD');
2089 my $upstreamversion=$version;
2090 $upstreamversion =~ s/-[^-]*$//;
2092 my $fakeversion="$upstreamversion-~~DGITFAKE";
2094 my $fakedsc=new IO::File 'fake.dsc', '>' or die $!;
2095 print $fakedsc <<END or die $!;
2098 Version: $fakeversion
2102 my $dscaddfile=sub {
2105 my $md = new Digest::MD5;
2107 my $fh = new IO::File $b, '<' or die "$b $!";
2112 print $fakedsc " ".$md->hexdigest." $size $b\n" or die $!;
2115 foreach my $f (<../../../../*>) { #/){
2116 my $b=$f; $b =~ s{.*/}{};
2117 next unless is_orig_file $b, srcfn $upstreamversion,'';
2118 link $f, $b or die "$b $!";
2122 my @files=qw(debian/source/format debian/rules);
2123 if (stat_exists '../../../debian/patches') {
2124 push @files, 'debian/patches';
2127 my $debtar= srcfn $fakeversion,'.debian.tar.gz';
2128 runcmd qw(env GZIP=-1 tar -zcf), "./$debtar", qw(-C ../../..), @files;
2130 $dscaddfile->($debtar);
2131 close $fakedsc or die $!;
2133 runcmd qw(sh -ec), 'exec dpkg-source --no-check -x fake.dsc >/dev/null';
2135 my $fakexdir= $package.'-'.(stripepoch $upstreamversion);
2136 rename $fakexdir, "fake" or die "$fakexdir $!";
2138 mkdir "work" or die $!;
2140 mktree_in_ud_here();
2141 runcmd @git, qw(reset --hard), $headref;
2144 if (stat_exists ".pc") {
2146 progress "Tree already contains .pc - will use it then delete it.";
2149 rename '../fake/.pc','.pc' or die $!;
2152 my $author = getfield $clogp, 'Maintainer';
2155 my $patchname = "auto-$version-$headref-$time";
2156 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
2158 my $descfn = ".git/dgit/quilt-description.tmp";
2159 open O, '>', $descfn or die "$descfn: $!";
2161 $msg =~ s/^\s+$/ ./mg;
2162 print O <<END or die $!;
2163 Description: Automatically generated patch ($clogp->{Version})
2164 Last (up to) $ncommits git changes, FYI:
2174 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
2175 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
2176 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
2177 runcmd_ordryrun_local @dpkgsource, qw(--commit .), $patchname;
2180 if (!open P, '>>', ".pc/applied-patches") {
2181 $!==&ENOENT or die $!;
2186 commit_quilty_patch();
2188 if ($mustdeletepc) {
2189 runcmd @git, qw(rm -rq .pc);
2190 commit_admin "Commit removal of .pc (quilt series tracking data)";
2193 changedir '../../../..';
2194 runcmd @git, qw(pull --ff-only -q .git/dgit/unpack/work master);
2197 sub quilt_fixup_editor () {
2198 my $descfn = $ENV{$fakeeditorenv};
2199 my $editing = $ARGV[$#ARGV];
2200 open I1, '<', $descfn or die "$descfn: $!";
2201 open I2, '<', $editing or die "$editing: $!";
2202 unlink $editing or die "$editing: $!";
2203 open O, '>', $editing or die "$editing: $!";
2204 while (<I1>) { print O or die $!; } I1->error and die $!;
2207 $copying ||= m/^\-\-\- /;
2208 next unless $copying;
2211 I2->error and die $!;
2217 if ($cleanmode eq 'dpkg-source') {
2218 runcmd_ordryrun_local @dpkgbuildpackage, qw(-T clean);
2219 } elsif ($cleanmode eq 'git') {
2220 runcmd_ordryrun_local @git, qw(clean -xdf);
2221 } elsif ($cleanmode eq 'none') {
2228 badusage "clean takes no additional arguments" if @ARGV;
2233 badusage "-p is not allowed when building" if defined $package;
2236 my $clogp = parsechangelog();
2237 $isuite = getfield $clogp, 'Distribution';
2238 $package = getfield $clogp, 'Source';
2239 $version = getfield $clogp, 'Version';
2240 build_maybe_quilt_fixup();
2243 sub changesopts () {
2244 my @opts =@changesopts[1..$#changesopts];
2245 if (!defined $changes_since_version) {
2246 my @vsns = archive_query('archive_query');
2247 my @quirk = access_quirk();
2248 if ($quirk[0] eq 'backports') {
2249 local $isuite = $quirk[2];
2251 canonicalise_suite();
2252 push @vsns, archive_query('archive_query');
2255 @vsns = map { $_->[0] } @vsns;
2256 @vsns = sort { -version_compare($a, $b) } @vsns;
2257 $changes_since_version = $vsns[0];
2258 progress "changelog will contain changes since $vsns[0]";
2260 $changes_since_version = '_';
2261 progress "package seems new, not specifying -v<version>";
2264 if ($changes_since_version ne '_') {
2265 unshift @opts, "-v$changes_since_version";
2272 runcmd_ordryrun_local @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
2273 printdone "build successful\n";
2279 (qw(git-buildpackage -us -uc --git-no-sign-tags),
2280 "--git-builder=@dpkgbuildpackage");
2281 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
2282 canonicalise_suite();
2283 push @cmd, "--git-debian-branch=".lbranch();
2285 push @cmd, changesopts();
2286 runcmd_ordryrun_local @cmd, @ARGV;
2287 printdone "build successful\n";
2292 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
2293 $dscfn = dscfn($version);
2294 if ($cleanmode eq 'dpkg-source') {
2295 runcmd_ordryrun_local (@dpkgbuildpackage, qw(-us -uc -S)),
2298 my $pwd = must_getcwd();
2299 my $leafdir = basename $pwd;
2301 runcmd_ordryrun_local @dpkgsource, qw(-b --), $leafdir;
2303 runcmd_ordryrun_local qw(sh -ec),
2304 'exec >$1; shift; exec "$@"','x',
2305 "../$sourcechanges",
2306 @dpkggenchanges, qw(-S), changesopts();
2310 sub cmd_build_source {
2311 badusage "build-source takes no additional arguments" if @ARGV;
2313 printdone "source built, results in $dscfn and $sourcechanges";
2319 my $pat = "${package}_".(stripepoch $version)."_*.changes";
2321 stat_exist $dscfn or fail "$dscfn (in parent directory): $!";
2322 stat_exists $sourcechanges
2323 or fail "$sourcechanges (in parent directory): $!";
2324 foreach my $cf (glob $pat) {
2325 next if $cf eq $sourcechanges;
2326 unlink $cf or fail "remove $cf: $!";
2329 runcmd_ordryrun_local @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
2330 my @changesfiles = glob $pat;
2331 @changesfiles = sort {
2332 ($b =~ m/_source\.changes$/ <=> $a =~ m/_source\.changes$/)
2335 fail "wrong number of different changes files (@changesfiles)"
2336 unless @changesfiles;
2337 runcmd_ordryrun_local @mergechanges, @changesfiles;
2338 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
2340 stat_exists $multichanges or fail "$multichanges: $!";
2342 printdone "build successful, results in $multichanges\n" or die $!;
2345 sub cmd_quilt_fixup {
2346 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
2347 my $clogp = parsechangelog();
2348 $version = getfield $clogp, 'Version';
2349 $package = getfield $clogp, 'Source';
2350 build_maybe_quilt_fixup();
2353 #---------- argument parsing and main program ----------
2356 print "dgit version $our_version\n" or die $!;
2363 if (defined $ENV{'DGIT_SSH'}) {
2364 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
2365 } elsif (defined $ENV{'GIT_SSH'}) {
2366 @ssh = ($ENV{'GIT_SSH'});
2370 last unless $ARGV[0] =~ m/^-/;
2374 if (m/^--dry-run$/) {
2377 } elsif (m/^--damp-run$/) {
2380 } elsif (m/^--no-sign$/) {
2383 } elsif (m/^--help$/) {
2385 } elsif (m/^--version$/) {
2387 } elsif (m/^--new$/) {
2390 } elsif (m/^--since-version=([^_]+|_)$/) {
2392 $changes_since_version = $1;
2393 } elsif (m/^--([-0-9a-z]+)=(.*)/s &&
2394 ($om = $opts_opt_map{$1}) &&
2398 } elsif (m/^--([-0-9a-z]+):(.*)/s &&
2399 !$opts_opt_cmdonly{$1} &&
2400 ($om = $opts_opt_map{$1})) {
2403 } elsif (m/^--existing-package=(.*)/s) {
2405 $existing_package = $1;
2406 } elsif (m/^--initiator-tempdir=(.*)/s) {
2407 $initiator_tempdir = $1;
2408 $initiator_tempdir =~ m#^/# or
2409 badusage "--initiator-tempdir must be used specify an".
2410 " absolute, not relative, directory."
2411 } elsif (m/^--distro=(.*)/s) {
2414 } elsif (m/^--build-products-dir=(.*)/s) {
2416 $buildproductsdir = $1;
2417 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
2420 } elsif (m/^--clean=(.*)$/s) {
2421 badusage "unknown cleaning mode \`$1'";
2422 } elsif (m/^--ignore-dirty$/s) {
2425 } elsif (m/^--no-quilt-fixup$/s) {
2428 } elsif (m/^--no-rm-on-error$/s) {
2432 badusage "unknown long option \`$_'";
2439 } elsif (s/^-L/-/) {
2442 } elsif (s/^-h/-/) {
2444 } elsif (s/^-D/-/) {
2446 open DEBUG, ">&STDERR" or die $!;
2449 } elsif (s/^-N/-/) {
2452 } elsif (s/^-v([^_]+|_)$//s) {
2454 $changes_since_version = $1;
2457 push @changesopts, $_;
2459 } elsif (s/^-c(.*=.*)//s) {
2461 push @git, '-c', $1;
2462 } elsif (s/^-d(.*)//s) {
2465 } elsif (s/^-C(.*)//s) {
2468 if ($changesfile =~ s#^(.*)/##) {
2469 $buildproductsdir = $1;
2471 } elsif (s/^-k(.*)//s) {
2473 } elsif (s/^-wn//s) {
2475 $cleanmode = 'none';
2476 } elsif (s/^-wg//s) {
2479 } elsif (s/^-wd//s) {
2481 $cleanmode = 'dpkg-source';
2483 badusage "unknown short option \`$_'";
2490 if ($ENV{$fakeeditorenv}) {
2491 quilt_fixup_editor();
2495 print STDERR "DRY RUN ONLY\n" if $dryrun_level > 1;
2496 print STDERR "DAMP RUN - WILL MAKE LOCAL (UNSIGNED) CHANGES\n"
2497 if $dryrun_level == 1;
2499 print STDERR $helpmsg or die $!;
2502 my $cmd = shift @ARGV;
2505 my $fn = ${*::}{"cmd_$cmd"};
2506 $fn or badusage "unknown operation $cmd";