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;
32 our $our_version = 'UNRELEASED'; ###substituted###
34 our $isuite = 'unstable';
45 our $existing_package = 'dpkg';
46 our $cleanmode = 'dpkg-source';
47 our $we_are_responder;
49 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
52 our (@dget) = qw(dget);
53 our (@dput) = qw(dput);
54 our (@debsign) = qw(debsign);
56 our (@sbuild) = qw(sbuild -A);
58 our (@dgit) = qw(dgit);
59 our (@dpkgbuildpackage) = qw(dpkg-buildpackage -i\.git/ -I.git);
60 our (@dpkgsource) = qw(dpkg-source -i\.git/ -I.git);
61 our (@dpkggenchanges) = qw(dpkg-genchanges);
62 our (@mergechanges) = qw(mergechanges -f);
63 our (@changesopts) = ('');
65 our %opts_opt_map = ('dget' => \@dget,
67 'debsign' => \@debsign,
72 'dpkg-source' => \@dpkgsource,
73 'dpkg-buildpackage' => \@dpkgbuildpackage,
74 'dpkg-genchanges' => \@dpkggenchanges,
75 'ch' => \@changesopts,
76 'mergechanges' => \@mergechanges);
78 our %opts_opt_cmdonly = ('gpg' => 1);
83 open DEBUG, ">/dev/null" or die $!;
85 our $remotename = 'dgit';
86 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
87 our $branchprefix = 'dgit';
90 sub lbranch () { return "$branchprefix/$csuite"; }
91 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
92 sub lref () { return "refs/heads/".lbranch(); }
93 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
94 sub rrref () { return "refs/$branchprefix/$csuite"; }
109 return "${package}_".(stripepoch $vsn).".dsc";
112 sub changesopts () { return @changesopts[1..$#changesopts]; }
116 sub fail { die "$us: @_\n"; }
118 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
120 sub no_such_package () {
121 print STDERR "$us: package $package does not exist in suite $isuite\n";
127 return "+".rrref().":".lrref();
130 #---------- remote protocol support, common ----------
132 # remote push initiator/responder protocol:
133 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
135 # > file begin parsed-changelog
136 # [indicates that output of dpkg-parsechangelog follows]
137 # > data-block NBYTES
138 # > [NBYTES bytes of data (no newline)]
139 # [maybe some more blocks]
145 # > file begin changes
151 # [indicates that signed tag is wanted]
152 # < data-block NBYTES
153 # < [NBYTES bytes of data (no newline)]
154 # [maybe some more blocks]
158 # > want signed-dsc-changes
159 # < data-block NBYTES [transfer of signed dsc]
161 # < data-block NBYTES [transfer of signed changes]
169 fail "connection lost: $!" if $fh->error;
170 fail "connection terminated" if $fh->eof;
171 fail "protocol violation; $m not expected";
174 sub protocol_expect (&$) {
175 my ($match, $fh) = @_;
178 defined && chomp or badproto $fh, "eof";
180 badproto $fh, "\`$_'";
183 sub protocol_send_file ($$) {
184 my ($fh, $ourfn) = @_;
185 open PF, "<", $ourfn or die "$ourfn: $!";
188 my $got = read PF, $d, 65536;
189 die "$ourfn: $!" unless defined $got;
191 print $fh "data-block ".length($d)."\n" or die $!;
194 print $fh "data-end\n" or die $!;
198 sub protocol_read_bytes ($$) {
199 my ($fh, $nbytes) = @_;
200 $nbytes =~ m/^\d{1,6}$/ or badproto \*RO, "bad byte count";
202 my $got = read $fh, $d, $nbytes;
203 $got==$nbytes or badproto $fh, "eof during data block";
207 sub protocol_receive_file ($$) {
208 my ($fh, $ourfn) = @_;
209 open PF, ">", $ourfn or die "$ourfn: $!";
211 protocol_expect { m/^data-block (.*})$|data-end$/ } \*STDIN;
213 my $d = protocol_read_bytes \*STDIN, $1;
214 print PF $d or die $!;
218 #---------- remote protocol support, responder ----------
220 sub responder_send_command ($) {
222 return unless $we_are_responder;
223 # called even without $we_are_responder
224 print DEBUG "<< $command\n";
225 print $command, "\n" or die $!;
228 sub responder_send_file ($$) {
229 my ($keyword, $ourfn) = @_;
230 return unless $we_are_responder;
231 responder_send_command "file-begin $keyword";
232 protocol_send_file \*STDOUT, $ourfn;
235 sub responder_receive_files ($@) {
236 my ($keyword, @ourfns) = @_;
237 die unless $we_are_responder;
238 responder_send_command "want $keyword";
239 foreach my $fn (@ourfns) {
240 protocol_receive_file \*STDIN, $fn;
242 protocol_expect { m/^files-end$/ } \*STDIN;
245 #---------- remote protocol support, initiator ----------
247 sub initiator_expect (&) {
249 protocol_expect { &$match } \*RO;
252 #---------- end remote code ----------
255 if ($we_are_responder) {
257 responder_send_command "progress ".length($m) or die $!;
268 $ua = LWP::UserAgent->new();
272 progress "downloading $what...";
273 my $r = $ua->get(@_) or die $!;
274 return undef if $r->code == 404;
275 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
276 return $r->decoded_content();
279 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
286 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
292 return join '', @out;
297 my $intro = shift @_;
298 print $fh $intro or die $!;
299 print $fh shellquote @_ or die $!;
300 print $fh "\n" or die $!;
304 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
306 fail "failed to fork/exec: $!";
307 } elsif (!($? & 0xff)) {
308 fail "subprocess failed with error exit status ".($?>>8);
310 fail "subprocess crashed (wait status $?)";
312 fail "subprocess produced invalid output";
317 printcmd(\*DEBUG,"+",@_) if $debug>0;
319 failedcmd @_ if system @_;
324 progress "dgit ok: @_";
326 progress "would be ok: @_ (but dry run only)";
330 sub cmdoutput_errok {
331 die Dumper(\@_)." ?" if grep { !defined } @_;
332 printcmd(\*DEBUG,"|",@_) if $debug>0;
333 open P, "-|", @_ or die $!;
336 { local $/ = undef; $d = <P>; }
338 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
341 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
346 my $d = cmdoutput_errok @_;
347 defined $d or failedcmd @_;
352 printcmd(\*STDERR,"#",@_);
355 sub runcmd_ordryrun {
364 my ($first_shell, @cmd) = @_;
365 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
368 our $helpmsg = <<END;
370 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
371 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
372 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
373 dgit [dgit-opts] push [dgit-opts] [suite]
374 important dgit options:
375 -k<keyid> sign tag and package with <keyid> instead of default
376 --dry-run -n do not change anything, but go through the motions
377 --new -N allow introducing a new package
378 --debug -D increase debug level
379 -c<name>=<value> set git config option (used directly by dgit too)
382 our $later_warning_msg = <<END;
383 Perhaps the upload is stuck in incoming. Using the version from git.
387 print STDERR "$us: @_\n", $helpmsg or die $!;
392 @ARGV or badusage "too few arguments";
393 return scalar shift @ARGV;
397 print $helpmsg or die $!;
401 our %defcfg = ('dgit.default.distro' => 'debian',
402 'dgit.default.username' => '',
403 'dgit.default.archive-query-default-component' => 'main',
404 'dgit.default.ssh' => 'ssh',
405 'dgit-distro.debian.git-host' => 'git.debian.org',
406 'dgit-distro.debian.git-proto' => 'git+ssh://',
407 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
408 'dgit-distro.debian.git-check' => 'ssh-cmd',
409 'dgit-distro.debian.git-create' => 'ssh-cmd',
410 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
411 'dgit-distro.debian.sshdakls-dir' =>
412 '/srv/ftp-master.debian.org/ftp/dists',
413 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
414 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
418 return undef if $c =~ /RETURN-UNDEF/;
419 my @cmd = (@git, qw(config --), $c);
422 local ($debug) = $debug-1;
423 $v = cmdoutput_errok @cmd;
430 my $dv = $defcfg{$c};
431 return $dv if defined $dv;
433 badcfg "need value for one of: @_";
436 sub access_distro () {
437 return cfg("dgit-suite.$isuite.distro",
438 "dgit.default.distro");
443 my $distro = $idistro || access_distro();
444 my $value = cfg(map { ("dgit-distro.$distro.$_",
445 "dgit.default.$_") } @keys);
449 sub string_to_ssh ($) {
451 if ($spec =~ m/\s/) {
452 return qw(sh -ec), 'exec '.$spec.' "$@"', 'x';
458 sub access_cfg_ssh () {
459 my $gitssh = access_cfg('ssh', 'RETURN-UNDEF');
460 if (!defined $gitssh) {
463 return string_to_ssh $gitssh;
467 sub access_someuserhost ($) {
469 my $user = access_cfg("$some-user",'username');
470 my $host = access_cfg("$some-host");
471 return length($user) ? "$user\@$host" : $host;
474 sub access_gituserhost () {
475 return access_someuserhost('git');
478 sub access_giturl () {
479 my $url = access_cfg('git-url','RETURN-UNDEF');
482 access_cfg('git-proto').
483 access_gituserhost().
484 access_cfg('git-path');
486 return "$url/$package.git";
489 sub parsecontrolfh ($$@) {
490 my ($fh, $desc, @opts) = @_;
491 my %opts = ('name' => $desc, @opts);
492 my $c = Dpkg::Control::Hash->new(%opts);
493 $c->parse($fh) or die "parsing of $desc failed";
498 my ($file, $desc) = @_;
499 my $fh = new IO::Handle;
500 open $fh, '<', $file or die "$file: $!";
501 my $c = parsecontrolfh($fh,$desc);
502 $fh->error and die $!;
508 my ($dctrl,$field) = @_;
509 my $v = $dctrl->{$field};
510 return $v if defined $v;
511 fail "missing field $field in ".$v->get_option('name');
515 my $c = Dpkg::Control::Hash->new();
516 my $p = new IO::Handle;
517 my @cmd = (qw(dpkg-parsechangelog), @_);
518 open $p, '-|', @cmd or die $!;
520 $?=0; $!=0; close $p or failedcmd @cmd;
526 sub archive_query ($) {
528 my $query = access_cfg('archive-query','RETURN-UNDEF');
529 if (!defined $query) {
530 my $distro = access_distro();
531 if ($distro eq 'debian') {
532 $query = "sshdakls:".
533 access_someuserhost('sshdakls').':'.
534 access_cfg('sshdakls-dir');
536 $query = "madison:$distro";
539 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
542 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
545 sub archive_query_madison ($$) {
546 my ($proto,$data) = @_;
547 die unless $proto eq 'madison';
548 $rmad{$package} ||= cmdoutput
549 qw(rmadison -asource),"-s$isuite","-u$data",$package;
550 my $rmad = $rmad{$package};
551 return madison_parse($rmad);
554 sub archive_query_sshdakls ($$) {
555 my ($proto,$data) = @_;
556 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
557 my $dakls = cmdoutput
558 access_cfg_ssh, $data, qw(dak ls -asource),"-s$isuite",$package;
559 return madison_parse($dakls);
562 sub canonicalise_suite_sshdakls ($$) {
563 my ($proto,$data) = @_;
564 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
568 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
569 " if test -d $isuite; then echo $isuite; exit 0; fi;".
571 my $dakls = cmdoutput @cmd;
572 failedcmd @cmd unless $dakls =~ m/^\w/;
576 sub madison_parse ($) {
579 foreach my $l (split /\n/, $rmad) {
580 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
581 \s*( [^ \t|]+ )\s* \|
582 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
583 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
584 $1 eq $package or die "$rmad $package ?";
591 $component = access_cfg('archive-query-default-component');
593 $5 eq 'source' or die "$rmad ?";
594 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
595 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
596 push @out, [$vsn,$subpath,$newsuite];
598 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
601 sub canonicalise_suite_madison ($$) {
602 my @r = archive_query_madison($_[0],$_[1]);
604 "unable to canonicalise suite using package $package".
605 " which does not appear to exist in suite $isuite;".
606 " --existing-package may help";
610 sub canonicalise_suite () {
611 return if defined $csuite;
612 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
613 $csuite = archive_query('canonicalise_suite');
614 if ($isuite ne $csuite) {
615 # madison canonicalises for us
616 progress "canonical suite name for $isuite is $csuite";
620 sub get_archive_dsc () {
621 canonicalise_suite();
622 my @vsns = archive_query('archive_query');
623 foreach my $vinfo (@vsns) {
624 my ($vsn,$subpath) = @$vinfo;
625 $dscurl = access_cfg('mirror').$subpath;
626 $dscdata = url_get($dscurl);
628 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
631 my $dscfh = new IO::File \$dscdata, '<' or die $!;
632 print DEBUG Dumper($dscdata) if $debug>1;
633 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
634 print DEBUG Dumper($dsc) if $debug>1;
635 my $fmt = getfield $dsc, 'Format';
636 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
642 sub check_for_git () {
644 my $how = access_cfg('git-check');
645 if ($how eq 'ssh-cmd') {
647 (access_cfg_ssh, access_gituserhost(),
648 " set -e; cd ".access_cfg('git-path').";".
649 " if test -d $package.git; then echo 1; else echo 0; fi");
650 my $r= cmdoutput @cmd;
651 failedcmd @cmd unless $r =~ m/^[01]$/;
654 badcfg "unknown git-check \`$how'";
658 sub create_remote_git_repo () {
659 my $how = access_cfg('git-create');
660 if ($how eq 'ssh-cmd') {
662 (access_cfg_ssh, access_gituserhost(),
663 "set -e; cd ".access_cfg('git-path').";".
664 " cp -a _template $package.git");
666 badcfg "unknown git-create \`$how'";
670 our ($dsc_hash,$lastpush_hash);
672 our $ud = '.git/dgit/unpack';
680 sub mktree_in_ud_from_only_subdir () {
681 # changes into the subdir
684 $dirs[0] =~ m#^([^/]+)/\.$# or die;
686 chdir $dir or die "$dir $!";
687 fail "source package contains .git directory" if stat '.git';
688 die $! unless $!==&ENOENT;
689 runcmd qw(git init -q);
690 rmtree('.git/objects');
691 symlink '../../../../objects','.git/objects' or die $!;
692 runcmd @git, qw(add -Af);
693 my $tree = cmdoutput @git, qw(write-tree);
694 $tree =~ m/^\w+$/ or die "$tree ?";
698 sub dsc_files_info () {
699 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
700 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
701 ['Files', 'Digest::MD5', 'new()']) {
702 my ($fname, $module, $method) = @$csumi;
703 my $field = $dsc->{$fname};
704 next unless defined $field;
705 eval "use $module; 1;" or die $@;
707 foreach (split /\n/, $field) {
709 m/^(\w+) (\d+) (\S+)$/ or
710 fail "could not parse .dsc $fname line \`$_'";
711 my $digester = eval "$module"."->$method;" or die $@;
716 Digester => $digester,
721 fail "missing any supported Checksums-* or Files field in ".
722 $dsc->get_option('name');
726 map { $_->{Filename} } dsc_files_info();
729 sub is_orig_file ($) {
731 m/\.orig(?:-\w+)?\.tar\.\w+$/;
734 sub make_commit ($) {
736 return cmdoutput @git, qw(hash-object -w -t commit), $file;
739 sub clogp_authline ($) {
741 my $author = getfield $clogp, 'Maintainer';
742 $author =~ s#,.*##ms;
743 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
744 my $authline = "$author $date";
745 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
746 fail "unexpected commit author line format \`$authline'".
747 " (was generated from changelog Maintainer field)";
751 sub generate_commit_from_dsc () {
755 foreach my $f (dsc_files()) {
756 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
758 link "../../../$f", $f
762 runcmd @dget, qw(--), $dscurl;
763 foreach my $f (grep { is_orig_file($_) } @files) {
764 link $f, "../../../../$f"
768 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
769 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
770 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
771 my $authline = clogp_authline $clogp;
772 my $changes = getfield $clogp, 'Changes';
773 open C, ">../commit.tmp" or die $!;
774 print C <<END or die $!;
781 # imported from the archive
784 my $outputhash = make_commit qw(../commit.tmp);
785 my $cversion = getfield $clogp, 'Version';
786 progress "synthesised git commit from .dsc $cversion";
787 if ($lastpush_hash) {
788 runcmd @git, qw(reset --hard), $lastpush_hash;
789 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
790 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
791 my $oversion = getfield $oldclogp, 'Version';
793 version_compare_string($oversion, $cversion);
795 # git upload/ is earlier vsn than archive, use archive
796 open C, ">../commit2.tmp" or die $!;
797 print C <<END or die $!;
799 parent $lastpush_hash
804 Record $package ($cversion) in archive suite $csuite
806 $outputhash = make_commit qw(../commit2.tmp);
807 } elsif ($vcmp > 0) {
808 print STDERR <<END or die $!;
810 Version actually in archive: $cversion (older)
811 Last allegedly pushed/uploaded: $oversion (newer or same)
814 $outputhash = $lastpush_hash;
816 $outputhash = $lastpush_hash;
819 chdir '../../../..' or die $!;
820 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
821 'DGIT_ARCHIVE', $outputhash;
822 cmdoutput @git, qw(log -n2), $outputhash;
823 # ... gives git a chance to complain if our commit is malformed
828 sub ensure_we_have_orig () {
829 foreach my $fi (dsc_files_info()) {
830 my $f = $fi->{Filename};
831 next unless is_orig_file($f);
832 if (open F, "<", "../$f") {
833 $fi->{Digester}->reset();
834 $fi->{Digester}->addfile(*F);
836 my $got = $fi->{Digester}->hexdigest();
837 $got eq $fi->{Hash} or
838 fail "existing file $f has hash $got but .dsc".
839 " demands hash $fi->{Hash}".
840 " (perhaps you should delete this file?)";
841 progress "using existing $f";
844 die "$f $!" unless $!==&ENOENT;
846 my $origurl = $dscurl;
847 $origurl =~ s{/[^/]+$}{};
849 die "$f ?" unless $f =~ m/^${package}_/;
850 die "$f ?" if $f =~ m#/#;
851 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
856 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
859 sub is_fast_fwd ($$) {
860 my ($ancestor,$child) = @_;
861 my @cmd = (@git, qw(merge-base), $ancestor, $child);
862 my $mb = cmdoutput_errok @cmd;
864 return rev_parse($mb) eq rev_parse($ancestor);
866 $?==256 or failedcmd @cmd;
871 sub git_fetch_us () {
872 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
875 sub fetch_from_archive () {
876 # ensures that lrref() is what is actually in the archive,
881 foreach my $field (@ourdscfield) {
882 $dsc_hash = $dsc->{$field};
883 last if defined $dsc_hash;
885 if (defined $dsc_hash) {
886 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
888 progress "last upload to archive specified git hash";
890 progress "last upload to archive has NO git hash";
893 progress "no version available from the archive";
896 my $lrref_fn = ".git/".lrref();
897 if (open H, $lrref_fn) {
898 $lastpush_hash = <H>;
899 chomp $lastpush_hash;
900 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
901 } elsif ($! == &ENOENT) {
906 print DEBUG "previous reference hash=$lastpush_hash\n";
908 if (defined $dsc_hash) {
909 fail "missing git history even though dsc has hash -".
910 " could not find commit $dsc_hash".
911 " (should be in ".access_giturl()."#".rrref().")"
912 unless $lastpush_hash;
914 ensure_we_have_orig();
915 if ($dsc_hash eq $lastpush_hash) {
916 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
917 print STDERR <<END or die $!;
919 Git commit in archive is behind the last version allegedly pushed/uploaded.
920 Commit referred to by archive: $dsc_hash
921 Last allegedly pushed/uploaded: $lastpush_hash
924 $hash = $lastpush_hash;
926 fail "archive's .dsc refers to ".$dsc_hash.
927 " but this is an ancestor of ".$lastpush_hash;
930 $hash = generate_commit_from_dsc();
931 } elsif ($lastpush_hash) {
932 # only in git, not in the archive yet
933 $hash = $lastpush_hash;
934 print STDERR <<END or die $!;
936 Package not found in the archive, but has allegedly been pushed using dgit.
940 print DEBUG "nothing found!\n";
941 if (defined $skew_warning_vsn) {
942 print STDERR <<END or die $!;
944 Warning: relevant archive skew detected.
945 Archive allegedly contains $skew_warning_vsn
946 But we were not able to obtain any version from the archive or git.
952 print DEBUG "current hash=$hash\n";
953 if ($lastpush_hash) {
954 fail "not fast forward on last upload branch!".
955 " (archive's version left in DGIT_ARCHIVE)"
956 unless is_fast_fwd($lastpush_hash, $hash);
958 if (defined $skew_warning_vsn) {
960 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
961 my $clogf = ".git/dgit/changelog.tmp";
962 runcmd shell_cmd "exec >$clogf",
963 @git, qw(cat-file blob), "$hash:debian/changelog";
964 my $gotclogp = parsechangelog("-l$clogf");
965 my $got_vsn = getfield $gotclogp, 'Version';
966 print DEBUG "SKEW CHECK GOT $got_vsn\n";
967 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
968 print STDERR <<END or die $!;
970 Warning: archive skew detected. Using the available version:
971 Archive allegedly contains $skew_warning_vsn
972 We were able to obtain only $got_vsn
977 if ($lastpush_hash ne $hash) {
978 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
982 dryrun_report @upd_cmd;
990 canonicalise_suite();
991 badusage "dry run makes no sense with clone" if $dryrun;
992 mkdir $dstdir or die "$dstdir $!";
993 chdir "$dstdir" or die "$dstdir $!";
994 runcmd @git, qw(init -q);
995 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
996 open H, "> .git/HEAD" or die $!;
997 print H "ref: ".lref()."\n" or die $!;
999 runcmd @git, qw(remote add), 'origin', access_giturl();
1000 if (check_for_git()) {
1001 progress "fetching existing git history";
1003 runcmd_ordryrun @git, qw(fetch origin);
1005 progress "starting new git history";
1007 fetch_from_archive() or no_such_package;
1008 runcmd @git, qw(reset --hard), lrref();
1009 printdone "ready for work in $dstdir";
1013 if (check_for_git()) {
1016 fetch_from_archive() or no_such_package();
1017 printdone "fetched into ".lrref();
1022 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
1024 printdone "fetched to ".lrref()." and merged into HEAD";
1027 sub check_not_dirty () {
1028 return if $ignoredirty;
1029 my @cmd = (@git, qw(diff --quiet HEAD));
1030 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1031 $!=0; $?=0; system @cmd;
1032 return if !$! && !$?;
1033 if (!$! && $?==256) {
1034 fail "working tree is dirty (does not match HEAD)";
1040 sub commit_quilty_patch () {
1041 my $output = cmdoutput @git, qw(status --porcelain);
1044 foreach my $l (split /\n/, $output) {
1045 next unless $l =~ m/\S/;
1046 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1049 print STDERR "git status: $l\n";
1053 fail "unexpected output from git status (is tree clean?)" if $bad;
1055 progress "nothing quilty to commit, ok.";
1058 runcmd_ordryrun @git, qw(add), sort keys %adds;
1059 my $m = "Commit Debian 3.0 (quilt) metadata";
1061 runcmd_ordryrun @git, qw(commit -m), $m;
1066 return 0 unless $format eq '3.0 (quilt)';
1067 progress "Format \`$format', urgh";
1069 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1075 sub push_parse_changelog ($) {
1078 my $clogp = Dpkg::Control::Hash->new();
1079 $clogp->load($clogpfn);
1081 $package = getfield $clogp, 'Source';
1082 my $cversion = getfield $clogp, 'Version';
1083 my $tag = debiantag($cversion);
1084 runcmd @git, qw(check-ref-format), $tag;
1086 my $dscfn = dscfn($cversion);
1088 return ($clogp, $cversion, $tag, $dscfn);
1091 sub push_parse_dsc ($$$) {
1092 my ($dscfn,$dscfnwhat, $cversion) = @_;
1093 $dsc = parsecontrol($dscfn,$dscfnwhat);
1094 my $dversion = getfield $dsc, 'Version';
1095 my $dscpackage = getfield $dsc, 'Source';
1096 ($dscpackage eq $package && $dversion eq $cversion) or
1097 fail "$dsc is for $dscpackage $dversion".
1098 " but debian/changelog is for $package $cversion";
1101 sub push_mktag ($$$$$$$$) {
1102 my ($head,$clogp,$tag,
1104 $changesfile,$changesfilewhat,
1107 $dsc->{$ourdscfield[0]} = $head;
1108 $dsc->save("$dscfn.tmp") or die $!;
1110 my $changes = parsecontrol($changesfile,$changesfilewhat);
1111 foreach my $field (qw(Source Distribution Version)) {
1112 $changes->{$field} eq $clogp->{$field} or
1113 fail "changes field $field \`$changes->{$field}'".
1114 " does not match changelog \`$clogp->{$field}'";
1117 my $cversion = getfield $clogp, 'Version';
1119 # We make the git tag by hand because (a) that makes it easier
1120 # to control the "tagger" (b) we can do remote signing
1121 my $authline = clogp_authline $clogp;
1122 open TO, '>', $tfn->('.tmp') or die $!;
1123 print TO <<END or die $!;
1129 $package release $cversion for $csuite [dgit]
1133 my $tagobjfn = $tfn->('.tmp');
1135 if (!defined $keyid) {
1136 $keyid = access_cfg('keyid','RETURN-UNDEF');
1138 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1139 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1140 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1141 push @sign_cmd, $tfn->('.tmp');
1142 runcmd_ordryrun @sign_cmd;
1144 $tagobjfn = $tfn->('.signed.tmp');
1145 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1146 $tfn->('.tmp'), $tfn->('.tmp.asc');
1153 sub sign_changes ($) {
1154 my ($changesfile) = @_;
1156 my @debsign_cmd = @debsign;
1157 push @debsign_cmd, "-k$keyid" if defined $keyid;
1158 push @debsign_cmd, "-p$gpg[0]" if $gpg[0] ne 'gpg';
1159 push @debsign_cmd, $changesfile;
1160 runcmd_ordryrun @debsign_cmd;
1165 print DEBUG "actually entering push\n";
1168 my $clogpfn = ".git/dgit/changelog.822.tmp";
1169 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1171 responder_send_file('parsed-changelog', $clogpfn);
1173 my ($clogp, $cversion, $tag, $dscfn) =
1174 push_parse_changelog("$clogpfn");
1177 fail "looked for .dsc $dscfn, but $!;".
1178 " maybe you forgot to build";
1180 responder_send_file('dsc', "../$dscfn");
1182 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1184 my $format = getfield $dsc, 'Format';
1185 print DEBUG "format $format\n";
1186 if (madformat($format)) {
1187 commit_quilty_patch();
1190 chdir $ud or die $!;
1191 progress "checking that $dscfn corresponds to HEAD";
1192 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1193 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1194 chdir '../../../..' or die $!;
1195 printcmd \*DEBUG,"+",@_;
1196 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1198 if (system @diffcmd) {
1199 if ($! && $?==256) {
1200 fail "$dscfn specifies a different tree to your HEAD commit;".
1201 " perhaps you forgot to build";
1207 #do fast forward check and maybe fake merge
1208 # if (!is_fast_fwd(mainbranch
1209 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1210 # map { lref($_).":".rref($_) }
1212 my $head = rev_parse('HEAD');
1213 if (!$changesfile) {
1214 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1215 if (stat "$multi") {
1216 $changesfile = $multi;
1218 $!==&ENOENT or die "$multi: $!";
1219 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1220 my @cs = glob "../$pat";
1221 fail "failed to find unique changes file".
1222 " (looked for $pat in .., or $multi);".
1223 " perhaps you need to use dgit -C"
1225 ($changesfile) = @cs;
1229 responder_send_file('changes',$changesfile);
1231 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1234 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1235 : push_mktag($head,$clogp,$tag,
1237 $changesfile,$changesfile,
1240 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1241 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1242 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1243 runcmd_ordryrun @git, qw(tag -v --), $tag;
1245 if (!check_for_git()) {
1246 create_remote_git_repo();
1248 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1249 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1251 if (!$we_are_responder) {
1253 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1255 progress "[new .dsc left in $dscfn.tmp]";
1259 if ($we_are_responder) {
1260 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1261 responder_receive_files('signed-dsc-changes',
1262 "../$dscfn$dryrunsuffix",
1263 "$changesfile$dryrunsuffix");
1265 sign_changes $changesfile;
1268 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1269 my $host = access_cfg('upload-host','RETURN-UNDEF');
1270 my @hostarg = defined($host) ? ($host,) : ();
1271 runcmd_ordryrun @dput, @hostarg, $changesfile;
1272 printdone "pushed and uploaded $cversion";
1274 responder_send_command("complete");
1280 badusage "-p is not allowed with clone; specify as argument instead"
1281 if defined $package;
1284 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1285 ($package,$isuite) = @ARGV;
1286 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1287 ($package,$dstdir) = @ARGV;
1288 } elsif (@ARGV==3) {
1289 ($package,$isuite,$dstdir) = @ARGV;
1291 badusage "incorrect arguments to dgit clone";
1293 $dstdir ||= "$package";
1297 sub branchsuite () {
1298 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1299 if ($branch =~ m#$lbranch_re#o) {
1306 sub fetchpullargs () {
1307 if (!defined $package) {
1308 my $sourcep = parsecontrol('debian/control','debian/control');
1309 $package = getfield $sourcep, 'Source';
1312 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1314 my $clogp = parsechangelog();
1315 $isuite = getfield $clogp, 'Distribution';
1317 canonicalise_suite();
1318 progress "fetching from suite $csuite";
1319 } elsif (@ARGV==1) {
1321 canonicalise_suite();
1323 badusage "incorrect arguments to dgit fetch or dgit pull";
1341 badusage "-p is not allowed with dgit push" if defined $package;
1343 my $clogp = parsechangelog();
1344 $package = getfield $clogp, 'Source';
1347 } elsif (@ARGV==1) {
1348 ($specsuite) = (@ARGV);
1350 badusage "incorrect arguments to dgit push";
1352 $isuite = getfield $clogp, 'Distribution';
1354 local ($package) = $existing_package; # this is a hack
1355 canonicalise_suite();
1357 if (defined $specsuite && $specsuite ne $isuite) {
1358 canonicalise_suite();
1359 $csuite eq $specsuite or
1360 fail "dgit push: changelog specifies $isuite ($csuite)".
1361 " but command line specifies $specsuite";
1363 if (check_for_git()) {
1366 if (fetch_from_archive()) {
1367 is_fast_fwd(lrref(), 'HEAD') or
1368 fail "dgit push: HEAD is not a descendant".
1369 " of the archive's version.\n".
1370 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1373 fail "package appears to be new in this suite;".
1374 " if this is intentional, use --new";
1379 #---------- remote commands' implementation ----------
1381 sub cmd_remote_push_responder {
1382 my ($nrargs) = shift @ARGV;
1383 my (@rargs) = @ARGV[0..$nrargs-1];
1384 @ARGV = @ARGV[$nrargs..$#ARGV];
1387 chdir $dir or die "$dir: $!";
1388 $we_are_responder = 1;
1390 responder_send_command("dgit-remote-push-ready");
1398 return unless defined $i_tmp;
1399 chdir "/" or die $!;
1400 eval { rmtree $i_tmp; };
1404 my ($base,$selector,@args) = @_;
1405 $selector =~ s/\-/_/g;
1406 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1412 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1422 push @rdgit, @ropts;
1423 push @rdgit, (scalar @rargs), @rargs;
1425 my @cmd = (@ssh, $host, shellquote @rdgit);
1426 my $pid = open2(\*RO, \*RI, @cmd);
1429 chdir $i_tmp or die "$i_tmp $!";
1430 initiator_expect { m/^dgit-remote-push-ready/ };
1432 initiator_expect { m/^(\S+)(?: (.*))?$/ };
1433 my ($icmd,$iargs) = ($1, $2);
1434 i_method "i_resp_", $icmd, $iargs;
1441 sub i_resp_progress ($) {
1443 my $msg = protocol_read_bytes \*RO, $rhs;
1447 sub i_resp_complete {
1452 sub i_resp_file ($) {
1454 my $localname = i_method "i_localname_", $keyword;
1455 my $localpath = "$i_tmp/$localname";
1456 stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1457 protocol_receive_file \*RO, $localpath;
1463 $_[0] =~ m/^(\S+) (.*)$/;
1469 sub i_resp_want ($) {
1471 die "$keyword ?" if $i_wanted{$keyword}++;
1472 my @localpaths = i_method "i_want_", $keyword;
1473 foreach my $localpath (@localpaths) {
1474 protocol_send_file \*RI, $localpath;
1476 print RI "end-files\n" or die $!;
1479 our ($i_clogp, $i_version, $i_tag, $i_dscfn);
1481 sub i_localname_parsed_changelog { return "remote-changelog.822"; }
1482 sub i_localname_changes { return "remote.changes"; }
1483 sub i_localname_dsc {
1484 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1485 push_parse_changelog 'remote-changelog.822';
1486 die if $i_dscfn =~ m#/|^\W#;
1490 sub i_want_signed_tag {
1491 defined $i_param{'head'} && defined $i_dscfn
1492 or badproto \*RO, "sequencing error";
1493 my $head = $i_param{'head'};
1494 die if $head =~ m/[^0-9a-f]/ || $head !~ m/^../;
1496 push_parse_dsc $i_dscfn, 'remote dsc',
1498 push_mktag $head, $i_clogp, $i_tag,
1500 'remote.changes', 'remote changes',
1506 sub i_want_signed_dsc_changes {
1507 rename "$i_dscfn.tmp","$i_dscfn" or die "$i_dscfn $!";
1508 sign_changes 'remote.changes';
1509 return ($i_dscfn, 'remote.changes');
1512 #---------- building etc. ----------
1518 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1520 sub build_maybe_quilt_fixup () {
1521 if (!open F, "debian/source/format") {
1522 die $! unless $!==&ENOENT;
1526 F->error and die $!;
1528 return unless madformat($_);
1530 my $clogp = parsechangelog();
1531 my $version = getfield $clogp, 'Version';
1532 my $author = getfield $clogp, 'Maintainer';
1533 my $headref = rev_parse('HEAD');
1536 my $patchname = "auto-$version-$headref-$time";
1537 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1539 my $descfn = ".git/dgit/quilt-description.tmp";
1540 open O, '>', $descfn or die "$descfn: $!";
1542 $msg =~ s/^\s+$/ ./mg;
1543 print O <<END or die $!;
1544 Description: Automatically generated patch ($clogp->{Version})
1545 Last (up to) $ncommits git changes, FYI:
1555 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1556 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1557 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1558 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1561 if (!open P, '>>', ".pc/applied-patches") {
1562 $!==&ENOENT or die $!;
1567 commit_quilty_patch();
1570 sub quilt_fixup_editor () {
1571 my $descfn = $ENV{$fakeeditorenv};
1572 my $editing = $ARGV[$#ARGV];
1573 open I1, '<', $descfn or die "$descfn: $!";
1574 open I2, '<', $editing or die "$editing: $!";
1575 unlink $editing or die "$editing: $!";
1576 open O, '>', $editing or die "$editing: $!";
1577 while (<I1>) { print O or die $!; } I1->error and die $!;
1580 $copying ||= m/^\-\-\- /;
1581 next unless $copying;
1584 I2->error and die $!;
1590 badusage "-p is not allowed when building" if defined $package;
1592 my $clogp = parsechangelog();
1593 $isuite = getfield $clogp, 'Distribution';
1594 $package = getfield $clogp, 'Source';
1595 $version = getfield $clogp, 'Version';
1596 build_maybe_quilt_fixup();
1600 badusage "dgit build implies --clean=dpkg-source"
1601 if $cleanmode ne 'dpkg-source';
1603 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1604 printdone "build successful\n";
1608 badusage "dgit git-build implies --clean=dpkg-source"
1609 if $cleanmode ne 'dpkg-source';
1612 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1613 "--git-builder=@dpkgbuildpackage");
1614 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1615 canonicalise_suite();
1616 push @cmd, "--git-debian-branch=".lbranch();
1618 push @cmd, changesopts();
1619 runcmd_ordryrun @cmd, @ARGV;
1620 printdone "build successful\n";
1625 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1626 $dscfn = dscfn($version);
1627 if ($cleanmode eq 'dpkg-source') {
1628 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1630 if ($cleanmode eq 'git') {
1631 runcmd_ordryrun @git, qw(clean -xdf);
1632 } elsif ($cleanmode eq 'none') {
1636 my $pwd = cmdoutput qw(env - pwd);
1637 my $leafdir = basename $pwd;
1638 chdir ".." or die $!;
1639 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1640 chdir $pwd or die $!;
1641 runcmd_ordryrun qw(sh -ec),
1642 'exec >$1; shift; exec "$@"','x',
1643 "../$sourcechanges",
1644 @dpkggenchanges, qw(-S), changesopts();
1648 sub cmd_build_source {
1649 badusage "build-source takes no additional arguments" if @ARGV;
1651 printdone "source built, results in $dscfn and $sourcechanges";
1656 chdir ".." or die $!;
1657 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1659 stat $dscfn or fail "$dscfn (in parent directory): $!";
1660 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1661 foreach my $cf (glob $pat) {
1662 next if $cf eq $sourcechanges;
1663 unlink $cf or fail "remove $cf: $!";
1666 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1667 runcmd_ordryrun @mergechanges, glob $pat;
1668 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1670 stat $multichanges or fail "$multichanges: $!";
1672 printdone "build successful, results in $multichanges\n" or die $!;
1675 sub cmd_quilt_fixup {
1676 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1677 my $clogp = parsechangelog();
1678 $version = getfield $clogp, 'Version';
1679 build_maybe_quilt_fixup();
1682 #---------- argument parsing and main program ----------
1685 print "dgit version $our_version\n" or die $!;
1692 if (defined $ENV{'DGIT_SSH'}) {
1693 @ssh = string_to_ssh $ENV{'DGIT_SSH'};
1694 } elsif (defined $ENV{'GIT_SSH'}) {
1695 @ssh = ($ENV{'GIT_SSH'});
1699 last unless $ARGV[0] =~ m/^-/;
1703 if (m/^--dry-run$/) {
1706 } elsif (m/^--no-sign$/) {
1709 } elsif (m/^--help$/) {
1711 } elsif (m/^--version$/) {
1713 } elsif (m/^--new$/) {
1716 } elsif (m/^--(\w+)=(.*)/s &&
1717 ($om = $opts_opt_map{$1}) &&
1721 } elsif (m/^--(\w+):(.*)/s &&
1722 !$opts_opt_cmdonly{$1} &&
1723 ($om = $opts_opt_map{$1})) {
1726 } elsif (m/^--existing-package=(.*)/s) {
1728 $existing_package = $1;
1729 } elsif (m/^--distro=(.*)/s) {
1732 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1735 } elsif (m/^--clean=(.*)$/s) {
1736 badusage "unknown cleaning mode \`$1'";
1737 } elsif (m/^--ignore-dirty$/s) {
1740 } elsif (m/^--no-quilt-fixup$/s) {
1744 badusage "unknown long option \`$_'";
1751 } elsif (s/^-h/-/) {
1753 } elsif (s/^-D/-/) {
1755 open DEBUG, ">&STDERR" or die $!;
1757 } elsif (s/^-N/-/) {
1760 } elsif (m/^-[vm]/) {
1762 push @changesopts, $_;
1764 } elsif (s/^-c(.*=.*)//s) {
1766 push @git, '-c', $1;
1767 } elsif (s/^-d(.*)//s) {
1770 } elsif (s/^-C(.*)//s) {
1773 } elsif (s/^-k(.*)//s) {
1775 } elsif (s/^-wn//s) {
1777 $cleanmode = 'none';
1778 } elsif (s/^-wg//s) {
1781 } elsif (s/^-wd//s) {
1783 $cleanmode = 'dpkg-source';
1785 badusage "unknown short option \`$_'";
1792 if ($ENV{$fakeeditorenv}) {
1793 quilt_fixup_editor();
1796 delete $ENV{'DGET_UNPACK'};
1799 print STDERR "DRY RUN ONLY\n" if $dryrun;
1801 print STDERR $helpmsg or die $!;
1804 my $cmd = shift @ARGV;
1806 { no strict qw(refs); &{"cmd_$cmd"}(); }