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);
81 open DEBUG, ">/dev/null" or die $!;
83 our $remotename = 'dgit';
84 our @ourdscfield = qw(Dgit Vcs-Dgit-Master);
85 our $branchprefix = 'dgit';
88 sub lbranch () { return "$branchprefix/$csuite"; }
89 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
90 sub lref () { return "refs/heads/".lbranch(); }
91 sub lrref () { return "refs/remotes/$remotename/$branchprefix/$csuite"; }
92 sub rrref () { return "refs/$branchprefix/$csuite"; }
107 return "${package}_".(stripepoch $vsn).".dsc";
110 sub changesopts () { return @changesopts[1..$#changesopts]; }
114 sub fail { die "$us: @_\n"; }
116 sub badcfg { print STDERR "$us: invalid configuration: @_\n"; exit 12; }
118 sub no_such_package () {
119 print STDERR "$us: package $package does not exist in suite $isuite\n";
125 return "+".rrref().":".lrref();
128 #---------- remote protocol support, common ----------
130 # remote push initiator/responder protocol:
131 # < dgit-remote-push-ready [optional extra info ignored by old initiators]
133 # > file begin parsed-changelog
134 # [indicates that output of dpkg-parsechangelog follows]
135 # > data-block NBYTES
136 # > [NBYTES bytes of data (no newline)]
137 # [maybe some more blocks]
143 # > file begin changes
147 # [indicates that signed tag is wanted]
148 # < data-block NBYTES
149 # < [NBYTES bytes of data (no newline)]
150 # [maybe some more blocks]
154 # > want signed-changes-dsc
155 # < data-block NBYTES [transfer of signed changes]
157 # < data-block NBYTES [transfer of signed dsc]
165 fail "connection lost: $!" if $fh->error;
166 fail "connection terminated" if $fh->eof;
167 fail "protocol violation; $m not expected";
170 sub protocol_expect ($&) {
171 my ($fh, $match) = @_;
174 defined && chomp or badproto $fh, "eof";
176 badproto $fh, "\`$_'";
179 sub protocol_send_file ($$) {
180 my ($fh, $ourfn) = @_;
181 open PF, "<", $ourfn or die "$ourfn: $!";
184 my $got = read PF, $d, 65536;
185 die "$ourfn: $!" unless defined $got;
187 print $fh "data-block ".length($d)."\n" or die $!;
190 print $fh "data-end\n" or die $!;
194 sub protocol_receive_file ($$) {
195 my ($fh, $ourfn) = @_;
196 open PF, ">", $ourfn or die "$ourfn: $!";
198 protocol_expect \*STDIN, { m/^data-block (\d{1,6})$|data-end$/ };
201 my $got = read $fh, $d, $1;
202 $got==$1 or badproto $fh, "eof during data block";
203 print PF $d or die $!;
207 #---------- remote protocol support, responder ----------
209 sub responder_send_command ($) {
211 return unless $we_are_responder;
212 # called even without $we_are_responder
213 print DEBUG "<< $command\n";
214 print $command, "\n" or die $!;
217 sub responder_send_file ($$) {
218 my ($keyword, $ourfn) = @_;
219 return unless $we_are_responder;
220 responder_send_command "file begin $cmdprefix";
221 protocol_send_file \*STDOUT, $ourfn;
224 sub responder_receive_files ($@) {
225 my ($keyword, @ourfns) = @_;
226 die unless $we_are_responder;
227 responder_send_command "want $keyword";
228 foreach my $fn (@ourfns) {
229 protocol_receive_file \*STDIN, $fn;
231 protocol_expect \*STDIN, { m/^files-end$/ };
234 #---------- remote protocol support, initiator ----------
238 #---------- end remote code ----------
241 if ($we_are_responder) {
243 responder_send_command "progress ".length($m) or die $!;
254 $ua = LWP::UserAgent->new();
258 progress "downloading $what...";
259 my $r = $ua->get(@_) or die $!;
260 return undef if $r->code == 404;
261 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
262 return $r->decoded_content();
265 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
272 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
278 return join '', @out;
283 my $intro = shift @_;
284 print $fh $intro or die $!;
285 print $fh shellquote @_ or die $!;
286 print $fh "\n" or die $!;
290 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
292 fail "failed to fork/exec: $!";
293 } elsif (!($? & 0xff)) {
294 fail "subprocess failed with error exit status ".($?>>8);
296 fail "subprocess crashed (wait status $?)";
298 fail "subprocess produced invalid output";
303 printcmd(\*DEBUG,"+",@_) if $debug>0;
305 failedcmd @_ if system @_;
310 progress "dgit ok: @_";
312 progress "would be ok: @_ (but dry run only)";
316 sub cmdoutput_errok {
317 die Dumper(\@_)." ?" if grep { !defined } @_;
318 printcmd(\*DEBUG,"|",@_) if $debug>0;
319 open P, "-|", @_ or die $!;
322 { local $/ = undef; $d = <P>; }
324 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
327 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
332 my $d = cmdoutput_errok @_;
333 defined $d or failedcmd @_;
338 printcmd(\*STDERR,"#",@_);
341 sub runcmd_ordryrun {
350 my ($first_shell, @cmd) = @_;
351 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
354 our $helpmsg = <<END;
356 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
357 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
358 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
359 dgit [dgit-opts] push [dgit-opts] [suite]
360 important dgit options:
361 -k<keyid> sign tag and package with <keyid> instead of default
362 --dry-run -n do not change anything, but go through the motions
363 --new -N allow introducing a new package
364 --debug -D increase debug level
365 -c<name>=<value> set git config option (used directly by dgit too)
368 our $later_warning_msg = <<END;
369 Perhaps the upload is stuck in incoming. Using the version from git.
373 print STDERR "$us: @_\n", $helpmsg or die $!;
378 @ARGV or badusage "too few arguments";
379 return scalar shift @ARGV;
383 print $helpmsg or die $!;
387 our %defcfg = ('dgit.default.distro' => 'debian',
388 'dgit.default.username' => '',
389 'dgit.default.archive-query-default-component' => 'main',
390 'dgit.default.ssh' => 'ssh',
391 'dgit-distro.debian.git-host' => 'git.debian.org',
392 'dgit-distro.debian.git-proto' => 'git+ssh://',
393 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
394 'dgit-distro.debian.git-check' => 'ssh-cmd',
395 'dgit-distro.debian.git-create' => 'ssh-cmd',
396 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
397 'dgit-distro.debian.sshdakls-dir' =>
398 '/srv/ftp-master.debian.org/ftp/dists',
399 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
400 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
404 return undef if $c =~ /RETURN-UNDEF/;
405 my @cmd = (@git, qw(config --), $c);
408 local ($debug) = $debug-1;
409 $v = cmdoutput_errok @cmd;
416 my $dv = $defcfg{$c};
417 return $dv if defined $dv;
419 badcfg "need value for one of: @_";
422 sub access_distro () {
423 return cfg("dgit-suite.$isuite.distro",
424 "dgit.default.distro");
429 my $distro = $idistro || access_distro();
430 my $value = cfg(map { ("dgit-distro.$distro.$_",
431 "dgit.default.$_") } @keys);
435 sub access_someuserhost ($) {
437 my $user = access_cfg("$some-user",'username');
438 my $host = access_cfg("$some-host");
439 return length($user) ? "$user\@$host" : $host;
442 sub access_gituserhost () {
443 return access_someuserhost('git');
446 sub access_giturl () {
447 my $url = access_cfg('git-url','RETURN-UNDEF');
450 access_cfg('git-proto').
451 access_gituserhost().
452 access_cfg('git-path');
454 return "$url/$package.git";
457 sub parsecontrolfh ($$@) {
458 my ($fh, $desc, @opts) = @_;
459 my %opts = ('name' => $desc, @opts);
460 my $c = Dpkg::Control::Hash->new(%opts);
461 $c->parse($fh) or die "parsing of $desc failed";
466 my ($file, $desc) = @_;
467 my $fh = new IO::Handle;
468 open $fh, '<', $file or die "$file: $!";
469 my $c = parsecontrolfh($fh,$desc);
470 $fh->error and die $!;
476 my ($dctrl,$field) = @_;
477 my $v = $dctrl->{$field};
478 return $v if defined $v;
479 fail "missing field $field in ".$v->get_option('name');
483 my $c = Dpkg::Control::Hash->new();
484 my $p = new IO::Handle;
485 my @cmd = (qw(dpkg-parsechangelog), @_);
486 open $p, '-|', @cmd or die $!;
488 $?=0; $!=0; close $p or failedcmd @cmd;
494 sub archive_query ($) {
496 my $query = access_cfg('archive-query','RETURN-UNDEF');
497 if (!defined $query) {
498 my $distro = access_distro();
499 if ($distro eq 'debian') {
500 $query = "sshdakls:".
501 access_someuserhost('sshdakls').':'.
502 access_cfg('sshdakls-dir');
504 $query = "madison:$distro";
507 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
510 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
513 sub archive_query_madison ($$) {
514 my ($proto,$data) = @_;
515 die unless $proto eq 'madison';
516 $rmad{$package} ||= cmdoutput
517 qw(rmadison -asource),"-s$isuite","-u$data",$package;
518 my $rmad = $rmad{$package};
519 return madison_parse($rmad);
522 sub archive_query_sshdakls ($$) {
523 my ($proto,$data) = @_;
524 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
525 my $dakls = cmdoutput
526 access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
527 return madison_parse($dakls);
530 sub canonicalise_suite_sshdakls ($$) {
531 my ($proto,$data) = @_;
532 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
534 (access_cfg('ssh'), $`,
536 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
537 " if test -d $isuite; then echo $isuite; exit 0; fi;".
539 my $dakls = cmdoutput @cmd;
540 failedcmd @cmd unless $dakls =~ m/^\w/;
544 sub madison_parse ($) {
547 foreach my $l (split /\n/, $rmad) {
548 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
549 \s*( [^ \t|]+ )\s* \|
550 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
551 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
552 $1 eq $package or die "$rmad $package ?";
559 $component = access_cfg('archive-query-default-component');
561 $5 eq 'source' or die "$rmad ?";
562 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
563 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
564 push @out, [$vsn,$subpath,$newsuite];
566 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
569 sub canonicalise_suite_madison ($$) {
570 my @r = archive_query_madison($_[0],$_[1]);
572 "unable to canonicalise suite using package $package".
573 " which does not appear to exist in suite $isuite;".
574 " --existing-package may help";
578 sub canonicalise_suite () {
579 return if defined $csuite;
580 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
581 $csuite = archive_query('canonicalise_suite');
582 if ($isuite ne $csuite) {
583 # madison canonicalises for us
584 progress "canonical suite name for $isuite is $csuite";
588 sub get_archive_dsc () {
589 canonicalise_suite();
590 my @vsns = archive_query('archive_query');
591 foreach my $vinfo (@vsns) {
592 my ($vsn,$subpath) = @$vinfo;
593 $dscurl = access_cfg('mirror').$subpath;
594 $dscdata = url_get($dscurl);
596 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
599 my $dscfh = new IO::File \$dscdata, '<' or die $!;
600 print DEBUG Dumper($dscdata) if $debug>1;
601 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
602 print DEBUG Dumper($dsc) if $debug>1;
603 my $fmt = getfield $dsc, 'Format';
604 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
610 sub check_for_git () {
612 my $how = access_cfg('git-check');
613 if ($how eq 'ssh-cmd') {
615 (access_cfg('ssh'),access_gituserhost(),
616 " set -e; cd ".access_cfg('git-path').";".
617 " if test -d $package.git; then echo 1; else echo 0; fi");
618 my $r= cmdoutput @cmd;
619 failedcmd @cmd unless $r =~ m/^[01]$/;
622 badcfg "unknown git-check \`$how'";
626 sub create_remote_git_repo () {
627 my $how = access_cfg('git-create');
628 if ($how eq 'ssh-cmd') {
630 (access_cfg('ssh'),access_gituserhost(),
631 "set -e; cd ".access_cfg('git-path').";".
632 " cp -a _template $package.git");
634 badcfg "unknown git-create \`$how'";
638 our ($dsc_hash,$lastpush_hash);
640 our $ud = '.git/dgit/unpack';
648 sub mktree_in_ud_from_only_subdir () {
649 # changes into the subdir
652 $dirs[0] =~ m#^([^/]+)/\.$# or die;
654 chdir $dir or die "$dir $!";
655 fail "source package contains .git directory" if stat '.git';
656 die $! unless $!==&ENOENT;
657 runcmd qw(git init -q);
658 rmtree('.git/objects');
659 symlink '../../../../objects','.git/objects' or die $!;
660 runcmd @git, qw(add -Af);
661 my $tree = cmdoutput @git, qw(write-tree);
662 $tree =~ m/^\w+$/ or die "$tree ?";
666 sub dsc_files_info () {
667 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
668 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
669 ['Files', 'Digest::MD5', 'new()']) {
670 my ($fname, $module, $method) = @$csumi;
671 my $field = $dsc->{$fname};
672 next unless defined $field;
673 eval "use $module; 1;" or die $@;
675 foreach (split /\n/, $field) {
677 m/^(\w+) (\d+) (\S+)$/ or
678 fail "could not parse .dsc $fname line \`$_'";
679 my $digester = eval "$module"."->$method;" or die $@;
684 Digester => $digester,
689 fail "missing any supported Checksums-* or Files field in ".
690 $dsc->get_option('name');
694 map { $_->{Filename} } dsc_files_info();
697 sub is_orig_file ($) {
699 m/\.orig(?:-\w+)?\.tar\.\w+$/;
702 sub make_commit ($) {
704 return cmdoutput @git, qw(hash-object -w -t commit), $file;
707 sub clogp_authline ($) {
709 my $author = getfield $clogp, 'Maintainer';
710 $author =~ s#,.*##ms;
711 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
712 my $authline = "$author $date";
713 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
714 fail "unexpected commit author line format \`$authline'".
715 " (was generated from changelog Maintainer field)";
719 sub generate_commit_from_dsc () {
723 foreach my $f (dsc_files()) {
724 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
726 link "../../../$f", $f
730 runcmd @dget, qw(--), $dscurl;
731 foreach my $f (grep { is_orig_file($_) } @files) {
732 link $f, "../../../../$f"
736 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
737 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
738 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
739 my $authline = clogp_authline $clogp;
740 my $changes = getfield $clogp, 'Changes';
741 open C, ">../commit.tmp" or die $!;
742 print C <<END or die $!;
749 # imported from the archive
752 my $outputhash = make_commit qw(../commit.tmp);
753 my $cversion = getfield $clogp, 'Version';
754 progress "synthesised git commit from .dsc $cversion";
755 if ($lastpush_hash) {
756 runcmd @git, qw(reset --hard), $lastpush_hash;
757 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
758 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
759 my $oversion = getfield $oldclogp, 'Version';
761 version_compare_string($oversion, $cversion);
763 # git upload/ is earlier vsn than archive, use archive
764 open C, ">../commit2.tmp" or die $!;
765 print C <<END or die $!;
767 parent $lastpush_hash
772 Record $package ($cversion) in archive suite $csuite
774 $outputhash = make_commit qw(../commit2.tmp);
775 } elsif ($vcmp > 0) {
776 print STDERR <<END or die $!;
778 Version actually in archive: $cversion (older)
779 Last allegedly pushed/uploaded: $oversion (newer or same)
782 $outputhash = $lastpush_hash;
784 $outputhash = $lastpush_hash;
787 chdir '../../../..' or die $!;
788 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
789 'DGIT_ARCHIVE', $outputhash;
790 cmdoutput @git, qw(log -n2), $outputhash;
791 # ... gives git a chance to complain if our commit is malformed
796 sub ensure_we_have_orig () {
797 foreach my $fi (dsc_files_info()) {
798 my $f = $fi->{Filename};
799 next unless is_orig_file($f);
800 if (open F, "<", "../$f") {
801 $fi->{Digester}->reset();
802 $fi->{Digester}->addfile(*F);
804 my $got = $fi->{Digester}->hexdigest();
805 $got eq $fi->{Hash} or
806 fail "existing file $f has hash $got but .dsc".
807 " demands hash $fi->{Hash}".
808 " (perhaps you should delete this file?)";
809 progress "using existing $f";
812 die "$f $!" unless $!==&ENOENT;
814 my $origurl = $dscurl;
815 $origurl =~ s{/[^/]+$}{};
817 die "$f ?" unless $f =~ m/^${package}_/;
818 die "$f ?" if $f =~ m#/#;
819 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
824 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
827 sub is_fast_fwd ($$) {
828 my ($ancestor,$child) = @_;
829 my @cmd = (@git, qw(merge-base), $ancestor, $child);
830 my $mb = cmdoutput_errok @cmd;
832 return rev_parse($mb) eq rev_parse($ancestor);
834 $?==256 or failedcmd @cmd;
839 sub git_fetch_us () {
840 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
843 sub fetch_from_archive () {
844 # ensures that lrref() is what is actually in the archive,
849 foreach my $field (@ourdscfield) {
850 $dsc_hash = $dsc->{$field};
851 last if defined $dsc_hash;
853 if (defined $dsc_hash) {
854 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
856 progress "last upload to archive specified git hash";
858 progress "last upload to archive has NO git hash";
861 progress "no version available from the archive";
864 my $lrref_fn = ".git/".lrref();
865 if (open H, $lrref_fn) {
866 $lastpush_hash = <H>;
867 chomp $lastpush_hash;
868 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
869 } elsif ($! == &ENOENT) {
874 print DEBUG "previous reference hash=$lastpush_hash\n";
876 if (defined $dsc_hash) {
877 fail "missing git history even though dsc has hash -".
878 " could not find commit $dsc_hash".
879 " (should be in ".access_giturl()."#".rrref().")"
880 unless $lastpush_hash;
882 ensure_we_have_orig();
883 if ($dsc_hash eq $lastpush_hash) {
884 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
885 print STDERR <<END or die $!;
887 Git commit in archive is behind the last version allegedly pushed/uploaded.
888 Commit referred to by archive: $dsc_hash
889 Last allegedly pushed/uploaded: $lastpush_hash
892 $hash = $lastpush_hash;
894 fail "archive's .dsc refers to ".$dsc_hash.
895 " but this is an ancestor of ".$lastpush_hash;
898 $hash = generate_commit_from_dsc();
899 } elsif ($lastpush_hash) {
900 # only in git, not in the archive yet
901 $hash = $lastpush_hash;
902 print STDERR <<END or die $!;
904 Package not found in the archive, but has allegedly been pushed using dgit.
908 print DEBUG "nothing found!\n";
909 if (defined $skew_warning_vsn) {
910 print STDERR <<END or die $!;
912 Warning: relevant archive skew detected.
913 Archive allegedly contains $skew_warning_vsn
914 But we were not able to obtain any version from the archive or git.
920 print DEBUG "current hash=$hash\n";
921 if ($lastpush_hash) {
922 fail "not fast forward on last upload branch!".
923 " (archive's version left in DGIT_ARCHIVE)"
924 unless is_fast_fwd($lastpush_hash, $hash);
926 if (defined $skew_warning_vsn) {
928 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
929 my $clogf = ".git/dgit/changelog.tmp";
930 runcmd shell_cmd "exec >$clogf",
931 @git, qw(cat-file blob), "$hash:debian/changelog";
932 my $gotclogp = parsechangelog("-l$clogf");
933 my $got_vsn = getfield $gotclogp, 'Version';
934 print DEBUG "SKEW CHECK GOT $got_vsn\n";
935 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
936 print STDERR <<END or die $!;
938 Warning: archive skew detected. Using the available version:
939 Archive allegedly contains $skew_warning_vsn
940 We were able to obtain only $got_vsn
945 if ($lastpush_hash ne $hash) {
946 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
950 dryrun_report @upd_cmd;
958 canonicalise_suite();
959 badusage "dry run makes no sense with clone" if $dryrun;
960 mkdir $dstdir or die "$dstdir $!";
961 chdir "$dstdir" or die "$dstdir $!";
962 runcmd @git, qw(init -q);
963 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
964 open H, "> .git/HEAD" or die $!;
965 print H "ref: ".lref()."\n" or die $!;
967 runcmd @git, qw(remote add), 'origin', access_giturl();
968 if (check_for_git()) {
969 progress "fetching existing git history";
971 runcmd_ordryrun @git, qw(fetch origin);
973 progress "starting new git history";
975 fetch_from_archive() or no_such_package;
976 runcmd @git, qw(reset --hard), lrref();
977 printdone "ready for work in $dstdir";
981 if (check_for_git()) {
984 fetch_from_archive() or no_such_package();
985 printdone "fetched into ".lrref();
990 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
992 printdone "fetched to ".lrref()." and merged into HEAD";
995 sub check_not_dirty () {
996 return if $ignoredirty;
997 my @cmd = (@git, qw(diff --quiet HEAD));
998 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
999 $!=0; $?=0; system @cmd;
1000 return if !$! && !$?;
1001 if (!$! && $?==256) {
1002 fail "working tree is dirty (does not match HEAD)";
1008 sub commit_quilty_patch () {
1009 my $output = cmdoutput @git, qw(status --porcelain);
1012 foreach my $l (split /\n/, $output) {
1013 next unless $l =~ m/\S/;
1014 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1017 print STDERR "git status: $l\n";
1021 fail "unexpected output from git status (is tree clean?)" if $bad;
1023 progress "nothing quilty to commit, ok.";
1026 runcmd_ordryrun @git, qw(add), sort keys %adds;
1027 my $m = "Commit Debian 3.0 (quilt) metadata";
1029 runcmd_ordryrun @git, qw(commit -m), $m;
1034 return 0 unless $format eq '3.0 (quilt)';
1035 progress "Format \`$format', urgh";
1037 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1043 sub push_parse_changelog ($) {
1046 my $clogp = Dpkg::Control::Hash->new();
1047 $clogp->load($clogpfn);
1049 $package = getfield $clogp, 'Source';
1050 my $cversion = getfield $clogp, 'Version';
1051 my $tag = debiantag($cversion);
1052 runcmd @git, qw(check-ref-format), $tag;
1054 my $dscfn = dscfn($cversion);
1056 return ($clogp, $cversion, $tag, $dscfn);
1059 sub push_parse_dsc ($$) {
1060 my ($dscfn,$dscfnwhat, $cversion) = @_;
1061 $dsc = parsecontrol($dscfn,$dscfnwhat);
1062 my $dversion = getfield $dsc, 'Version';
1063 my $dscpackage = getfield $dsc, 'Source';
1064 ($dscpackage eq $package && $dversion eq $cversion) or
1065 fail "$dsc is for $dscpackage $dversion".
1066 " but debian/changelog is for $package $cversion";
1069 sub push_mktag ($$$$$$$$) {
1070 my ($head,$clogp,$tag,
1072 $changesfile,$changesfilewhat,
1075 $dsc->{$ourdscfield[0]} = $head;
1076 $dsc->save("$dscfn.tmp") or die $!;
1078 my $changes = parsecontrol($changesfile,$changesfilewhat);
1079 foreach my $field (qw(Source Distribution Version)) {
1080 $changes->{$field} eq $clogp->{$field} or
1081 fail "changes field $field \`$changes->{$field}'".
1082 " does not match changelog \`$clogp->{$field}'";
1085 # We make the git tag by hand because (a) that makes it easier
1086 # to control the "tagger" (b) we can do remote signing
1087 my $authline = clogp_authline $clogp;
1088 open TO, '>', $tfn->('.tmp') or die $!;
1089 print TO <<END or die $!;
1095 $package release $cversion for $csuite [dgit]
1099 my $tagobjfn = $tfn->('.tmp');
1101 if (!defined $keyid) {
1102 $keyid = access_cfg('keyid','RETURN-UNDEF');
1104 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1105 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1106 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1107 push @sign_cmd, $tfn->('.tmp');
1108 runcmd_ordryrun @sign_cmd;
1110 $tagobjfn = $tfn->('.signed.tmp');
1111 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1112 $tfn->('.tmp'), $tfn->('.tmp.asc');
1120 print DEBUG "actually entering push\n";
1123 my $clogpfn = ".git/dgit/changelog.822.tmp";
1124 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1126 responder_send_file('parsed-changelog', $clogpfn);
1128 my ($clogp, $cversion, $tag, $dscfn) =
1129 push_parse_changelog("$clogpfn");
1132 fail "looked for .dsc $dscfn, but $!;".
1133 " maybe you forgot to build";
1135 responder_send_file('dsc', "../$dscfn");
1137 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1139 my $format = getfield $dsc, 'Format';
1140 print DEBUG "format $format\n";
1141 if (madformat($format)) {
1142 commit_quilty_patch();
1145 chdir $ud or die $!;
1146 progress "checking that $dscfn corresponds to HEAD";
1147 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1148 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1149 chdir '../../../..' or die $!;
1150 printcmd \*DEBUG,"+",@_;
1151 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1153 if (system @diffcmd) {
1154 if ($! && $?==256) {
1155 fail "$dscfn specifies a different tree to your HEAD commit;".
1156 " perhaps you forgot to build";
1162 #do fast forward check and maybe fake merge
1163 # if (!is_fast_fwd(mainbranch
1164 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1165 # map { lref($_).":".rref($_) }
1167 my $head = rev_parse('HEAD');
1168 if (!$changesfile) {
1169 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1170 if (stat "$multi") {
1171 $changesfile = $multi;
1173 $!==&ENOENT or die "$multi: $!";
1174 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1175 my @cs = glob "../$pat";
1176 fail "failed to find unique changes file".
1177 " (looked for $pat in .., or $multi);".
1178 " perhaps you need to use dgit -C"
1180 ($changesfile) = @cs;
1184 responder_send_file('changes',$changesfn);
1186 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1189 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1190 : push_mktag($head,$clogp,$tag,
1192 $changesfile,$changesfile,
1195 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1196 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1197 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1198 runcmd_ordryrun @git, qw(tag -v --), $tag;
1200 if (!check_for_git()) {
1201 create_remote_git_repo();
1203 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1204 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1206 if (!$we_are_responder) {
1208 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1210 progress "[new .dsc left in $dscfn.tmp]";
1215 if ($we_are_responder) {
1216 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1217 responder_receive_files('signed-changes-dsc',
1218 "$changesfile$dryrunsuffix",
1219 "../$dscfn$dryrunsuffix");
1221 my @debsign_cmd = @debsign;
1222 push @debsign_cmd, "-k$keyid" if defined $keyid;
1223 push @debsign_cmd, $changesfile;
1224 runcmd_ordryrun @debsign_cmd;
1227 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1228 my $host = access_cfg('upload-host','RETURN-UNDEF');
1229 my @hostarg = defined($host) ? ($host,) : ();
1230 runcmd_ordryrun @dput, @hostarg, $changesfile;
1231 printdone "pushed and uploaded $cversion";
1233 responder_send_command("complete");
1239 badusage "-p is not allowed with clone; specify as argument instead"
1240 if defined $package;
1243 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1244 ($package,$isuite) = @ARGV;
1245 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1246 ($package,$dstdir) = @ARGV;
1247 } elsif (@ARGV==3) {
1248 ($package,$isuite,$dstdir) = @ARGV;
1250 badusage "incorrect arguments to dgit clone";
1252 $dstdir ||= "$package";
1256 sub branchsuite () {
1257 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1258 if ($branch =~ m#$lbranch_re#o) {
1265 sub fetchpullargs () {
1266 if (!defined $package) {
1267 my $sourcep = parsecontrol('debian/control','debian/control');
1268 $package = getfield $sourcep, 'Source';
1271 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1273 my $clogp = parsechangelog();
1274 $isuite = getfield $clogp, 'Distribution';
1276 canonicalise_suite();
1277 progress "fetching from suite $csuite";
1278 } elsif (@ARGV==1) {
1280 canonicalise_suite();
1282 badusage "incorrect arguments to dgit fetch or dgit pull";
1300 badusage "-p is not allowed with dgit push" if defined $package;
1302 my $clogp = parsechangelog();
1303 $package = getfield $clogp, 'Source';
1306 } elsif (@ARGV==1) {
1307 ($specsuite) = (@ARGV);
1309 badusage "incorrect arguments to dgit push";
1311 $isuite = getfield $clogp, 'Distribution';
1313 local ($package) = $existing_package; # this is a hack
1314 canonicalise_suite();
1316 if (defined $specsuite && $specsuite ne $isuite) {
1317 canonicalise_suite();
1318 $csuite eq $specsuite or
1319 fail "dgit push: changelog specifies $isuite ($csuite)".
1320 " but command line specifies $specsuite";
1322 if (check_for_git()) {
1325 if (fetch_from_archive()) {
1326 is_fast_fwd(lrref(), 'HEAD') or
1327 fail "dgit push: HEAD is not a descendant".
1328 " of the archive's version.\n".
1329 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1332 fail "package appears to be new in this suite;".
1333 " if this is intentional, use --new";
1338 #---------- remote commands' implementation ----------
1340 sub cmd_remote_push_responder {
1341 my ($nrargs) = shift @ARGV;
1342 my (@rargs) = @ARGV[0..$nrargs-1];
1343 @ARGV = @ARGV[$nrargs..$#ARGV];
1346 chdir $dir or die "$dir: $!";
1349 responder_send_command("dgit-remote-push-ready");
1356 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1366 push @rdgit, @ropts;
1367 push @rdgit, (scalar @rargs), @rargs;
1369 my @cmd = (@ssh, $host, shellquote @rdgit);
1370 my $pid = open2(\*RO, \*RI, @cmd);
1371 initiator_expect { m/^dgit-remote-push-ready/ };
1373 initiator_expect { m/^(\S+)\s+(.*)$/ };
1374 my ($icmd,$iargs) = ($1, $2);
1376 { no strict qw(refs); &{"i_resp_$icmd"}($iargs); }
1380 #---------- building etc. ----------
1386 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1388 sub build_maybe_quilt_fixup () {
1389 if (!open F, "debian/source/format") {
1390 die $! unless $!==&ENOENT;
1394 F->error and die $!;
1396 return unless madformat($_);
1398 my $clogp = parsechangelog();
1399 my $version = getfield $clogp, 'Version';
1400 my $author = getfield $clogp, 'Maintainer';
1401 my $headref = rev_parse('HEAD');
1404 my $patchname = "auto-$version-$headref-$time";
1405 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1407 my $descfn = ".git/dgit/quilt-description.tmp";
1408 open O, '>', $descfn or die "$descfn: $!";
1410 $msg =~ s/^\s+$/ ./mg;
1411 print O <<END or die $!;
1412 Description: Automatically generated patch ($clogp->{Version})
1413 Last (up to) $ncommits git changes, FYI:
1423 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1424 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1425 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1426 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1429 if (!open P, '>>', ".pc/applied-patches") {
1430 $!==&ENOENT or die $!;
1435 commit_quilty_patch();
1438 sub quilt_fixup_editor () {
1439 my $descfn = $ENV{$fakeeditorenv};
1440 my $editing = $ARGV[$#ARGV];
1441 open I1, '<', $descfn or die "$descfn: $!";
1442 open I2, '<', $editing or die "$editing: $!";
1443 unlink $editing or die "$editing: $!";
1444 open O, '>', $editing or die "$editing: $!";
1445 while (<I1>) { print O or die $!; } I1->error and die $!;
1448 $copying ||= m/^\-\-\- /;
1449 next unless $copying;
1452 I2->error and die $!;
1458 badusage "-p is not allowed when building" if defined $package;
1460 my $clogp = parsechangelog();
1461 $isuite = getfield $clogp, 'Distribution';
1462 $package = getfield $clogp, 'Source';
1463 $version = getfield $clogp, 'Version';
1464 build_maybe_quilt_fixup();
1468 badusage "dgit build implies --clean=dpkg-source"
1469 if $cleanmode ne 'dpkg-source';
1471 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1472 printdone "build successful\n";
1476 badusage "dgit git-build implies --clean=dpkg-source"
1477 if $cleanmode ne 'dpkg-source';
1480 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1481 "--git-builder=@dpkgbuildpackage");
1482 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1483 canonicalise_suite();
1484 push @cmd, "--git-debian-branch=".lbranch();
1486 push @cmd, changesopts();
1487 runcmd_ordryrun @cmd, @ARGV;
1488 printdone "build successful\n";
1493 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1494 $dscfn = dscfn($version);
1495 if ($cleanmode eq 'dpkg-source') {
1496 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1498 if ($cleanmode eq 'git') {
1499 runcmd_ordryrun @git, qw(clean -xdf);
1500 } elsif ($cleanmode eq 'none') {
1504 my $pwd = cmdoutput qw(env - pwd);
1505 my $leafdir = basename $pwd;
1506 chdir ".." or die $!;
1507 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1508 chdir $pwd or die $!;
1509 runcmd_ordryrun qw(sh -ec),
1510 'exec >$1; shift; exec "$@"','x',
1511 "../$sourcechanges",
1512 @dpkggenchanges, qw(-S), changesopts();
1516 sub cmd_build_source {
1517 badusage "build-source takes no additional arguments" if @ARGV;
1519 printdone "source built, results in $dscfn and $sourcechanges";
1524 chdir ".." or die $!;
1525 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1527 stat $dscfn or fail "$dscfn (in parent directory): $!";
1528 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1529 foreach my $cf (glob $pat) {
1530 next if $cf eq $sourcechanges;
1531 unlink $cf or fail "remove $cf: $!";
1534 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1535 runcmd_ordryrun @mergechanges, glob $pat;
1536 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1538 stat $multichanges or fail "$multichanges: $!";
1540 printdone "build successful, results in $multichanges\n" or die $!;
1543 sub cmd_quilt_fixup {
1544 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1545 my $clogp = parsechangelog();
1546 $version = getfield $clogp, 'Version';
1547 build_maybe_quilt_fixup();
1550 #---------- argument parsing and main program ----------
1553 print "dgit version $our_version\n" or die $!;
1560 last unless $ARGV[0] =~ m/^-/;
1564 if (m/^--dry-run$/) {
1567 } elsif (m/^--no-sign$/) {
1570 } elsif (m/^--help$/) {
1572 } elsif (m/^--version$/) {
1574 } elsif (m/^--new$/) {
1577 } elsif (m/^--(\w+)=(.*)/s &&
1578 ($om = $opts_opt_map{$1}) &&
1582 } elsif (m/^--(\w+):(.*)/s &&
1583 ($om = $opts_opt_map{$1})) {
1586 } elsif (m/^--existing-package=(.*)/s) {
1588 $existing_package = $1;
1589 } elsif (m/^--distro=(.*)/s) {
1592 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1595 } elsif (m/^--clean=(.*)$/s) {
1596 badusage "unknown cleaning mode \`$1'";
1597 } elsif (m/^--ignore-dirty$/s) {
1600 } elsif (m/^--no-quilt-fixup$/s) {
1604 badusage "unknown long option \`$_'";
1611 } elsif (s/^-h/-/) {
1613 } elsif (s/^-D/-/) {
1615 open DEBUG, ">&STDERR" or die $!;
1617 } elsif (s/^-N/-/) {
1620 } elsif (m/^-[vm]/) {
1622 push @changesopts, $_;
1624 } elsif (s/^-c(.*=.*)//s) {
1626 push @git, '-c', $1;
1627 } elsif (s/^-d(.*)//s) {
1630 } elsif (s/^-C(.*)//s) {
1633 } elsif (s/^-k(.*)//s) {
1635 } elsif (s/^-wn//s) {
1637 $cleanmode = 'none';
1638 } elsif (s/^-wg//s) {
1641 } elsif (s/^-wd//s) {
1643 $cleanmode = 'dpkg-source';
1645 badusage "unknown short option \`$_'";
1652 if ($ENV{$fakeeditorenv}) {
1653 quilt_fixup_editor();
1656 delete $ENV{'DGET_UNPACK'};
1659 print STDERR "DRY RUN ONLY\n" if $dryrun;
1661 print STDERR $helpmsg or die $!;
1664 my $cmd = shift @ARGV;
1666 { no strict qw(refs); &{"cmd_$cmd"}(); }