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);
82 open DEBUG, ">/dev/null" or die $!;
84 our $remotename = 'dgit';
85 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
86 our $branchprefix = 'dgit';
89 sub lbranch () { return "$branchprefix/$csuite"; }
90 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
91 sub lref () { return "refs/heads/".lbranch(); }
92 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
93 sub rrref () { return "refs/$branchprefix/$csuite"; }
108 return "${package}_".(stripepoch $vsn).".dsc";
111 sub changesopts () { return @changesopts[1..$#changesopts]; }
115 sub fail { die "$us: @_\n"; }
117 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
119 sub no_such_package () {
120 print STDERR "$us: package $package does not exist in suite $isuite\n";
126 return "+".rrref().":".lrref();
129 #---------- remote protocol support, common ----------
131 # remote push initiator/responder protocol:
132 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
134 # > file begin parsed-changelog
135 # [indicates that output of dpkg-parsechangelog follows]
136 # > data-block NBYTES
137 # > [NBYTES bytes of data (no newline)]
138 # [maybe some more blocks]
144 # > file begin changes
150 # [indicates that signed tag is wanted]
151 # < data-block NBYTES
152 # < [NBYTES bytes of data (no newline)]
153 # [maybe some more blocks]
157 # > want signed-changes-dsc
158 # < data-block NBYTES [transfer of signed changes]
160 # < data-block NBYTES [transfer of signed dsc]
168 fail "connection lost: $!" if $fh->error;
169 fail "connection terminated" if $fh->eof;
170 fail "protocol violation; $m not expected";
173 sub protocol_expect ($&) {
174 my ($fh, $match) = @_;
177 defined && chomp or badproto $fh, "eof";
179 badproto $fh, "\`$_'";
182 sub protocol_send_file ($$) {
183 my ($fh, $ourfn) = @_;
184 open PF, "<", $ourfn or die "$ourfn: $!";
187 my $got = read PF, $d, 65536;
188 die "$ourfn: $!" unless defined $got;
190 print $fh "data-block ".length($d)."\n" or die $!;
193 print $fh "data-end\n" or die $!;
197 sub protocol_read_bytes ($$) {
198 my ($fh, $nbytes) = @_;
199 $nbytes =~ m/^\d{1,6}$/ or badproto \*RO, "bad byte count";
201 my $got = read $fh, $d, $nbytes;
202 $got==$nbytes or badproto $fh, "eof during data block";
206 sub protocol_receive_file ($$) {
207 my ($fh, $ourfn) = @_;
208 open PF, ">", $ourfn or die "$ourfn: $!";
210 protocol_expect \*STDIN, { m/^data-block (.*})$|data-end$/ };
212 my $d = protocol_read_bytes \*STDIN, $1;
213 print PF $d or die $!;
217 #---------- remote protocol support, responder ----------
219 sub responder_send_command ($) {
221 return unless $we_are_responder;
222 # called even without $we_are_responder
223 print DEBUG "<< $command\n";
224 print $command, "\n" or die $!;
227 sub responder_send_file ($$) {
228 my ($keyword, $ourfn) = @_;
229 return unless $we_are_responder;
230 responder_send_command "file-begin $keyword";
231 protocol_send_file \*STDOUT, $ourfn;
234 sub responder_receive_files ($@) {
235 my ($keyword, @ourfns) = @_;
236 die unless $we_are_responder;
237 responder_send_command "want $keyword";
238 foreach my $fn (@ourfns) {
239 protocol_receive_file \*STDIN, $fn;
241 protocol_expect \*STDIN, { m/^files-end$/ };
244 #---------- remote protocol support, initiator ----------
246 sub initiator_expect (&) {
248 protocol_expect \*RO, &$match;
251 #---------- end remote code ----------
254 if ($we_are_responder) {
256 responder_send_command "progress ".length($m) or die $!;
267 $ua = LWP::UserAgent->new();
271 progress "downloading $what...";
272 my $r = $ua->get(@_) or die $!;
273 return undef if $r->code == 404;
274 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
275 return $r->decoded_content();
278 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
285 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
291 return join '', @out;
296 my $intro = shift @_;
297 print $fh $intro or die $!;
298 print $fh shellquote @_ or die $!;
299 print $fh "\n" or die $!;
303 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
305 fail "failed to fork/exec: $!";
306 } elsif (!($? & 0xff)) {
307 fail "subprocess failed with error exit status ".($?>>8);
309 fail "subprocess crashed (wait status $?)";
311 fail "subprocess produced invalid output";
316 printcmd(\*DEBUG,"+",@_) if $debug>0;
318 failedcmd @_ if system @_;
323 progress "dgit ok: @_";
325 progress "would be ok: @_ (but dry run only)";
329 sub cmdoutput_errok {
330 die Dumper(\@_)." ?" if grep { !defined } @_;
331 printcmd(\*DEBUG,"|",@_) if $debug>0;
332 open P, "-|", @_ or die $!;
335 { local $/ = undef; $d = <P>; }
337 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
340 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
345 my $d = cmdoutput_errok @_;
346 defined $d or failedcmd @_;
351 printcmd(\*STDERR,"#",@_);
354 sub runcmd_ordryrun {
363 my ($first_shell, @cmd) = @_;
364 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
367 our $helpmsg = <<END;
369 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
370 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
371 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
372 dgit [dgit-opts] push [dgit-opts] [suite]
373 important dgit options:
374 -k<keyid> sign tag and package with <keyid> instead of default
375 --dry-run -n do not change anything, but go through the motions
376 --new -N allow introducing a new package
377 --debug -D increase debug level
378 -c<name>=<value> set git config option (used directly by dgit too)
381 our $later_warning_msg = <<END;
382 Perhaps the upload is stuck in incoming. Using the version from git.
386 print STDERR "$us: @_\n", $helpmsg or die $!;
391 @ARGV or badusage "too few arguments";
392 return scalar shift @ARGV;
396 print $helpmsg or die $!;
400 our %defcfg = ('dgit.default.distro' => 'debian',
401 'dgit.default.username' => '',
402 'dgit.default.archive-query-default-component' => 'main',
403 'dgit.default.ssh' => 'ssh',
404 'dgit-distro.debian.git-host' => 'git.debian.org',
405 'dgit-distro.debian.git-proto' => 'git+ssh://',
406 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
407 'dgit-distro.debian.git-check' => 'ssh-cmd',
408 'dgit-distro.debian.git-create' => 'ssh-cmd',
409 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
410 'dgit-distro.debian.sshdakls-dir' =>
411 '/srv/ftp-master.debian.org/ftp/dists',
412 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
413 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
417 return undef if $c =~ /RETURN-UNDEF/;
418 my @cmd = (@git, qw(config --), $c);
421 local ($debug) = $debug-1;
422 $v = cmdoutput_errok @cmd;
429 my $dv = $defcfg{$c};
430 return $dv if defined $dv;
432 badcfg "need value for one of: @_";
435 sub access_distro () {
436 return cfg("dgit-suite.$isuite.distro",
437 "dgit.default.distro");
442 my $distro = $idistro || access_distro();
443 my $value = cfg(map { ("dgit-distro.$distro.$_",
444 "dgit.default.$_") } @keys);
448 sub access_someuserhost ($) {
450 my $user = access_cfg("$some-user",'username');
451 my $host = access_cfg("$some-host");
452 return length($user) ? "$user\@$host" : $host;
455 sub access_gituserhost () {
456 return access_someuserhost('git');
459 sub access_giturl () {
460 my $url = access_cfg('git-url','RETURN-UNDEF');
463 access_cfg('git-proto').
464 access_gituserhost().
465 access_cfg('git-path');
467 return "$url/$package.git";
470 sub parsecontrolfh ($$@) {
471 my ($fh, $desc, @opts) = @_;
472 my %opts = ('name' => $desc, @opts);
473 my $c = Dpkg::Control::Hash->new(%opts);
474 $c->parse($fh) or die "parsing of $desc failed";
479 my ($file, $desc) = @_;
480 my $fh = new IO::Handle;
481 open $fh, '<', $file or die "$file: $!";
482 my $c = parsecontrolfh($fh,$desc);
483 $fh->error and die $!;
489 my ($dctrl,$field) = @_;
490 my $v = $dctrl->{$field};
491 return $v if defined $v;
492 fail "missing field $field in ".$v->get_option('name');
496 my $c = Dpkg::Control::Hash->new();
497 my $p = new IO::Handle;
498 my @cmd = (qw(dpkg-parsechangelog), @_);
499 open $p, '-|', @cmd or die $!;
501 $?=0; $!=0; close $p or failedcmd @cmd;
507 sub archive_query ($) {
509 my $query = access_cfg('archive-query','RETURN-UNDEF');
510 if (!defined $query) {
511 my $distro = access_distro();
512 if ($distro eq 'debian') {
513 $query = "sshdakls:".
514 access_someuserhost('sshdakls').':'.
515 access_cfg('sshdakls-dir');
517 $query = "madison:$distro";
520 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
523 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
526 sub archive_query_madison ($$) {
527 my ($proto,$data) = @_;
528 die unless $proto eq 'madison';
529 $rmad{$package} ||= cmdoutput
530 qw(rmadison -asource),"-s$isuite","-u$data",$package;
531 my $rmad = $rmad{$package};
532 return madison_parse($rmad);
535 sub archive_query_sshdakls ($$) {
536 my ($proto,$data) = @_;
537 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
538 my $dakls = cmdoutput
539 access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
540 return madison_parse($dakls);
543 sub canonicalise_suite_sshdakls ($$) {
544 my ($proto,$data) = @_;
545 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
547 (access_cfg('ssh'), $`,
549 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
550 " if test -d $isuite; then echo $isuite; exit 0; fi;".
552 my $dakls = cmdoutput @cmd;
553 failedcmd @cmd unless $dakls =~ m/^\w/;
557 sub madison_parse ($) {
560 foreach my $l (split /\n/, $rmad) {
561 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
562 \s*( [^ \t|]+ )\s* \|
563 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
564 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
565 $1 eq $package or die "$rmad $package ?";
572 $component = access_cfg('archive-query-default-component');
574 $5 eq 'source' or die "$rmad ?";
575 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
576 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
577 push @out, [$vsn,$subpath,$newsuite];
579 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
582 sub canonicalise_suite_madison ($$) {
583 my @r = archive_query_madison($_[0],$_[1]);
585 "unable to canonicalise suite using package $package".
586 " which does not appear to exist in suite $isuite;".
587 " --existing-package may help";
591 sub canonicalise_suite () {
592 return if defined $csuite;
593 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
594 $csuite = archive_query('canonicalise_suite');
595 if ($isuite ne $csuite) {
596 # madison canonicalises for us
597 progress "canonical suite name for $isuite is $csuite";
601 sub get_archive_dsc () {
602 canonicalise_suite();
603 my @vsns = archive_query('archive_query');
604 foreach my $vinfo (@vsns) {
605 my ($vsn,$subpath) = @$vinfo;
606 $dscurl = access_cfg('mirror').$subpath;
607 $dscdata = url_get($dscurl);
609 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
612 my $dscfh = new IO::File \$dscdata, '<' or die $!;
613 print DEBUG Dumper($dscdata) if $debug>1;
614 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
615 print DEBUG Dumper($dsc) if $debug>1;
616 my $fmt = getfield $dsc, 'Format';
617 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
623 sub check_for_git () {
625 my $how = access_cfg('git-check');
626 if ($how eq 'ssh-cmd') {
628 (access_cfg('ssh'),access_gituserhost(),
629 " set -e; cd ".access_cfg('git-path').";".
630 " if test -d $package.git; then echo 1; else echo 0; fi");
631 my $r= cmdoutput @cmd;
632 failedcmd @cmd unless $r =~ m/^[01]$/;
635 badcfg "unknown git-check \`$how'";
639 sub create_remote_git_repo () {
640 my $how = access_cfg('git-create');
641 if ($how eq 'ssh-cmd') {
643 (access_cfg('ssh'),access_gituserhost(),
644 "set -e; cd ".access_cfg('git-path').";".
645 " cp -a _template $package.git");
647 badcfg "unknown git-create \`$how'";
651 our ($dsc_hash,$lastpush_hash);
653 our $ud = '.git/dgit/unpack';
661 sub mktree_in_ud_from_only_subdir () {
662 # changes into the subdir
665 $dirs[0] =~ m#^([^/]+)/\.$# or die;
667 chdir $dir or die "$dir $!";
668 fail "source package contains .git directory" if stat '.git';
669 die $! unless $!==&ENOENT;
670 runcmd qw(git init -q);
671 rmtree('.git/objects');
672 symlink '../../../../objects','.git/objects' or die $!;
673 runcmd @git, qw(add -Af);
674 my $tree = cmdoutput @git, qw(write-tree);
675 $tree =~ m/^\w+$/ or die "$tree ?";
679 sub dsc_files_info () {
680 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
681 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
682 ['Files', 'Digest::MD5', 'new()']) {
683 my ($fname, $module, $method) = @$csumi;
684 my $field = $dsc->{$fname};
685 next unless defined $field;
686 eval "use $module; 1;" or die $@;
688 foreach (split /\n/, $field) {
690 m/^(\w+) (\d+) (\S+)$/ or
691 fail "could not parse .dsc $fname line \`$_'";
692 my $digester = eval "$module"."->$method;" or die $@;
697 Digester => $digester,
702 fail "missing any supported Checksums-* or Files field in ".
703 $dsc->get_option('name');
707 map { $_->{Filename} } dsc_files_info();
710 sub is_orig_file ($) {
712 m/\.orig(?:-\w+)?\.tar\.\w+$/;
715 sub make_commit ($) {
717 return cmdoutput @git, qw(hash-object -w -t commit), $file;
720 sub clogp_authline ($) {
722 my $author = getfield $clogp, 'Maintainer';
723 $author =~ s#,.*##ms;
724 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
725 my $authline = "$author $date";
726 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
727 fail "unexpected commit author line format \`$authline'".
728 " (was generated from changelog Maintainer field)";
732 sub generate_commit_from_dsc () {
736 foreach my $f (dsc_files()) {
737 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
739 link "../../../$f", $f
743 runcmd @dget, qw(--), $dscurl;
744 foreach my $f (grep { is_orig_file($_) } @files) {
745 link $f, "../../../../$f"
749 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
750 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
751 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
752 my $authline = clogp_authline $clogp;
753 my $changes = getfield $clogp, 'Changes';
754 open C, ">../commit.tmp" or die $!;
755 print C <<END or die $!;
762 # imported from the archive
765 my $outputhash = make_commit qw(../commit.tmp);
766 my $cversion = getfield $clogp, 'Version';
767 progress "synthesised git commit from .dsc $cversion";
768 if ($lastpush_hash) {
769 runcmd @git, qw(reset --hard), $lastpush_hash;
770 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
771 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
772 my $oversion = getfield $oldclogp, 'Version';
774 version_compare_string($oversion, $cversion);
776 # git upload/ is earlier vsn than archive, use archive
777 open C, ">../commit2.tmp" or die $!;
778 print C <<END or die $!;
780 parent $lastpush_hash
785 Record $package ($cversion) in archive suite $csuite
787 $outputhash = make_commit qw(../commit2.tmp);
788 } elsif ($vcmp > 0) {
789 print STDERR <<END or die $!;
791 Version actually in archive: $cversion (older)
792 Last allegedly pushed/uploaded: $oversion (newer or same)
795 $outputhash = $lastpush_hash;
797 $outputhash = $lastpush_hash;
800 chdir '../../../..' or die $!;
801 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
802 'DGIT_ARCHIVE', $outputhash;
803 cmdoutput @git, qw(log -n2), $outputhash;
804 # ... gives git a chance to complain if our commit is malformed
809 sub ensure_we_have_orig () {
810 foreach my $fi (dsc_files_info()) {
811 my $f = $fi->{Filename};
812 next unless is_orig_file($f);
813 if (open F, "<", "../$f") {
814 $fi->{Digester}->reset();
815 $fi->{Digester}->addfile(*F);
817 my $got = $fi->{Digester}->hexdigest();
818 $got eq $fi->{Hash} or
819 fail "existing file $f has hash $got but .dsc".
820 " demands hash $fi->{Hash}".
821 " (perhaps you should delete this file?)";
822 progress "using existing $f";
825 die "$f $!" unless $!==&ENOENT;
827 my $origurl = $dscurl;
828 $origurl =~ s{/[^/]+$}{};
830 die "$f ?" unless $f =~ m/^${package}_/;
831 die "$f ?" if $f =~ m#/#;
832 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
837 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
840 sub is_fast_fwd ($$) {
841 my ($ancestor,$child) = @_;
842 my @cmd = (@git, qw(merge-base), $ancestor, $child);
843 my $mb = cmdoutput_errok @cmd;
845 return rev_parse($mb) eq rev_parse($ancestor);
847 $?==256 or failedcmd @cmd;
852 sub git_fetch_us () {
853 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
856 sub fetch_from_archive () {
857 # ensures that lrref() is what is actually in the archive,
862 foreach my $field (@ourdscfield) {
863 $dsc_hash = $dsc->{$field};
864 last if defined $dsc_hash;
866 if (defined $dsc_hash) {
867 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
869 progress "last upload to archive specified git hash";
871 progress "last upload to archive has NO git hash";
874 progress "no version available from the archive";
877 my $lrref_fn = ".git/".lrref();
878 if (open H, $lrref_fn) {
879 $lastpush_hash = <H>;
880 chomp $lastpush_hash;
881 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
882 } elsif ($! == &ENOENT) {
887 print DEBUG "previous reference hash=$lastpush_hash\n";
889 if (defined $dsc_hash) {
890 fail "missing git history even though dsc has hash -".
891 " could not find commit $dsc_hash".
892 " (should be in ".access_giturl()."#".rrref().")"
893 unless $lastpush_hash;
895 ensure_we_have_orig();
896 if ($dsc_hash eq $lastpush_hash) {
897 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
898 print STDERR <<END or die $!;
900 Git commit in archive is behind the last version allegedly pushed/uploaded.
901 Commit referred to by archive: $dsc_hash
902 Last allegedly pushed/uploaded: $lastpush_hash
905 $hash = $lastpush_hash;
907 fail "archive's .dsc refers to ".$dsc_hash.
908 " but this is an ancestor of ".$lastpush_hash;
911 $hash = generate_commit_from_dsc();
912 } elsif ($lastpush_hash) {
913 # only in git, not in the archive yet
914 $hash = $lastpush_hash;
915 print STDERR <<END or die $!;
917 Package not found in the archive, but has allegedly been pushed using dgit.
921 print DEBUG "nothing found!\n";
922 if (defined $skew_warning_vsn) {
923 print STDERR <<END or die $!;
925 Warning: relevant archive skew detected.
926 Archive allegedly contains $skew_warning_vsn
927 But we were not able to obtain any version from the archive or git.
933 print DEBUG "current hash=$hash\n";
934 if ($lastpush_hash) {
935 fail "not fast forward on last upload branch!".
936 " (archive's version left in DGIT_ARCHIVE)"
937 unless is_fast_fwd($lastpush_hash, $hash);
939 if (defined $skew_warning_vsn) {
941 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
942 my $clogf = ".git/dgit/changelog.tmp";
943 runcmd shell_cmd "exec >$clogf",
944 @git, qw(cat-file blob), "$hash:debian/changelog";
945 my $gotclogp = parsechangelog("-l$clogf");
946 my $got_vsn = getfield $gotclogp, 'Version';
947 print DEBUG "SKEW CHECK GOT $got_vsn\n";
948 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
949 print STDERR <<END or die $!;
951 Warning: archive skew detected. Using the available version:
952 Archive allegedly contains $skew_warning_vsn
953 We were able to obtain only $got_vsn
958 if ($lastpush_hash ne $hash) {
959 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
963 dryrun_report @upd_cmd;
971 canonicalise_suite();
972 badusage "dry run makes no sense with clone" if $dryrun;
973 mkdir $dstdir or die "$dstdir $!";
974 chdir "$dstdir" or die "$dstdir $!";
975 runcmd @git, qw(init -q);
976 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
977 open H, "> .git/HEAD" or die $!;
978 print H "ref: ".lref()."\n" or die $!;
980 runcmd @git, qw(remote add), 'origin', access_giturl();
981 if (check_for_git()) {
982 progress "fetching existing git history";
984 runcmd_ordryrun @git, qw(fetch origin);
986 progress "starting new git history";
988 fetch_from_archive() or no_such_package;
989 runcmd @git, qw(reset --hard), lrref();
990 printdone "ready for work in $dstdir";
994 if (check_for_git()) {
997 fetch_from_archive() or no_such_package();
998 printdone "fetched into ".lrref();
1003 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
1005 printdone "fetched to ".lrref()." and merged into HEAD";
1008 sub check_not_dirty () {
1009 return if $ignoredirty;
1010 my @cmd = (@git, qw(diff --quiet HEAD));
1011 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1012 $!=0; $?=0; system @cmd;
1013 return if !$! && !$?;
1014 if (!$! && $?==256) {
1015 fail "working tree is dirty (does not match HEAD)";
1021 sub commit_quilty_patch () {
1022 my $output = cmdoutput @git, qw(status --porcelain);
1025 foreach my $l (split /\n/, $output) {
1026 next unless $l =~ m/\S/;
1027 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1030 print STDERR "git status: $l\n";
1034 fail "unexpected output from git status (is tree clean?)" if $bad;
1036 progress "nothing quilty to commit, ok.";
1039 runcmd_ordryrun @git, qw(add), sort keys %adds;
1040 my $m = "Commit Debian 3.0 (quilt) metadata";
1042 runcmd_ordryrun @git, qw(commit -m), $m;
1047 return 0 unless $format eq '3.0 (quilt)';
1048 progress "Format \`$format', urgh";
1050 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1056 sub push_parse_changelog ($) {
1059 my $clogp = Dpkg::Control::Hash->new();
1060 $clogp->load($clogpfn);
1062 $package = getfield $clogp, 'Source';
1063 my $cversion = getfield $clogp, 'Version';
1064 my $tag = debiantag($cversion);
1065 runcmd @git, qw(check-ref-format), $tag;
1067 my $dscfn = dscfn($cversion);
1069 return ($clogp, $cversion, $tag, $dscfn);
1072 sub push_parse_dsc ($$) {
1073 my ($dscfn,$dscfnwhat, $cversion) = @_;
1074 $dsc = parsecontrol($dscfn,$dscfnwhat);
1075 my $dversion = getfield $dsc, 'Version';
1076 my $dscpackage = getfield $dsc, 'Source';
1077 ($dscpackage eq $package && $dversion eq $cversion) or
1078 fail "$dsc is for $dscpackage $dversion".
1079 " but debian/changelog is for $package $cversion";
1082 sub push_mktag ($$$$$$$$) {
1083 my ($head,$clogp,$tag,
1085 $changesfile,$changesfilewhat,
1088 $dsc->{$ourdscfield[0]} = $head;
1089 $dsc->save("$dscfn.tmp") or die $!;
1091 my $changes = parsecontrol($changesfile,$changesfilewhat);
1092 foreach my $field (qw(Source Distribution Version)) {
1093 $changes->{$field} eq $clogp->{$field} or
1094 fail "changes field $field \`$changes->{$field}'".
1095 " does not match changelog \`$clogp->{$field}'";
1098 # We make the git tag by hand because (a) that makes it easier
1099 # to control the "tagger" (b) we can do remote signing
1100 my $authline = clogp_authline $clogp;
1101 open TO, '>', $tfn->('.tmp') or die $!;
1102 print TO <<END or die $!;
1108 $package release $cversion for $csuite [dgit]
1112 my $tagobjfn = $tfn->('.tmp');
1114 if (!defined $keyid) {
1115 $keyid = access_cfg('keyid','RETURN-UNDEF');
1117 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1118 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1119 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1120 push @sign_cmd, $tfn->('.tmp');
1121 runcmd_ordryrun @sign_cmd;
1123 $tagobjfn = $tfn->('.signed.tmp');
1124 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1125 $tfn->('.tmp'), $tfn->('.tmp.asc');
1132 sub sign_changes ($) {
1133 my ($changesfile) = @_;
1135 my @debsign_cmd = @debsign;
1136 push @debsign_cmd, "-k$keyid" if defined $keyid;
1137 push @debsign_cmd, $changesfile;
1138 runcmd_ordryrun @debsign_cmd;
1143 print DEBUG "actually entering push\n";
1146 my $clogpfn = ".git/dgit/changelog.822.tmp";
1147 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1149 responder_send_file('parsed-changelog', $clogpfn);
1151 my ($clogp, $cversion, $tag, $dscfn) =
1152 push_parse_changelog("$clogpfn");
1155 fail "looked for .dsc $dscfn, but $!;".
1156 " maybe you forgot to build";
1158 responder_send_file('dsc', "../$dscfn");
1160 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1162 my $format = getfield $dsc, 'Format';
1163 print DEBUG "format $format\n";
1164 if (madformat($format)) {
1165 commit_quilty_patch();
1168 chdir $ud or die $!;
1169 progress "checking that $dscfn corresponds to HEAD";
1170 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1171 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1172 chdir '../../../..' or die $!;
1173 printcmd \*DEBUG,"+",@_;
1174 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1176 if (system @diffcmd) {
1177 if ($! && $?==256) {
1178 fail "$dscfn specifies a different tree to your HEAD commit;".
1179 " perhaps you forgot to build";
1185 #do fast forward check and maybe fake merge
1186 # if (!is_fast_fwd(mainbranch
1187 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1188 # map { lref($_).":".rref($_) }
1190 my $head = rev_parse('HEAD');
1191 if (!$changesfile) {
1192 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1193 if (stat "$multi") {
1194 $changesfile = $multi;
1196 $!==&ENOENT or die "$multi: $!";
1197 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1198 my @cs = glob "../$pat";
1199 fail "failed to find unique changes file".
1200 " (looked for $pat in .., or $multi);".
1201 " perhaps you need to use dgit -C"
1203 ($changesfile) = @cs;
1207 responder_send_file('changes',$changesfn);
1209 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1212 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1213 : push_mktag($head,$clogp,$tag,
1215 $changesfile,$changesfile,
1218 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1219 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1220 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1221 runcmd_ordryrun @git, qw(tag -v --), $tag;
1223 if (!check_for_git()) {
1224 create_remote_git_repo();
1226 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1227 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1229 if (!$we_are_responder) {
1231 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1233 progress "[new .dsc left in $dscfn.tmp]";
1237 if ($we_are_responder) {
1238 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1239 responder_receive_files('signed-dsc-changes',
1240 "../$dscfn$dryrunsuffix",
1241 "$changesfile$dryrupnsuffix");
1243 sign_changes $changesfile;
1246 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1247 my $host = access_cfg('upload-host','RETURN-UNDEF');
1248 my @hostarg = defined($host) ? ($host,) : ();
1249 runcmd_ordryrun @dput, @hostarg, $changesfile;
1250 printdone "pushed and uploaded $cversion";
1252 responder_send_command("complete");
1258 badusage "-p is not allowed with clone; specify as argument instead"
1259 if defined $package;
1262 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1263 ($package,$isuite) = @ARGV;
1264 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1265 ($package,$dstdir) = @ARGV;
1266 } elsif (@ARGV==3) {
1267 ($package,$isuite,$dstdir) = @ARGV;
1269 badusage "incorrect arguments to dgit clone";
1271 $dstdir ||= "$package";
1275 sub branchsuite () {
1276 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1277 if ($branch =~ m#$lbranch_re#o) {
1284 sub fetchpullargs () {
1285 if (!defined $package) {
1286 my $sourcep = parsecontrol('debian/control','debian/control');
1287 $package = getfield $sourcep, 'Source';
1290 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1292 my $clogp = parsechangelog();
1293 $isuite = getfield $clogp, 'Distribution';
1295 canonicalise_suite();
1296 progress "fetching from suite $csuite";
1297 } elsif (@ARGV==1) {
1299 canonicalise_suite();
1301 badusage "incorrect arguments to dgit fetch or dgit pull";
1319 badusage "-p is not allowed with dgit push" if defined $package;
1321 my $clogp = parsechangelog();
1322 $package = getfield $clogp, 'Source';
1325 } elsif (@ARGV==1) {
1326 ($specsuite) = (@ARGV);
1328 badusage "incorrect arguments to dgit push";
1330 $isuite = getfield $clogp, 'Distribution';
1332 local ($package) = $existing_package; # this is a hack
1333 canonicalise_suite();
1335 if (defined $specsuite && $specsuite ne $isuite) {
1336 canonicalise_suite();
1337 $csuite eq $specsuite or
1338 fail "dgit push: changelog specifies $isuite ($csuite)".
1339 " but command line specifies $specsuite";
1341 if (check_for_git()) {
1344 if (fetch_from_archive()) {
1345 is_fast_fwd(lrref(), 'HEAD') or
1346 fail "dgit push: HEAD is not a descendant".
1347 " of the archive's version.\n".
1348 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1351 fail "package appears to be new in this suite;".
1352 " if this is intentional, use --new";
1357 #---------- remote commands' implementation ----------
1359 sub cmd_remote_push_responder {
1360 my ($nrargs) = shift @ARGV;
1361 my (@rargs) = @ARGV[0..$nrargs-1];
1362 @ARGV = @ARGV[$nrargs..$#ARGV];
1365 chdir $dir or die "$dir: $!";
1368 responder_send_command("dgit-remote-push-ready");
1376 return unless defined $i_tmp;
1377 chdir "/" or die $!;
1378 eval { rmtree $i_tmp; };
1382 my ($base,$selector,@args) = @_;
1383 $selector =~ s/\-/_/g;
1384 { no strict qw(refs); &{"${base}_${selector}"}(@args); }
1390 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1400 push @rdgit, @ropts;
1401 push @rdgit, (scalar @rargs), @rargs;
1403 my @cmd = (@ssh, $host, shellquote @rdgit);
1404 my $pid = open2(\*RO, \*RI, @cmd);
1407 chdir $i_tmp or die "$i_tmp $!";
1408 initiator_expect { m/^dgit-remote-push-ready/ };
1410 initiator_expect { m/^(\S+)(?: (.*))?$/ };
1411 my ($icmd,$iargs) = ($1, $2);
1412 i_method "i_resp_", $icmd, $iargs;
1419 sub i_resp_progress ($) {
1421 my $msg = protocol_read_bytes \*RO, $rhs;
1425 sub i_resp_complete {
1430 sub i_resp_file ($) {
1432 my $localname = i_method "i_localname_", $keyword;
1433 my $localpath = "$i_tmp/$localname";
1434 stat $localpath and badproto \*RO, "file $keyword ($localpath) twice";
1435 protocol_receive_file \*RO, $localpath;
1441 $_[0] =~ m/^(\S+) (.*)$/;
1447 sub i_resp_want ($) {
1449 my @localpaths = i_method "i_want_", $keyword;
1450 foreach my $localpath (@localpaths) {
1451 protocol_send_file \*RI, $localpath;
1453 print RI "end-files\n" or die $!;
1456 our ($i_clogp, $i_version, $i_tag, $i_dscfn);
1458 sub i_localname_parsed_changelog { return "remote-changelog.822"; }
1459 sub i_localname_changes { return "remote.changes"; }
1460 sub i_localname_dsc {
1461 ($i_clogp, $i_version, $i_tag, $i_dscfn) =
1462 push_parse_changelog 'remote-changelog.822';
1463 die if $i_dscfn =~ m#/|^\W#;
1467 #---------- building etc. ----------
1473 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1475 sub build_maybe_quilt_fixup () {
1476 if (!open F, "debian/source/format") {
1477 die $! unless $!==&ENOENT;
1481 F->error and die $!;
1483 return unless madformat($_);
1485 my $clogp = parsechangelog();
1486 my $version = getfield $clogp, 'Version';
1487 my $author = getfield $clogp, 'Maintainer';
1488 my $headref = rev_parse('HEAD');
1491 my $patchname = "auto-$version-$headref-$time";
1492 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1494 my $descfn = ".git/dgit/quilt-description.tmp";
1495 open O, '>', $descfn or die "$descfn: $!";
1497 $msg =~ s/^\s+$/ ./mg;
1498 print O <<END or die $!;
1499 Description: Automatically generated patch ($clogp->{Version})
1500 Last (up to) $ncommits git changes, FYI:
1510 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1511 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1512 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1513 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1516 if (!open P, '>>', ".pc/applied-patches") {
1517 $!==&ENOENT or die $!;
1522 commit_quilty_patch();
1525 sub quilt_fixup_editor () {
1526 my $descfn = $ENV{$fakeeditorenv};
1527 my $editing = $ARGV[$#ARGV];
1528 open I1, '<', $descfn or die "$descfn: $!";
1529 open I2, '<', $editing or die "$editing: $!";
1530 unlink $editing or die "$editing: $!";
1531 open O, '>', $editing or die "$editing: $!";
1532 while (<I1>) { print O or die $!; } I1->error and die $!;
1535 $copying ||= m/^\-\-\- /;
1536 next unless $copying;
1539 I2->error and die $!;
1545 badusage "-p is not allowed when building" if defined $package;
1547 my $clogp = parsechangelog();
1548 $isuite = getfield $clogp, 'Distribution';
1549 $package = getfield $clogp, 'Source';
1550 $version = getfield $clogp, 'Version';
1551 build_maybe_quilt_fixup();
1555 badusage "dgit build implies --clean=dpkg-source"
1556 if $cleanmode ne 'dpkg-source';
1558 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1559 printdone "build successful\n";
1563 badusage "dgit git-build implies --clean=dpkg-source"
1564 if $cleanmode ne 'dpkg-source';
1567 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1568 "--git-builder=@dpkgbuildpackage");
1569 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1570 canonicalise_suite();
1571 push @cmd, "--git-debian-branch=".lbranch();
1573 push @cmd, changesopts();
1574 runcmd_ordryrun @cmd, @ARGV;
1575 printdone "build successful\n";
1580 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1581 $dscfn = dscfn($version);
1582 if ($cleanmode eq 'dpkg-source') {
1583 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1585 if ($cleanmode eq 'git') {
1586 runcmd_ordryrun @git, qw(clean -xdf);
1587 } elsif ($cleanmode eq 'none') {
1591 my $pwd = cmdoutput qw(env - pwd);
1592 my $leafdir = basename $pwd;
1593 chdir ".." or die $!;
1594 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1595 chdir $pwd or die $!;
1596 runcmd_ordryrun qw(sh -ec),
1597 'exec >$1; shift; exec "$@"','x',
1598 "../$sourcechanges",
1599 @dpkggenchanges, qw(-S), changesopts();
1603 sub cmd_build_source {
1604 badusage "build-source takes no additional arguments" if @ARGV;
1606 printdone "source built, results in $dscfn and $sourcechanges";
1611 chdir ".." or die $!;
1612 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1614 stat $dscfn or fail "$dscfn (in parent directory): $!";
1615 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1616 foreach my $cf (glob $pat) {
1617 next if $cf eq $sourcechanges;
1618 unlink $cf or fail "remove $cf: $!";
1621 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1622 runcmd_ordryrun @mergechanges, glob $pat;
1623 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1625 stat $multichanges or fail "$multichanges: $!";
1627 printdone "build successful, results in $multichanges\n" or die $!;
1630 sub cmd_quilt_fixup {
1631 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1632 my $clogp = parsechangelog();
1633 $version = getfield $clogp, 'Version';
1634 build_maybe_quilt_fixup();
1637 #---------- argument parsing and main program ----------
1640 print "dgit version $our_version\n" or die $!;
1647 last unless $ARGV[0] =~ m/^-/;
1651 if (m/^--dry-run$/) {
1654 } elsif (m/^--no-sign$/) {
1657 } elsif (m/^--help$/) {
1659 } elsif (m/^--version$/) {
1661 } elsif (m/^--new$/) {
1664 } elsif (m/^--(\w+)=(.*)/s &&
1665 ($om = $opts_opt_map{$1}) &&
1669 } elsif (m/^--(\w+):(.*)/s &&
1670 ($om = $opts_opt_map{$1})) {
1673 } elsif (m/^--existing-package=(.*)/s) {
1675 $existing_package = $1;
1676 } elsif (m/^--distro=(.*)/s) {
1679 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1682 } elsif (m/^--clean=(.*)$/s) {
1683 badusage "unknown cleaning mode \`$1'";
1684 } elsif (m/^--ignore-dirty$/s) {
1687 } elsif (m/^--no-quilt-fixup$/s) {
1691 badusage "unknown long option \`$_'";
1698 } elsif (s/^-h/-/) {
1700 } elsif (s/^-D/-/) {
1702 open DEBUG, ">&STDERR" or die $!;
1704 } elsif (s/^-N/-/) {
1707 } elsif (m/^-[vm]/) {
1709 push @changesopts, $_;
1711 } elsif (s/^-c(.*=.*)//s) {
1713 push @git, '-c', $1;
1714 } elsif (s/^-d(.*)//s) {
1717 } elsif (s/^-C(.*)//s) {
1720 } elsif (s/^-k(.*)//s) {
1722 } elsif (s/^-wn//s) {
1724 $cleanmode = 'none';
1725 } elsif (s/^-wg//s) {
1728 } elsif (s/^-wd//s) {
1730 $cleanmode = 'dpkg-source';
1732 badusage "unknown short option \`$_'";
1739 if ($ENV{$fakeeditorenv}) {
1740 quilt_fixup_editor();
1743 delete $ENV{'DGET_UNPACK'};
1746 print STDERR "DRY RUN ONLY\n" if $dryrun;
1748 print STDERR $helpmsg or die $!;
1751 my $cmd = shift @ARGV;
1753 { no strict qw(refs); &{"cmd_$cmd"}(); }