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;
33 our $our_version = 'UNRELEASED'; ###substituted###
35 our $isuite = 'unstable';
46 our $existing_package = 'dpkg';
47 our $cleanmode = 'dpkg-source';
48 our $we_are_responder;
50 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
53 our (@dget) = qw(dget);
54 our (@dput) = qw(dput);
55 our (@debsign) = qw(debsign);
57 our (@sbuild) = qw(sbuild -A);
59 our (@dgit) = qw(dgit);
60 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
61 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
62 our (@dpkggenchanges) = qw(dpkg-genchanges);
63 our (@mergechanges) = qw(mergechanges -f);
64 our (@changesopts) = ('');
66 our %opts_opt_map = ('dget' => \@dget,
68 'debsign' => \@debsign,
73 'dpkg-source' => \@dpkgsource,
74 'dpkg-buildpackage' => \@dpkgbuildpackage,
75 'dpkg-genchanges' => \@dpkggenchanges,
76 'ch' => \@changesopts,
77 'mergechanges' => \@mergechanges);
79 our %opts_opt_cmdonly = ('gpg' => 1);
84 open DEBUG, ">/dev/null" or die $!;
86 our $remotename = 'dgit';
87 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
88 our $branchprefix = 'dgit';
91 sub lbranch () { return "$branchprefix/$csuite"; }
92 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
93 sub lref () { return "refs/heads/".lbranch(); }
94 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
95 sub rrref () { return "refs/$branchprefix/$csuite"; }
110 return "${package}_".(stripepoch $vsn).".dsc";
113 sub changesopts () { return @changesopts[1..$#changesopts]; }
117 sub fail { die "$us: @_\n"; }
119 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
121 sub no_such_package () {
122 print STDERR "$us: package $package does not exist in suite $isuite\n";
128 return "+".rrref().":".lrref();
131 #---------- remote protocol support, common ----------
133 # remote push initiator/responder protocol:
134 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
136 # > file begin parsed-changelog
137 # [indicates that output of dpkg-parsechangelog follows]
138 # > data-block NBYTES
139 # > [NBYTES bytes of data (no newline)]
140 # [maybe some more blocks]
146 # > file begin changes
152 # [indicates that signed tag is wanted]
153 # < data-block NBYTES
154 # < [NBYTES bytes of data (no newline)]
155 # [maybe some more blocks]
159 # > want signed-dsc-changes
160 # < data-block NBYTES [transfer of signed dsc]
162 # < data-block NBYTES [transfer of signed changes]
170 fail "connection lost: $!" if $fh->error;
171 fail "connection terminated" if $fh->eof;
172 fail "protocol violation; $m not expected";
175 sub protocol_expect ($&) {
176 my ($fh, $match) = @_;
179 defined && chomp or badproto $fh, "eof";
181 badproto $fh, "\`$_'";
184 sub protocol_send_file ($$) {
185 my ($fh, $ourfn) = @_;
186 open PF, "<", $ourfn or die "$ourfn: $!";
189 my $got = read PF, $d, 65536;
190 die "$ourfn: $!" unless defined $got;
192 print $fh "data-block ".length($d)."\n" or die $!;
195 print $fh "data-end\n" or die $!;
199 sub protocol_read_bytes ($$) {
200 my ($fh, $nbytes) = @_;
201 $nbytes =~ m/^\d{1,6}$/ or badproto \*RO, "bad byte count";
203 my $got = read $fh, $d, $nbytes;
204 $got==$nbytes or badproto $fh, "eof during data block";
208 sub protocol_receive_file ($$) {
209 my ($fh, $ourfn) = @_;
210 open PF, ">", $ourfn or die "$ourfn: $!";
212 protocol_expect \*STDIN, { m/^data-block (.*})$|data-end$/ };
214 my $d = protocol_read_bytes \*STDIN, $1;
215 print PF $d or die $!;
219 #---------- remote protocol support, responder ----------
221 sub responder_send_command ($) {
223 return unless $we_are_responder;
224 # called even without $we_are_responder
225 print DEBUG "<< $command\n";
226 print $command, "\n" or die $!;
229 sub responder_send_file ($$) {
230 my ($keyword, $ourfn) = @_;
231 return unless $we_are_responder;
232 responder_send_command "file-begin $keyword";
233 protocol_send_file \*STDOUT, $ourfn;
236 sub responder_receive_files ($@) {
237 my ($keyword, @ourfns) = @_;
238 die unless $we_are_responder;
239 responder_send_command "want $keyword";
240 foreach my $fn (@ourfns) {
241 protocol_receive_file \*STDIN, $fn;
243 protocol_expect \*STDIN, { m/^files-end$/ };
246 #---------- remote protocol support, initiator ----------
248 sub initiator_expect (&) {
250 protocol_expect \*RO, &$match;
253 #---------- end remote code ----------
256 if ($we_are_responder) {
258 responder_send_command "progress ".length($m) or die $!;
269 $ua = LWP::UserAgent->new();
273 progress "downloading $what...";
274 my $r = $ua->get(@_) or die $!;
275 return undef if $r->code == 404;
276 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
277 return $r->decoded_content();
280 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
287 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
293 return join '', @out;
298 my $intro = shift @_;
299 print $fh $intro or die $!;
300 print $fh shellquote @_ or die $!;
301 print $fh "\n" or die $!;
305 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
307 fail "failed to fork/exec: $!";
308 } elsif (!($? & 0xff)) {
309 fail "subprocess failed with error exit status ".($?>>8);
311 fail "subprocess crashed (wait status $?)";
313 fail "subprocess produced invalid output";
318 printcmd(\*DEBUG,"+",@_) if $debug>0;
320 failedcmd @_ if system @_;
325 progress "dgit ok: @_";
327 progress "would be ok: @_ (but dry run only)";
331 sub cmdoutput_errok {
332 die Dumper(\@_)." ?" if grep { !defined } @_;
333 printcmd(\*DEBUG,"|",@_) if $debug>0;
334 open P, "-|", @_ or die $!;
337 { local $/ = undef; $d = <P>; }
339 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
342 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
347 my $d = cmdoutput_errok @_;
348 defined $d or failedcmd @_;
353 printcmd(\*STDERR,"#",@_);
356 sub runcmd_ordryrun {
365 my ($first_shell, @cmd) = @_;
366 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
369 our $helpmsg = <<END;
371 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
372 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
373 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
374 dgit [dgit-opts] push [dgit-opts] [suite]
375 important dgit options:
376 -k<keyid> sign tag and package with <keyid> instead of default
377 --dry-run -n do not change anything, but go through the motions
378 --new -N allow introducing a new package
379 --debug -D increase debug level
380 -c<name>=<value> set git config option (used directly by dgit too)
383 our $later_warning_msg = <<END;
384 Perhaps the upload is stuck in incoming. Using the version from git.
388 print STDERR "$us: @_\n", $helpmsg or die $!;
393 @ARGV or badusage "too few arguments";
394 return scalar shift @ARGV;
398 print $helpmsg or die $!;
402 our %defcfg = ('dgit.default.distro' => 'debian',
403 'dgit.default.username' => '',
404 'dgit.default.archive-query-default-component' => 'main',
405 'dgit.default.ssh' => 'ssh',
406 'dgit-distro.debian.git-host' => 'git.debian.org',
407 'dgit-distro.debian.git-proto' => 'git+ssh://',
408 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
409 'dgit-distro.debian.git-check' => 'ssh-cmd',
410 'dgit-distro.debian.git-create' => 'ssh-cmd',
411 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
412 'dgit-distro.debian.sshdakls-dir' =>
413 '/srv/ftp-master.debian.org/ftp/dists',
414 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
415 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
419 return undef if $c =~ /RETURN-UNDEF/;
420 my @cmd = (@git, qw(config --), $c);
423 local ($debug) = $debug-1;
424 $v = cmdoutput_errok @cmd;
431 my $dv = $defcfg{$c};
432 return $dv if defined $dv;
434 badcfg "need value for one of: @_";
437 sub access_distro () {
438 return cfg("dgit-suite.$isuite.distro",
439 "dgit.default.distro");
444 my $distro = $idistro || access_distro();
445 my $value = cfg(map { ("dgit-distro.$distro.$_",
446 "dgit.default.$_") } @keys);
450 sub string_to_ssh ($) {
452 if ($spec =~ m/\s/) {
453 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
459 sub access_cfg_ssh () {
460 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
461 if (!defined $gitssh) {
464 return string_to_ssh $gitssh;
468 sub access_someuserhost ($) {
470 my $user = access_cfg("$some-user",'username');
471 my $host = access_cfg("$some-host");
472 return length($user) ? "$user\@$host" : $host;
475 sub access_gituserhost () {
476 return access_someuserhost('git');
479 sub access_giturl () {
480 my $url = access_cfg('git-url','RETURN-UNDEF');
483 access_cfg('git-proto').
484 access_gituserhost().
485 access_cfg('git-path');
487 return "$url/$package.git";
490 sub parsecontrolfh ($$@) {
491 my ($fh, $desc, @opts) = @_;
492 my %opts = ('name' => $desc, @opts);
493 my $c = Dpkg::Control::Hash->new(%opts);
494 $c->parse($fh) or die "parsing of $desc failed";
499 my ($file, $desc) = @_;
500 my $fh = new IO::Handle;
501 open $fh, '<', $file or die "$file: $!";
502 my $c = parsecontrolfh($fh,$desc);
503 $fh->error and die $!;
509 my ($dctrl,$field) = @_;
510 my $v = $dctrl->{$field};
511 return $v if defined $v;
512 fail "missing field $field in ".$v->get_option('name');
516 my $c = Dpkg::Control::Hash->new();
517 my $p = new IO::Handle;
518 my @cmd = (qw(dpkg-parsechangelog), @_);
519 open $p, '-|', @cmd or die $!;
521 $?=0; $!=0; close $p or failedcmd @cmd;
527 sub archive_query ($) {
529 my $query = access_cfg('archive-query','RETURN-UNDEF');
530 if (!defined $query) {
531 my $distro = access_distro();
532 if ($distro eq 'debian') {
533 $query = "sshdakls:".
534 access_someuserhost('sshdakls').':'.
535 access_cfg('sshdakls-dir');
537 $query = "madison:$distro";
540 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
543 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
546 sub archive_query_madison ($$) {
547 my ($proto,$data) = @_;
548 die unless $proto eq 'madison';
549 $rmad{$package} ||= cmdoutput
550 qw(rmadison -asource),"-s$isuite","-u$data",$package;
551 my $rmad = $rmad{$package};
552 return madison_parse($rmad);
555 sub archive_query_sshdakls ($$) {
556 my ($proto,$data) = @_;
557 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
558 my $dakls = cmdoutput
559 access_cfg_ssh, $data, qw(dak ls -asource),"-s$isuite",$package;
560 return madison_parse($dakls);
563 sub canonicalise_suite_sshdakls ($$) {
564 my ($proto,$data) = @_;
565 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
569 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
570 " if test -d $isuite; then echo $isuite; exit 0; fi;".
572 my $dakls = cmdoutput @cmd;
573 failedcmd @cmd unless $dakls =~ m/^\w/;
577 sub madison_parse ($) {
580 foreach my $l (split /\n/, $rmad) {
581 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
582 \s*( [^ \t|]+ )\s* \|
583 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
584 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
585 $1 eq $package or die "$rmad $package ?";
592 $component = access_cfg('archive-query-default-component');
594 $5 eq 'source' or die "$rmad ?";
595 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
596 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
597 push @out, [$vsn,$subpath,$newsuite];
599 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
602 sub canonicalise_suite_madison ($$) {
603 my @r = archive_query_madison($_[0],$_[1]);
605 "unable to canonicalise suite using package $package".
606 " which does not appear to exist in suite $isuite;".
607 " --existing-package may help";
611 sub canonicalise_suite () {
612 return if defined $csuite;
613 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
614 $csuite = archive_query('canonicalise_suite');
615 if ($isuite ne $csuite) {
616 # madison canonicalises for us
617 progress "canonical suite name for $isuite is $csuite";
621 sub get_archive_dsc () {
622 canonicalise_suite();
623 my @vsns = archive_query('archive_query');
624 foreach my $vinfo (@vsns) {
625 my ($vsn,$subpath) = @$vinfo;
626 $dscurl = access_cfg('mirror').$subpath;
627 $dscdata = url_get($dscurl);
629 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
632 my $dscfh = new IO::File \$dscdata, '<' or die $!;
633 print DEBUG Dumper($dscdata) if $debug>1;
634 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
635 print DEBUG Dumper($dsc) if $debug>1;
636 my $fmt = getfield $dsc, 'Format';
637 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
643 sub check_for_git () {
645 my $how = access_cfg('git-check');
646 if ($how eq 'ssh-cmd') {
648 (access_cfg_ssh, access_gituserhost(),
649 " set -e; cd ".access_cfg('git-path').";".
650 " if test -d $package.git; then echo 1; else echo 0; fi");
651 my $r= cmdoutput @cmd;
652 failedcmd @cmd unless $r =~ m/^[01]$/;
655 badcfg "unknown git-check \`$how'";
659 sub create_remote_git_repo () {
660 my $how = access_cfg('git-create');
661 if ($how eq 'ssh-cmd') {
663 (access_cfg_ssh, access_gituserhost(),
664 "set -e; cd ".access_cfg('git-path').";".
665 " cp -a _template $package.git");
667 badcfg "unknown git-create \`$how'";
671 our ($dsc_hash,$lastpush_hash);
673 our $ud = '.git/dgit/unpack';
681 sub mktree_in_ud_from_only_subdir () {
682 # changes into the subdir
685 $dirs[0] =~ m#^([^/]+)/\.$# or die;
687 chdir $dir or die "$dir $!";
688 fail "source package contains .git directory" if stat '.git';
689 die $! unless $!==&ENOENT;
690 runcmd qw(git init -q);
691 rmtree('.git/objects');
692 symlink '../../../../objects','.git/objects' or die $!;
693 runcmd @git, qw(add -Af);
694 my $tree = cmdoutput @git, qw(write-tree);
695 $tree =~ m/^\w+$/ or die "$tree ?";
699 sub dsc_files_info () {
700 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
701 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
702 ['Files', 'Digest::MD5', 'new()']) {
703 my ($fname, $module, $method) = @$csumi;
704 my $field = $dsc->{$fname};
705 next unless defined $field;
706 eval "use $module; 1;" or die $@;
708 foreach (split /\n/, $field) {
710 m/^(\w+) (\d+) (\S+)$/ or
711 fail "could not parse .dsc $fname line \`$_'";
712 my $digester = eval "$module"."->$method;" or die $@;
717 Digester => $digester,
722 fail "missing any supported Checksums-* or Files field in ".
723 $dsc->get_option('name');
727 map { $_->{Filename} } dsc_files_info();
730 sub is_orig_file ($) {
732 m/\.orig(?:-\w+)?\.tar\.\w+$/;
735 sub make_commit ($) {
737 return cmdoutput @git, qw(hash-object -w -t commit), $file;
740 sub clogp_authline ($) {
742 my $author = getfield $clogp, 'Maintainer';
743 $author =~ s#,.*##ms;
744 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
745 my $authline = "$author $date";
746 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
747 fail "unexpected commit author line format \`$authline'".
748 " (was generated from changelog Maintainer field)";
752 sub generate_commit_from_dsc () {
756 foreach my $f (dsc_files()) {
757 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
759 link "../../../$f", $f
763 runcmd @dget, qw(--), $dscurl;
764 foreach my $f (grep { is_orig_file($_) } @files) {
765 link $f, "../../../../$f"
769 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
770 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
771 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
772 my $authline = clogp_authline $clogp;
773 my $changes = getfield $clogp, 'Changes';
774 open C, ">../commit.tmp" or die $!;
775 print C <<END or die $!;
782 # imported from the archive
785 my $outputhash = make_commit qw(../commit.tmp);
786 my $cversion = getfield $clogp, 'Version';
787 progress "synthesised git commit from .dsc $cversion";
788 if ($lastpush_hash) {
789 runcmd @git, qw(reset --hard), $lastpush_hash;
790 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
791 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
792 my $oversion = getfield $oldclogp, 'Version';
794 version_compare_string($oversion, $cversion);
796 # git upload/ is earlier vsn than archive, use archive
797 open C, ">../commit2.tmp" or die $!;
798 print C <<END or die $!;
800 parent $lastpush_hash
805 Record $package ($cversion) in archive suite $csuite
807 $outputhash = make_commit qw(../commit2.tmp);
808 } elsif ($vcmp > 0) {
809 print STDERR <<END or die $!;
811 Version actually in archive: $cversion (older)
812 Last allegedly pushed/uploaded: $oversion (newer or same)
815 $outputhash = $lastpush_hash;
817 $outputhash = $lastpush_hash;
820 chdir '../../../..' or die $!;
821 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
822 'DGIT_ARCHIVE', $outputhash;
823 cmdoutput @git, qw(log -n2), $outputhash;
824 # ... gives git a chance to complain if our commit is malformed
829 sub ensure_we_have_orig () {
830 foreach my $fi (dsc_files_info()) {
831 my $f = $fi->{Filename};
832 next unless is_orig_file($f);
833 if (open F, "<", "../$f") {
834 $fi->{Digester}->reset();
835 $fi->{Digester}->addfile(*F);
837 my $got = $fi->{Digester}->hexdigest();
838 $got eq $fi->{Hash} or
839 fail "existing file $f has hash $got but .dsc".
840 " demands hash $fi->{Hash}".
841 " (perhaps you should delete this file?)";
842 progress "using existing $f";
845 die "$f $!" unless $!==&ENOENT;
847 my $origurl = $dscurl;
848 $origurl =~ s{/[^/]+$}{};
850 die "$f ?" unless $f =~ m/^${package}_/;
851 die "$f ?" if $f =~ m#/#;
852 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
857 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
860 sub is_fast_fwd ($$) {
861 my ($ancestor,$child) = @_;
862 my @cmd = (@git, qw(merge-base), $ancestor, $child);
863 my $mb = cmdoutput_errok @cmd;
865 return rev_parse($mb) eq rev_parse($ancestor);
867 $?==256 or failedcmd @cmd;
872 sub git_fetch_us () {
873 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
876 sub fetch_from_archive () {
877 # ensures that lrref() is what is actually in the archive,
882 foreach my $field (@ourdscfield) {
883 $dsc_hash = $dsc->{$field};
884 last if defined $dsc_hash;
886 if (defined $dsc_hash) {
887 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
889 progress "last upload to archive specified git hash";
891 progress "last upload to archive has NO git hash";
894 progress "no version available from the archive";
897 my $lrref_fn = ".git/".lrref();
898 if (open H, $lrref_fn) {
899 $lastpush_hash = <H>;
900 chomp $lastpush_hash;
901 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
902 } elsif ($! == &ENOENT) {
907 print DEBUG "previous reference hash=$lastpush_hash\n";
909 if (defined $dsc_hash) {
910 fail "missing git history even though dsc has hash -".
911 " could not find commit $dsc_hash".
912 " (should be in ".access_giturl()."#".rrref().")"
913 unless $lastpush_hash;
915 ensure_we_have_orig();
916 if ($dsc_hash eq $lastpush_hash) {
917 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
918 print STDERR <<END or die $!;
920 Git commit in archive is behind the last version allegedly pushed/uploaded.
921 Commit referred to by archive: $dsc_hash
922 Last allegedly pushed/uploaded: $lastpush_hash
925 $hash = $lastpush_hash;
927 fail "archive's .dsc refers to ".$dsc_hash.
928 " but this is an ancestor of ".$lastpush_hash;
931 $hash = generate_commit_from_dsc();
932 } elsif ($lastpush_hash) {
933 # only in git, not in the archive yet
934 $hash = $lastpush_hash;
935 print STDERR <<END or die $!;
937 Package not found in the archive, but has allegedly been pushed using dgit.
941 print DEBUG "nothing found!\n";
942 if (defined $skew_warning_vsn) {
943 print STDERR <<END or die $!;
945 Warning: relevant archive skew detected.
946 Archive allegedly contains $skew_warning_vsn
947 But we were not able to obtain any version from the archive or git.
953 print DEBUG "current hash=$hash\n";
954 if ($lastpush_hash) {
955 fail "not fast forward on last upload branch!".
956 " (archive's version left in DGIT_ARCHIVE)"
957 unless is_fast_fwd($lastpush_hash, $hash);
959 if (defined $skew_warning_vsn) {
961 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
962 my $clogf = ".git/dgit/changelog.tmp";
963 runcmd shell_cmd "exec >$clogf",
964 @git, qw(cat-file blob), "$hash:debian/changelog";
965 my $gotclogp = parsechangelog("-l$clogf");
966 my $got_vsn = getfield $gotclogp, 'Version';
967 print DEBUG "SKEW CHECK GOT $got_vsn\n";
968 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
969 print STDERR <<END or die $!;
971 Warning: archive skew detected. Using the available version:
972 Archive allegedly contains $skew_warning_vsn
973 We were able to obtain only $got_vsn
978 if ($lastpush_hash ne $hash) {
979 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
983 dryrun_report @upd_cmd;
991 canonicalise_suite();
992 badusage "dry run makes no sense with clone" if $dryrun;
993 mkdir $dstdir or die "$dstdir $!";
994 chdir "$dstdir" or die "$dstdir $!";
995 runcmd @git, qw(init -q);
996 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
997 open H, "> .git/HEAD" or die $!;
998 print H "ref: ".lref()."\n" or die $!;
1000 runcmd @git, qw(remote add), 'origin', access_giturl();
1001 if (check_for_git()) {
1002 progress "fetching existing git history";
1004 runcmd_ordryrun @git, qw(fetch origin);
1006 progress "starting new git history";
1008 fetch_from_archive() or no_such_package;
1009 runcmd @git, qw(reset --hard), lrref();
1010 printdone "ready for work in $dstdir";
1014 if (check_for_git()) {
1017 fetch_from_archive() or no_such_package();
1018 printdone "fetched into ".lrref();
1023 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
1025 printdone "fetched to ".lrref()." and merged into HEAD";
1028 sub check_not_dirty () {
1029 return if $ignoredirty;
1030 my @cmd = (@git, qw(diff --quiet HEAD));
1031 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1032 $!=0; $?=0; system @cmd;
1033 return if !$! && !$?;
1034 if (!$! && $?==256) {
1035 fail "working tree is dirty (does not match HEAD)";
1041 sub commit_quilty_patch () {
1042 my $output = cmdoutput @git, qw(status --porcelain);
1045 foreach my $l (split /\n/, $output) {
1046 next unless $l =~ m/\S/;
1047 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1050 print STDERR "git status: $l\n";
1054 fail "unexpected output from git status (is tree clean?)" if $bad;
1056 progress "nothing quilty to commit, ok.";
1059 runcmd_ordryrun @git, qw(add), sort keys %adds;
1060 my $m = "Commit Debian 3.0 (quilt) metadata";
1062 runcmd_ordryrun @git, qw(commit -m), $m;
1067 return 0 unless $format eq '3.0 (quilt)';
1068 progress "Format \`$format', urgh";
1070 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1076 sub push_parse_changelog ($) {
1079 my $clogp = Dpkg::Control::Hash->new();
1080 $clogp->load($clogpfn);
1082 $package = getfield $clogp, 'Source';
1083 my $cversion = getfield $clogp, 'Version';
1084 my $tag = debiantag($cversion);
1085 runcmd @git, qw(check-ref-format), $tag;
1087 my $dscfn = dscfn($cversion);
1089 return ($clogp, $cversion, $tag, $dscfn);
1092 sub push_parse_dsc ($$) {
1093 my ($dscfn,$dscfnwhat, $cversion) = @_;
1094 $dsc = parsecontrol($dscfn,$dscfnwhat);
1095 my $dversion = getfield $dsc, 'Version';
1096 my $dscpackage = getfield $dsc, 'Source';
1097 ($dscpackage eq $package && $dversion eq $cversion) or
1098 fail "$dsc is for $dscpackage $dversion".
1099 " but debian/changelog is for $package $cversion";
1102 sub push_mktag ($$$$$$$$) {
1103 my ($head,$clogp,$tag,
1105 $changesfile,$changesfilewhat,
1108 $dsc->{$ourdscfield[0]} = $head;
1109 $dsc->save("$dscfn.tmp") or die $!;
1111 my $changes = parsecontrol($changesfile,$changesfilewhat);
1112 foreach my $field (qw(Source Distribution Version)) {
1113 $changes->{$field} eq $clogp->{$field} or
1114 fail "changes field $field \`$changes->{$field}'".
1115 " does not match changelog \`$clogp->{$field}'";
1118 # We make the git tag by hand because (a) that makes it easier
1119 # to control the "tagger" (b) we can do remote signing
1120 my $authline = clogp_authline $clogp;
1121 open TO, '>', $tfn->('.tmp') or die $!;
1122 print TO <<END or die $!;
1128 $package release $cversion for $csuite [dgit]
1132 my $tagobjfn = $tfn->('.tmp');
1134 if (!defined $keyid) {
1135 $keyid = access_cfg('keyid','RETURN-UNDEF');
1137 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1138 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1139 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1140 push @sign_cmd, $tfn->('.tmp');
1141 runcmd_ordryrun @sign_cmd;
1143 $tagobjfn = $tfn->('.signed.tmp');
1144 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1145 $tfn->('.tmp'), $tfn->('.tmp.asc');
1152 sub sign_changes ($) {
1153 my ($changesfile) = @_;
1155 my @debsign_cmd = @debsign;
1156 push @debsign_cmd, "-k$keyid" if defined $keyid;
1157 push @debsign_cmd, "-p$pgp[0]" if $pgp[0] ne 'gpg';
1158 push @debsign_cmd, $changesfile;
1159 runcmd_ordryrun @debsign_cmd;
1164 print DEBUG "actually entering push\n";
1167 my $clogpfn = ".git/dgit/changelog.822.tmp";
1168 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1170 responder_send_file('parsed-changelog', $clogpfn);
1172 my ($clogp, $cversion, $tag, $dscfn) =
1173 push_parse_changelog("$clogpfn");
1176 fail "looked for .dsc $dscfn, but $!;".
1177 " maybe you forgot to build";
1179 responder_send_file('dsc', "../$dscfn");
1181 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1183 my $format = getfield $dsc, 'Format';
1184 print DEBUG "format $format\n";
1185 if (madformat($format)) {
1186 commit_quilty_patch();
1189 chdir $ud or die $!;
1190 progress "checking that $dscfn corresponds to HEAD";
1191 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1192 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1193 chdir '../../../..' or die $!;
1194 printcmd \*DEBUG,"+",@_;
1195 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1197 if (system @diffcmd) {
1198 if ($! && $?==256) {
1199 fail "$dscfn specifies a different tree to your HEAD commit;".
1200 " perhaps you forgot to build";
1206 #do fast forward check and maybe fake merge
1207 # if (!is_fast_fwd(mainbranch
1208 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1209 # map { lref($_).":".rref($_) }
1211 my $head = rev_parse('HEAD');
1212 if (!$changesfile) {
1213 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1214 if (stat "$multi") {
1215 $changesfile = $multi;
1217 $!==&ENOENT or die "$multi: $!";
1218 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1219 my @cs = glob "../$pat";
1220 fail "failed to find unique changes file".
1221 " (looked for $pat in .., or $multi);".
1222 " perhaps you need to use dgit -C"
1224 ($changesfile) = @cs;
1228 responder_send_file('changes',$changesfn);
1230 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1233 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1234 : push_mktag($head,$clogp,$tag,
1236 $changesfile,$changesfile,
1239 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1240 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1241 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1242 runcmd_ordryrun @git, qw(tag -v --), $tag;
1244 if (!check_for_git()) {
1245 create_remote_git_repo();
1247 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1248 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1250 if (!$we_are_responder) {
1252 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1254 progress "[new .dsc left in $dscfn.tmp]";
1258 if ($we_are_responder) {
1259 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1260 responder_receive_files('signed-dsc-changes',
1261 "../$dscfn$dryrunsuffix",
1262 "$changesfile$dryrupnsuffix");
1264 sign_changes $changesfile;
1267 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1268 my $host = access_cfg('upload-host','RETURN-UNDEF');
1269 my @hostarg = defined($host) ? ($host,) : ();
1270 runcmd_ordryrun @dput, @hostarg, $changesfile;
1271 printdone "pushed and uploaded $cversion";
1273 responder_send_command("complete");
1279 badusage "-p is not allowed with clone; specify as argument instead"
1280 if defined $package;
1283 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1284 ($package,$isuite) = @ARGV;
1285 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1286 ($package,$dstdir) = @ARGV;
1287 } elsif (@ARGV==3) {
1288 ($package,$isuite,$dstdir) = @ARGV;
1290 badusage "incorrect arguments to dgit clone";
1292 $dstdir ||= "$package";
1296 sub branchsuite () {
1297 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1298 if ($branch =~ m#$lbranch_re#o) {
1305 sub fetchpullargs () {
1306 if (!defined $package) {
1307 my $sourcep = parsecontrol('debian/control','debian/control');
1308 $package = getfield $sourcep, 'Source';
1311 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1313 my $clogp = parsechangelog();
1314 $isuite = getfield $clogp, 'Distribution';
1316 canonicalise_suite();
1317 progress "fetching from suite $csuite";
1318 } elsif (@ARGV==1) {
1320 canonicalise_suite();
1322 badusage "incorrect arguments to dgit fetch or dgit pull";
1340 badusage "-p is not allowed with dgit push" if defined $package;
1342 my $clogp = parsechangelog();
1343 $package = getfield $clogp, 'Source';
1346 } elsif (@ARGV==1) {
1347 ($specsuite) = (@ARGV);
1349 badusage "incorrect arguments to dgit push";
1351 $isuite = getfield $clogp, 'Distribution';
1353 local ($package) = $existing_package; # this is a hack
1354 canonicalise_suite();
1356 if (defined $specsuite && $specsuite ne $isuite) {
1357 canonicalise_suite();
1358 $csuite eq $specsuite or
1359 fail "dgit push: changelog specifies $isuite ($csuite)".
1360 " but command line specifies $specsuite";
1362 if (check_for_git()) {
1365 if (fetch_from_archive()) {
1366 is_fast_fwd(lrref(), 'HEAD') or
1367 fail "dgit push: HEAD is not a descendant".
1368 " of the archive's version.\n".
1369 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1372 fail "package appears to be new in this suite;".
1373 " if this is intentional, use --new";
1378 #---------- remote commands' implementation ----------
1380 sub cmd_remote_push_responder {
1381 my ($nrargs) = shift @ARGV;
1382 my (@rargs) = @ARGV[0..$nrargs-1];
1383 @ARGV = @ARGV[$nrargs..$#ARGV];
1386 chdir $dir or die "$dir: $!";
1389 responder_send_command("dgit-remote-push-ready");
1397 return unless defined $i_tmp;
1398 chdir "/" or die $!;
1399 eval { rmtree $i_tmp; };
1403 my ($base,$selector,@args) = @_;
1404 $selector =~ s/\-/_/g;
1405 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1411 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1421 push @rdgit, @ropts;
1422 push @rdgit, (scalar @rargs), @rargs;
1424 my @cmd = (@ssh, $host, shellquote @rdgit);
1425 my $pid = open2(\*RO, \*RI, @cmd);
1428 chdir $i_tmp or die "$i_tmp $!";
1429 initiator_expect { m/^dgit-remote-push-ready/ };
1431 initiator_expect { m/^(\S+)(?: (.*))?$/ };
1432 my ($icmd,$iargs) = ($1, $2);
1433 i_method "i_resp_", $icmd, $iargs;
1440 sub i_resp_progress ($) {
1442 my $msg = protocol_read_bytes \*RO, $rhs;
1446 sub i_resp_complete {
1451 sub i_resp_file ($) {
1453 my $localname = i_method "i_localname_", $keyword;
1454 my $localpath = "$i_tmp/$localname";
1455 stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1456 protocol_receive_file \*RO, $localpath;
1462 $_[0] =~ m/^(\S+) (.*)$/;
1468 sub i_resp_want ($) {
1470 die "$keyword ?" if $i_wanted{$keyword}++;
1471 my @localpaths = i_method "i_want_", $keyword;
1472 foreach my $localpath (@localpaths) {
1473 protocol_send_file \*RI, $localpath;
1475 print RI "end-files\n" or die $!;
1478 our ($i_clogp, $i_version, $i_tag, $i_dscfn);
1480 sub i_localname_parsed_changelog { return "remote-changelog.822"; }
1481 sub i_localname_changes { return "remote.changes"; }
1482 sub i_localname_dsc {
1483 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1484 push_parse_changelog 'remote-changelog.822';
1485 die if $i_dscfn =~ m#/|^\W#;
1489 sub i_want_signed_tag {
1490 defined $i_param{'head'} && defined $dscfn
1491 or badproto \*RO, "sequencing error";
1492 my $head = $i_param{'head'};
1493 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1495 push_parse_dsc $i_dscfn, 'remote dsc',
1497 push_mktag $head, $i_clogp, $i_tag,
1499 'remote.changes', 'remote changes',
1505 sub i_want_signed_dsc_changes {
1506 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1507 sign_changes 'remote.changes';
1508 return ($i_dscfn, 'remote.changes');
1511 #---------- building etc. ----------
1517 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1519 sub build_maybe_quilt_fixup () {
1520 if (!open F, "debian/source/format") {
1521 die $! unless $!==&ENOENT;
1525 F->error and die $!;
1527 return unless madformat($_);
1529 my $clogp = parsechangelog();
1530 my $version = getfield $clogp, 'Version';
1531 my $author = getfield $clogp, 'Maintainer';
1532 my $headref = rev_parse('HEAD');
1535 my $patchname = "auto-$version-$headref-$time";
1536 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1538 my $descfn = ".git/dgit/quilt-description.tmp";
1539 open O, '>', $descfn or die "$descfn: $!";
1541 $msg =~ s/^\s+$/ ./mg;
1542 print O <<END or die $!;
1543 Description: Automatically generated patch ($clogp->{Version})
1544 Last (up to) $ncommits git changes, FYI:
1554 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1555 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1556 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1557 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1560 if (!open P, '>>', ".pc/applied-patches") {
1561 $!==&ENOENT or die $!;
1566 commit_quilty_patch();
1569 sub quilt_fixup_editor () {
1570 my $descfn = $ENV{$fakeeditorenv};
1571 my $editing = $ARGV[$#ARGV];
1572 open I1, '<', $descfn or die "$descfn: $!";
1573 open I2, '<', $editing or die "$editing: $!";
1574 unlink $editing or die "$editing: $!";
1575 open O, '>', $editing or die "$editing: $!";
1576 while (<I1>) { print O or die $!; } I1->error and die $!;
1579 $copying ||= m/^\-\-\- /;
1580 next unless $copying;
1583 I2->error and die $!;
1589 badusage "-p is not allowed when building" if defined $package;
1591 my $clogp = parsechangelog();
1592 $isuite = getfield $clogp, 'Distribution';
1593 $package = getfield $clogp, 'Source';
1594 $version = getfield $clogp, 'Version';
1595 build_maybe_quilt_fixup();
1599 badusage "dgit build implies --clean=dpkg-source"
1600 if $cleanmode ne 'dpkg-source';
1602 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1603 printdone "build successful\n";
1607 badusage "dgit git-build implies --clean=dpkg-source"
1608 if $cleanmode ne 'dpkg-source';
1611 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1612 "--git-builder=@dpkgbuildpackage");
1613 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1614 canonicalise_suite();
1615 push @cmd, "--git-debian-branch=".lbranch();
1617 push @cmd, changesopts();
1618 runcmd_ordryrun @cmd, @ARGV;
1619 printdone "build successful\n";
1624 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1625 $dscfn = dscfn($version);
1626 if ($cleanmode eq 'dpkg-source') {
1627 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1629 if ($cleanmode eq 'git') {
1630 runcmd_ordryrun @git, qw(clean -xdf);
1631 } elsif ($cleanmode eq 'none') {
1635 my $pwd = cmdoutput qw(env - pwd);
1636 my $leafdir = basename $pwd;
1637 chdir ".." or die $!;
1638 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1639 chdir $pwd or die $!;
1640 runcmd_ordryrun qw(sh -ec),
1641 'exec >$1; shift; exec "$@"','x',
1642 "../$sourcechanges",
1643 @dpkggenchanges, qw(-S), changesopts();
1647 sub cmd_build_source {
1648 badusage "build-source takes no additional arguments" if @ARGV;
1650 printdone "source built, results in $dscfn and $sourcechanges";
1655 chdir ".." or die $!;
1656 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1658 stat $dscfn or fail "$dscfn (in parent directory): $!";
1659 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1660 foreach my $cf (glob $pat) {
1661 next if $cf eq $sourcechanges;
1662 unlink $cf or fail "remove $cf: $!";
1665 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1666 runcmd_ordryrun @mergechanges, glob $pat;
1667 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1669 stat $multichanges or fail "$multichanges: $!";
1671 printdone "build successful, results in $multichanges\n" or die $!;
1674 sub cmd_quilt_fixup {
1675 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1676 my $clogp = parsechangelog();
1677 $version = getfield $clogp, 'Version';
1678 build_maybe_quilt_fixup();
1681 #---------- argument parsing and main program ----------
1684 print "dgit version $our_version\n" or die $!;
1691 if (defined $ENV{'DGIT_SSH'}) {
1692 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1693 } elsif (defined $ENV{'GIT_SSH'}) {
1694 @ssh = ($ENV{'GIT_SSH'});
1698 last unless $ARGV[0] =~ m/^-/;
1702 if (m/^--dry-run$/) {
1705 } elsif (m/^--no-sign$/) {
1708 } elsif (m/^--help$/) {
1710 } elsif (m/^--version$/) {
1712 } elsif (m/^--new$/) {
1715 } elsif (m/^--(\w+)=(.*)/s &&
1716 ($om = $opts_opt_map{$1}) &&
1720 } elsif (m/^--(\w+):(.*)/s &&
1721 !$opts_opt_cmdonly{$1} &&
1722 ($om = $opts_opt_map{$1})) {
1725 } elsif (m/^--existing-package=(.*)/s) {
1727 $existing_package = $1;
1728 } elsif (m/^--distro=(.*)/s) {
1731 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1734 } elsif (m/^--clean=(.*)$/s) {
1735 badusage "unknown cleaning mode \`$1'";
1736 } elsif (m/^--ignore-dirty$/s) {
1739 } elsif (m/^--no-quilt-fixup$/s) {
1743 badusage "unknown long option \`$_'";
1750 } elsif (s/^-h/-/) {
1752 } elsif (s/^-D/-/) {
1754 open DEBUG, ">&STDERR" or die $!;
1756 } elsif (s/^-N/-/) {
1759 } elsif (m/^-[vm]/) {
1761 push @changesopts, $_;
1763 } elsif (s/^-c(.*=.*)//s) {
1765 push @git, '-c', $1;
1766 } elsif (s/^-d(.*)//s) {
1769 } elsif (s/^-C(.*)//s) {
1772 } elsif (s/^-k(.*)//s) {
1774 } elsif (s/^-wn//s) {
1776 $cleanmode = 'none';
1777 } elsif (s/^-wg//s) {
1780 } elsif (s/^-wd//s) {
1782 $cleanmode = 'dpkg-source';
1784 badusage "unknown short option \`$_'";
1791 if ($ENV{$fakeeditorenv}) {
1792 quilt_fixup_editor();
1795 delete $ENV{'DGET_UNPACK'};
1798 print STDERR "DRY RUN ONLY\n" if $dryrun;
1800 print STDERR $helpmsg or die $!;
1803 my $cmd = shift @ARGV;
1805 { no strict qw(refs); &{"cmd_$cmd"}(); }