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 ----------
236 sub initiator_expect (&) {
238 protocol_expect \*RO, &$match;
241 #---------- end remote code ----------
244 if ($we_are_responder) {
246 responder_send_command "progress ".length($m) or die $!;
257 $ua = LWP::UserAgent->new();
261 progress "downloading $what...";
262 my $r = $ua->get(@_) or die $!;
263 return undef if $r->code == 404;
264 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
265 return $r->decoded_content();
268 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
275 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
281 return join '', @out;
286 my $intro = shift @_;
287 print $fh $intro or die $!;
288 print $fh shellquote @_ or die $!;
289 print $fh "\n" or die $!;
293 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
295 fail "failed to fork/exec: $!";
296 } elsif (!($? & 0xff)) {
297 fail "subprocess failed with error exit status ".($?>>8);
299 fail "subprocess crashed (wait status $?)";
301 fail "subprocess produced invalid output";
306 printcmd(\*DEBUG,"+",@_) if $debug>0;
308 failedcmd @_ if system @_;
313 progress "dgit ok: @_";
315 progress "would be ok: @_ (but dry run only)";
319 sub cmdoutput_errok {
320 die Dumper(\@_)." ?" if grep { !defined } @_;
321 printcmd(\*DEBUG,"|",@_) if $debug>0;
322 open P, "-|", @_ or die $!;
325 { local $/ = undef; $d = <P>; }
327 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
330 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
335 my $d = cmdoutput_errok @_;
336 defined $d or failedcmd @_;
341 printcmd(\*STDERR,"#",@_);
344 sub runcmd_ordryrun {
353 my ($first_shell, @cmd) = @_;
354 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
357 our $helpmsg = <<END;
359 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
360 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
361 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
362 dgit [dgit-opts] push [dgit-opts] [suite]
363 important dgit options:
364 -k<keyid> sign tag and package with <keyid> instead of default
365 --dry-run -n do not change anything, but go through the motions
366 --new -N allow introducing a new package
367 --debug -D increase debug level
368 -c<name>=<value> set git config option (used directly by dgit too)
371 our $later_warning_msg = <<END;
372 Perhaps the upload is stuck in incoming. Using the version from git.
376 print STDERR "$us: @_\n", $helpmsg or die $!;
381 @ARGV or badusage "too few arguments";
382 return scalar shift @ARGV;
386 print $helpmsg or die $!;
390 our %defcfg = ('dgit.default.distro' => 'debian',
391 'dgit.default.username' => '',
392 'dgit.default.archive-query-default-component' => 'main',
393 'dgit.default.ssh' => 'ssh',
394 'dgit-distro.debian.git-host' => 'git.debian.org',
395 'dgit-distro.debian.git-proto' => 'git+ssh://',
396 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
397 'dgit-distro.debian.git-check' => 'ssh-cmd',
398 'dgit-distro.debian.git-create' => 'ssh-cmd',
399 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
400 'dgit-distro.debian.sshdakls-dir' =>
401 '/srv/ftp-master.debian.org/ftp/dists',
402 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
403 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
407 return undef if $c =~ /RETURN-UNDEF/;
408 my @cmd = (@git, qw(config --), $c);
411 local ($debug) = $debug-1;
412 $v = cmdoutput_errok @cmd;
419 my $dv = $defcfg{$c};
420 return $dv if defined $dv;
422 badcfg "need value for one of: @_";
425 sub access_distro () {
426 return cfg("dgit-suite.$isuite.distro",
427 "dgit.default.distro");
432 my $distro = $idistro || access_distro();
433 my $value = cfg(map { ("dgit-distro.$distro.$_",
434 "dgit.default.$_") } @keys);
438 sub access_someuserhost ($) {
440 my $user = access_cfg("$some-user",'username');
441 my $host = access_cfg("$some-host");
442 return length($user) ? "$user\@$host" : $host;
445 sub access_gituserhost () {
446 return access_someuserhost('git');
449 sub access_giturl () {
450 my $url = access_cfg('git-url','RETURN-UNDEF');
453 access_cfg('git-proto').
454 access_gituserhost().
455 access_cfg('git-path');
457 return "$url/$package.git";
460 sub parsecontrolfh ($$@) {
461 my ($fh, $desc, @opts) = @_;
462 my %opts = ('name' => $desc, @opts);
463 my $c = Dpkg::Control::Hash->new(%opts);
464 $c->parse($fh) or die "parsing of $desc failed";
469 my ($file, $desc) = @_;
470 my $fh = new IO::Handle;
471 open $fh, '<', $file or die "$file: $!";
472 my $c = parsecontrolfh($fh,$desc);
473 $fh->error and die $!;
479 my ($dctrl,$field) = @_;
480 my $v = $dctrl->{$field};
481 return $v if defined $v;
482 fail "missing field $field in ".$v->get_option('name');
486 my $c = Dpkg::Control::Hash->new();
487 my $p = new IO::Handle;
488 my @cmd = (qw(dpkg-parsechangelog), @_);
489 open $p, '-|', @cmd or die $!;
491 $?=0; $!=0; close $p or failedcmd @cmd;
497 sub archive_query ($) {
499 my $query = access_cfg('archive-query','RETURN-UNDEF');
500 if (!defined $query) {
501 my $distro = access_distro();
502 if ($distro eq 'debian') {
503 $query = "sshdakls:".
504 access_someuserhost('sshdakls').':'.
505 access_cfg('sshdakls-dir');
507 $query = "madison:$distro";
510 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
513 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
516 sub archive_query_madison ($$) {
517 my ($proto,$data) = @_;
518 die unless $proto eq 'madison';
519 $rmad{$package} ||= cmdoutput
520 qw(rmadison -asource),"-s$isuite","-u$data",$package;
521 my $rmad = $rmad{$package};
522 return madison_parse($rmad);
525 sub archive_query_sshdakls ($$) {
526 my ($proto,$data) = @_;
527 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
528 my $dakls = cmdoutput
529 access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
530 return madison_parse($dakls);
533 sub canonicalise_suite_sshdakls ($$) {
534 my ($proto,$data) = @_;
535 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
537 (access_cfg('ssh'), $`,
539 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
540 " if test -d $isuite; then echo $isuite; exit 0; fi;".
542 my $dakls = cmdoutput @cmd;
543 failedcmd @cmd unless $dakls =~ m/^\w/;
547 sub madison_parse ($) {
550 foreach my $l (split /\n/, $rmad) {
551 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
552 \s*( [^ \t|]+ )\s* \|
553 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
554 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
555 $1 eq $package or die "$rmad $package ?";
562 $component = access_cfg('archive-query-default-component');
564 $5 eq 'source' or die "$rmad ?";
565 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
566 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
567 push @out, [$vsn,$subpath,$newsuite];
569 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
572 sub canonicalise_suite_madison ($$) {
573 my @r = archive_query_madison($_[0],$_[1]);
575 "unable to canonicalise suite using package $package".
576 " which does not appear to exist in suite $isuite;".
577 " --existing-package may help";
581 sub canonicalise_suite () {
582 return if defined $csuite;
583 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
584 $csuite = archive_query('canonicalise_suite');
585 if ($isuite ne $csuite) {
586 # madison canonicalises for us
587 progress "canonical suite name for $isuite is $csuite";
591 sub get_archive_dsc () {
592 canonicalise_suite();
593 my @vsns = archive_query('archive_query');
594 foreach my $vinfo (@vsns) {
595 my ($vsn,$subpath) = @$vinfo;
596 $dscurl = access_cfg('mirror').$subpath;
597 $dscdata = url_get($dscurl);
599 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
602 my $dscfh = new IO::File \$dscdata, '<' or die $!;
603 print DEBUG Dumper($dscdata) if $debug>1;
604 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
605 print DEBUG Dumper($dsc) if $debug>1;
606 my $fmt = getfield $dsc, 'Format';
607 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
613 sub check_for_git () {
615 my $how = access_cfg('git-check');
616 if ($how eq 'ssh-cmd') {
618 (access_cfg('ssh'),access_gituserhost(),
619 " set -e; cd ".access_cfg('git-path').";".
620 " if test -d $package.git; then echo 1; else echo 0; fi");
621 my $r= cmdoutput @cmd;
622 failedcmd @cmd unless $r =~ m/^[01]$/;
625 badcfg "unknown git-check \`$how'";
629 sub create_remote_git_repo () {
630 my $how = access_cfg('git-create');
631 if ($how eq 'ssh-cmd') {
633 (access_cfg('ssh'),access_gituserhost(),
634 "set -e; cd ".access_cfg('git-path').";".
635 " cp -a _template $package.git");
637 badcfg "unknown git-create \`$how'";
641 our ($dsc_hash,$lastpush_hash);
643 our $ud = '.git/dgit/unpack';
651 sub mktree_in_ud_from_only_subdir () {
652 # changes into the subdir
655 $dirs[0] =~ m#^([^/]+)/\.$# or die;
657 chdir $dir or die "$dir $!";
658 fail "source package contains .git directory" if stat '.git';
659 die $! unless $!==&ENOENT;
660 runcmd qw(git init -q);
661 rmtree('.git/objects');
662 symlink '../../../../objects','.git/objects' or die $!;
663 runcmd @git, qw(add -Af);
664 my $tree = cmdoutput @git, qw(write-tree);
665 $tree =~ m/^\w+$/ or die "$tree ?";
669 sub dsc_files_info () {
670 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
671 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
672 ['Files', 'Digest::MD5', 'new()']) {
673 my ($fname, $module, $method) = @$csumi;
674 my $field = $dsc->{$fname};
675 next unless defined $field;
676 eval "use $module; 1;" or die $@;
678 foreach (split /\n/, $field) {
680 m/^(\w+) (\d+) (\S+)$/ or
681 fail "could not parse .dsc $fname line \`$_'";
682 my $digester = eval "$module"."->$method;" or die $@;
687 Digester => $digester,
692 fail "missing any supported Checksums-* or Files field in ".
693 $dsc->get_option('name');
697 map { $_->{Filename} } dsc_files_info();
700 sub is_orig_file ($) {
702 m/\.orig(?:-\w+)?\.tar\.\w+$/;
705 sub make_commit ($) {
707 return cmdoutput @git, qw(hash-object -w -t commit), $file;
710 sub clogp_authline ($) {
712 my $author = getfield $clogp, 'Maintainer';
713 $author =~ s#,.*##ms;
714 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
715 my $authline = "$author $date";
716 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
717 fail "unexpected commit author line format \`$authline'".
718 " (was generated from changelog Maintainer field)";
722 sub generate_commit_from_dsc () {
726 foreach my $f (dsc_files()) {
727 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
729 link "../../../$f", $f
733 runcmd @dget, qw(--), $dscurl;
734 foreach my $f (grep { is_orig_file($_) } @files) {
735 link $f, "../../../../$f"
739 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
740 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
741 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
742 my $authline = clogp_authline $clogp;
743 my $changes = getfield $clogp, 'Changes';
744 open C, ">../commit.tmp" or die $!;
745 print C <<END or die $!;
752 # imported from the archive
755 my $outputhash = make_commit qw(../commit.tmp);
756 my $cversion = getfield $clogp, 'Version';
757 progress "synthesised git commit from .dsc $cversion";
758 if ($lastpush_hash) {
759 runcmd @git, qw(reset --hard), $lastpush_hash;
760 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
761 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
762 my $oversion = getfield $oldclogp, 'Version';
764 version_compare_string($oversion, $cversion);
766 # git upload/ is earlier vsn than archive, use archive
767 open C, ">../commit2.tmp" or die $!;
768 print C <<END or die $!;
770 parent $lastpush_hash
775 Record $package ($cversion) in archive suite $csuite
777 $outputhash = make_commit qw(../commit2.tmp);
778 } elsif ($vcmp > 0) {
779 print STDERR <<END or die $!;
781 Version actually in archive: $cversion (older)
782 Last allegedly pushed/uploaded: $oversion (newer or same)
785 $outputhash = $lastpush_hash;
787 $outputhash = $lastpush_hash;
790 chdir '../../../..' or die $!;
791 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
792 'DGIT_ARCHIVE', $outputhash;
793 cmdoutput @git, qw(log -n2), $outputhash;
794 # ... gives git a chance to complain if our commit is malformed
799 sub ensure_we_have_orig () {
800 foreach my $fi (dsc_files_info()) {
801 my $f = $fi->{Filename};
802 next unless is_orig_file($f);
803 if (open F, "<", "../$f") {
804 $fi->{Digester}->reset();
805 $fi->{Digester}->addfile(*F);
807 my $got = $fi->{Digester}->hexdigest();
808 $got eq $fi->{Hash} or
809 fail "existing file $f has hash $got but .dsc".
810 " demands hash $fi->{Hash}".
811 " (perhaps you should delete this file?)";
812 progress "using existing $f";
815 die "$f $!" unless $!==&ENOENT;
817 my $origurl = $dscurl;
818 $origurl =~ s{/[^/]+$}{};
820 die "$f ?" unless $f =~ m/^${package}_/;
821 die "$f ?" if $f =~ m#/#;
822 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
827 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
830 sub is_fast_fwd ($$) {
831 my ($ancestor,$child) = @_;
832 my @cmd = (@git, qw(merge-base), $ancestor, $child);
833 my $mb = cmdoutput_errok @cmd;
835 return rev_parse($mb) eq rev_parse($ancestor);
837 $?==256 or failedcmd @cmd;
842 sub git_fetch_us () {
843 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
846 sub fetch_from_archive () {
847 # ensures that lrref() is what is actually in the archive,
852 foreach my $field (@ourdscfield) {
853 $dsc_hash = $dsc->{$field};
854 last if defined $dsc_hash;
856 if (defined $dsc_hash) {
857 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
859 progress "last upload to archive specified git hash";
861 progress "last upload to archive has NO git hash";
864 progress "no version available from the archive";
867 my $lrref_fn = ".git/".lrref();
868 if (open H, $lrref_fn) {
869 $lastpush_hash = <H>;
870 chomp $lastpush_hash;
871 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
872 } elsif ($! == &ENOENT) {
877 print DEBUG "previous reference hash=$lastpush_hash\n";
879 if (defined $dsc_hash) {
880 fail "missing git history even though dsc has hash -".
881 " could not find commit $dsc_hash".
882 " (should be in ".access_giturl()."#".rrref().")"
883 unless $lastpush_hash;
885 ensure_we_have_orig();
886 if ($dsc_hash eq $lastpush_hash) {
887 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
888 print STDERR <<END or die $!;
890 Git commit in archive is behind the last version allegedly pushed/uploaded.
891 Commit referred to by archive: $dsc_hash
892 Last allegedly pushed/uploaded: $lastpush_hash
895 $hash = $lastpush_hash;
897 fail "archive's .dsc refers to ".$dsc_hash.
898 " but this is an ancestor of ".$lastpush_hash;
901 $hash = generate_commit_from_dsc();
902 } elsif ($lastpush_hash) {
903 # only in git, not in the archive yet
904 $hash = $lastpush_hash;
905 print STDERR <<END or die $!;
907 Package not found in the archive, but has allegedly been pushed using dgit.
911 print DEBUG "nothing found!\n";
912 if (defined $skew_warning_vsn) {
913 print STDERR <<END or die $!;
915 Warning: relevant archive skew detected.
916 Archive allegedly contains $skew_warning_vsn
917 But we were not able to obtain any version from the archive or git.
923 print DEBUG "current hash=$hash\n";
924 if ($lastpush_hash) {
925 fail "not fast forward on last upload branch!".
926 " (archive's version left in DGIT_ARCHIVE)"
927 unless is_fast_fwd($lastpush_hash, $hash);
929 if (defined $skew_warning_vsn) {
931 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
932 my $clogf = ".git/dgit/changelog.tmp";
933 runcmd shell_cmd "exec >$clogf",
934 @git, qw(cat-file blob), "$hash:debian/changelog";
935 my $gotclogp = parsechangelog("-l$clogf");
936 my $got_vsn = getfield $gotclogp, 'Version';
937 print DEBUG "SKEW CHECK GOT $got_vsn\n";
938 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
939 print STDERR <<END or die $!;
941 Warning: archive skew detected. Using the available version:
942 Archive allegedly contains $skew_warning_vsn
943 We were able to obtain only $got_vsn
948 if ($lastpush_hash ne $hash) {
949 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
953 dryrun_report @upd_cmd;
961 canonicalise_suite();
962 badusage "dry run makes no sense with clone" if $dryrun;
963 mkdir $dstdir or die "$dstdir $!";
964 chdir "$dstdir" or die "$dstdir $!";
965 runcmd @git, qw(init -q);
966 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
967 open H, "> .git/HEAD" or die $!;
968 print H "ref: ".lref()."\n" or die $!;
970 runcmd @git, qw(remote add), 'origin', access_giturl();
971 if (check_for_git()) {
972 progress "fetching existing git history";
974 runcmd_ordryrun @git, qw(fetch origin);
976 progress "starting new git history";
978 fetch_from_archive() or no_such_package;
979 runcmd @git, qw(reset --hard), lrref();
980 printdone "ready for work in $dstdir";
984 if (check_for_git()) {
987 fetch_from_archive() or no_such_package();
988 printdone "fetched into ".lrref();
993 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
995 printdone "fetched to ".lrref()." and merged into HEAD";
998 sub check_not_dirty () {
999 return if $ignoredirty;
1000 my @cmd = (@git, qw(diff --quiet HEAD));
1001 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1002 $!=0; $?=0; system @cmd;
1003 return if !$! && !$?;
1004 if (!$! && $?==256) {
1005 fail "working tree is dirty (does not match HEAD)";
1011 sub commit_quilty_patch () {
1012 my $output = cmdoutput @git, qw(status --porcelain);
1015 foreach my $l (split /\n/, $output) {
1016 next unless $l =~ m/\S/;
1017 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1020 print STDERR "git status: $l\n";
1024 fail "unexpected output from git status (is tree clean?)" if $bad;
1026 progress "nothing quilty to commit, ok.";
1029 runcmd_ordryrun @git, qw(add), sort keys %adds;
1030 my $m = "Commit Debian 3.0 (quilt) metadata";
1032 runcmd_ordryrun @git, qw(commit -m), $m;
1037 return 0 unless $format eq '3.0 (quilt)';
1038 progress "Format \`$format', urgh";
1040 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1046 sub push_parse_changelog ($) {
1049 my $clogp = Dpkg::Control::Hash->new();
1050 $clogp->load($clogpfn);
1052 $package = getfield $clogp, 'Source';
1053 my $cversion = getfield $clogp, 'Version';
1054 my $tag = debiantag($cversion);
1055 runcmd @git, qw(check-ref-format), $tag;
1057 my $dscfn = dscfn($cversion);
1059 return ($clogp, $cversion, $tag, $dscfn);
1062 sub push_parse_dsc ($$) {
1063 my ($dscfn,$dscfnwhat, $cversion) = @_;
1064 $dsc = parsecontrol($dscfn,$dscfnwhat);
1065 my $dversion = getfield $dsc, 'Version';
1066 my $dscpackage = getfield $dsc, 'Source';
1067 ($dscpackage eq $package && $dversion eq $cversion) or
1068 fail "$dsc is for $dscpackage $dversion".
1069 " but debian/changelog is for $package $cversion";
1072 sub push_mktag ($$$$$$$$) {
1073 my ($head,$clogp,$tag,
1075 $changesfile,$changesfilewhat,
1078 $dsc->{$ourdscfield[0]} = $head;
1079 $dsc->save("$dscfn.tmp") or die $!;
1081 my $changes = parsecontrol($changesfile,$changesfilewhat);
1082 foreach my $field (qw(Source Distribution Version)) {
1083 $changes->{$field} eq $clogp->{$field} or
1084 fail "changes field $field \`$changes->{$field}'".
1085 " does not match changelog \`$clogp->{$field}'";
1088 # We make the git tag by hand because (a) that makes it easier
1089 # to control the "tagger" (b) we can do remote signing
1090 my $authline = clogp_authline $clogp;
1091 open TO, '>', $tfn->('.tmp') or die $!;
1092 print TO <<END or die $!;
1098 $package release $cversion for $csuite [dgit]
1102 my $tagobjfn = $tfn->('.tmp');
1104 if (!defined $keyid) {
1105 $keyid = access_cfg('keyid','RETURN-UNDEF');
1107 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1108 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1109 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1110 push @sign_cmd, $tfn->('.tmp');
1111 runcmd_ordryrun @sign_cmd;
1113 $tagobjfn = $tfn->('.signed.tmp');
1114 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1115 $tfn->('.tmp'), $tfn->('.tmp.asc');
1123 print DEBUG "actually entering push\n";
1126 my $clogpfn = ".git/dgit/changelog.822.tmp";
1127 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1129 responder_send_file('parsed-changelog', $clogpfn);
1131 my ($clogp, $cversion, $tag, $dscfn) =
1132 push_parse_changelog("$clogpfn");
1135 fail "looked for .dsc $dscfn, but $!;".
1136 " maybe you forgot to build";
1138 responder_send_file('dsc', "../$dscfn");
1140 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1142 my $format = getfield $dsc, 'Format';
1143 print DEBUG "format $format\n";
1144 if (madformat($format)) {
1145 commit_quilty_patch();
1148 chdir $ud or die $!;
1149 progress "checking that $dscfn corresponds to HEAD";
1150 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1151 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1152 chdir '../../../..' or die $!;
1153 printcmd \*DEBUG,"+",@_;
1154 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1156 if (system @diffcmd) {
1157 if ($! && $?==256) {
1158 fail "$dscfn specifies a different tree to your HEAD commit;".
1159 " perhaps you forgot to build";
1165 #do fast forward check and maybe fake merge
1166 # if (!is_fast_fwd(mainbranch
1167 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1168 # map { lref($_).":".rref($_) }
1170 my $head = rev_parse('HEAD');
1171 if (!$changesfile) {
1172 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1173 if (stat "$multi") {
1174 $changesfile = $multi;
1176 $!==&ENOENT or die "$multi: $!";
1177 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1178 my @cs = glob "../$pat";
1179 fail "failed to find unique changes file".
1180 " (looked for $pat in .., or $multi);".
1181 " perhaps you need to use dgit -C"
1183 ($changesfile) = @cs;
1187 responder_send_file('changes',$changesfn);
1189 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1192 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1193 : push_mktag($head,$clogp,$tag,
1195 $changesfile,$changesfile,
1198 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1199 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1200 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1201 runcmd_ordryrun @git, qw(tag -v --), $tag;
1203 if (!check_for_git()) {
1204 create_remote_git_repo();
1206 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1207 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1209 if (!$we_are_responder) {
1211 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1213 progress "[new .dsc left in $dscfn.tmp]";
1218 if ($we_are_responder) {
1219 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1220 responder_receive_files('signed-changes-dsc',
1221 "$changesfile$dryrunsuffix",
1222 "../$dscfn$dryrunsuffix");
1224 my @debsign_cmd = @debsign;
1225 push @debsign_cmd, "-k$keyid" if defined $keyid;
1226 push @debsign_cmd, $changesfile;
1227 runcmd_ordryrun @debsign_cmd;
1230 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1231 my $host = access_cfg('upload-host','RETURN-UNDEF');
1232 my @hostarg = defined($host) ? ($host,) : ();
1233 runcmd_ordryrun @dput, @hostarg, $changesfile;
1234 printdone "pushed and uploaded $cversion";
1236 responder_send_command("complete");
1242 badusage "-p is not allowed with clone; specify as argument instead"
1243 if defined $package;
1246 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1247 ($package,$isuite) = @ARGV;
1248 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1249 ($package,$dstdir) = @ARGV;
1250 } elsif (@ARGV==3) {
1251 ($package,$isuite,$dstdir) = @ARGV;
1253 badusage "incorrect arguments to dgit clone";
1255 $dstdir ||= "$package";
1259 sub branchsuite () {
1260 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1261 if ($branch =~ m#$lbranch_re#o) {
1268 sub fetchpullargs () {
1269 if (!defined $package) {
1270 my $sourcep = parsecontrol('debian/control','debian/control');
1271 $package = getfield $sourcep, 'Source';
1274 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1276 my $clogp = parsechangelog();
1277 $isuite = getfield $clogp, 'Distribution';
1279 canonicalise_suite();
1280 progress "fetching from suite $csuite";
1281 } elsif (@ARGV==1) {
1283 canonicalise_suite();
1285 badusage "incorrect arguments to dgit fetch or dgit pull";
1303 badusage "-p is not allowed with dgit push" if defined $package;
1305 my $clogp = parsechangelog();
1306 $package = getfield $clogp, 'Source';
1309 } elsif (@ARGV==1) {
1310 ($specsuite) = (@ARGV);
1312 badusage "incorrect arguments to dgit push";
1314 $isuite = getfield $clogp, 'Distribution';
1316 local ($package) = $existing_package; # this is a hack
1317 canonicalise_suite();
1319 if (defined $specsuite && $specsuite ne $isuite) {
1320 canonicalise_suite();
1321 $csuite eq $specsuite or
1322 fail "dgit push: changelog specifies $isuite ($csuite)".
1323 " but command line specifies $specsuite";
1325 if (check_for_git()) {
1328 if (fetch_from_archive()) {
1329 is_fast_fwd(lrref(), 'HEAD') or
1330 fail "dgit push: HEAD is not a descendant".
1331 " of the archive's version.\n".
1332 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1335 fail "package appears to be new in this suite;".
1336 " if this is intentional, use --new";
1341 #---------- remote commands' implementation ----------
1343 sub cmd_remote_push_responder {
1344 my ($nrargs) = shift @ARGV;
1345 my (@rargs) = @ARGV[0..$nrargs-1];
1346 @ARGV = @ARGV[$nrargs..$#ARGV];
1349 chdir $dir or die "$dir: $!";
1352 responder_send_command("dgit-remote-push-ready");
1359 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1369 push @rdgit, @ropts;
1370 push @rdgit, (scalar @rargs), @rargs;
1372 my @cmd = (@ssh, $host, shellquote @rdgit);
1373 my $pid = open2(\*RO, \*RI, @cmd);
1374 initiator_expect { m/^dgit-remote-push-ready/ };
1376 initiator_expect { m/^(\S+)\s+(.*)$/ };
1377 my ($icmd,$iargs) = ($1, $2);
1379 { no strict qw(refs); &{"i_resp_$icmd"}($iargs); }
1383 #---------- building etc. ----------
1389 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1391 sub build_maybe_quilt_fixup () {
1392 if (!open F, "debian/source/format") {
1393 die $! unless $!==&ENOENT;
1397 F->error and die $!;
1399 return unless madformat($_);
1401 my $clogp = parsechangelog();
1402 my $version = getfield $clogp, 'Version';
1403 my $author = getfield $clogp, 'Maintainer';
1404 my $headref = rev_parse('HEAD');
1407 my $patchname = "auto-$version-$headref-$time";
1408 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1410 my $descfn = ".git/dgit/quilt-description.tmp";
1411 open O, '>', $descfn or die "$descfn: $!";
1413 $msg =~ s/^\s+$/ ./mg;
1414 print O <<END or die $!;
1415 Description: Automatically generated patch ($clogp->{Version})
1416 Last (up to) $ncommits git changes, FYI:
1426 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1427 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1428 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1429 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1432 if (!open P, '>>', ".pc/applied-patches") {
1433 $!==&ENOENT or die $!;
1438 commit_quilty_patch();
1441 sub quilt_fixup_editor () {
1442 my $descfn = $ENV{$fakeeditorenv};
1443 my $editing = $ARGV[$#ARGV];
1444 open I1, '<', $descfn or die "$descfn: $!";
1445 open I2, '<', $editing or die "$editing: $!";
1446 unlink $editing or die "$editing: $!";
1447 open O, '>', $editing or die "$editing: $!";
1448 while (<I1>) { print O or die $!; } I1->error and die $!;
1451 $copying ||= m/^\-\-\- /;
1452 next unless $copying;
1455 I2->error and die $!;
1461 badusage "-p is not allowed when building" if defined $package;
1463 my $clogp = parsechangelog();
1464 $isuite = getfield $clogp, 'Distribution';
1465 $package = getfield $clogp, 'Source';
1466 $version = getfield $clogp, 'Version';
1467 build_maybe_quilt_fixup();
1471 badusage "dgit build implies --clean=dpkg-source"
1472 if $cleanmode ne 'dpkg-source';
1474 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1475 printdone "build successful\n";
1479 badusage "dgit git-build implies --clean=dpkg-source"
1480 if $cleanmode ne 'dpkg-source';
1483 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1484 "--git-builder=@dpkgbuildpackage");
1485 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1486 canonicalise_suite();
1487 push @cmd, "--git-debian-branch=".lbranch();
1489 push @cmd, changesopts();
1490 runcmd_ordryrun @cmd, @ARGV;
1491 printdone "build successful\n";
1496 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1497 $dscfn = dscfn($version);
1498 if ($cleanmode eq 'dpkg-source') {
1499 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1501 if ($cleanmode eq 'git') {
1502 runcmd_ordryrun @git, qw(clean -xdf);
1503 } elsif ($cleanmode eq 'none') {
1507 my $pwd = cmdoutput qw(env - pwd);
1508 my $leafdir = basename $pwd;
1509 chdir ".." or die $!;
1510 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1511 chdir $pwd or die $!;
1512 runcmd_ordryrun qw(sh -ec),
1513 'exec >$1; shift; exec "$@"','x',
1514 "../$sourcechanges",
1515 @dpkggenchanges, qw(-S), changesopts();
1519 sub cmd_build_source {
1520 badusage "build-source takes no additional arguments" if @ARGV;
1522 printdone "source built, results in $dscfn and $sourcechanges";
1527 chdir ".." or die $!;
1528 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1530 stat $dscfn or fail "$dscfn (in parent directory): $!";
1531 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1532 foreach my $cf (glob $pat) {
1533 next if $cf eq $sourcechanges;
1534 unlink $cf or fail "remove $cf: $!";
1537 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1538 runcmd_ordryrun @mergechanges, glob $pat;
1539 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1541 stat $multichanges or fail "$multichanges: $!";
1543 printdone "build successful, results in $multichanges\n" or die $!;
1546 sub cmd_quilt_fixup {
1547 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1548 my $clogp = parsechangelog();
1549 $version = getfield $clogp, 'Version';
1550 build_maybe_quilt_fixup();
1553 #---------- argument parsing and main program ----------
1556 print "dgit version $our_version\n" or die $!;
1563 last unless $ARGV[0] =~ m/^-/;
1567 if (m/^--dry-run$/) {
1570 } elsif (m/^--no-sign$/) {
1573 } elsif (m/^--help$/) {
1575 } elsif (m/^--version$/) {
1577 } elsif (m/^--new$/) {
1580 } elsif (m/^--(\w+)=(.*)/s &&
1581 ($om = $opts_opt_map{$1}) &&
1585 } elsif (m/^--(\w+):(.*)/s &&
1586 ($om = $opts_opt_map{$1})) {
1589 } elsif (m/^--existing-package=(.*)/s) {
1591 $existing_package = $1;
1592 } elsif (m/^--distro=(.*)/s) {
1595 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1598 } elsif (m/^--clean=(.*)$/s) {
1599 badusage "unknown cleaning mode \`$1'";
1600 } elsif (m/^--ignore-dirty$/s) {
1603 } elsif (m/^--no-quilt-fixup$/s) {
1607 badusage "unknown long option \`$_'";
1614 } elsif (s/^-h/-/) {
1616 } elsif (s/^-D/-/) {
1618 open DEBUG, ">&STDERR" or die $!;
1620 } elsif (s/^-N/-/) {
1623 } elsif (m/^-[vm]/) {
1625 push @changesopts, $_;
1627 } elsif (s/^-c(.*=.*)//s) {
1629 push @git, '-c', $1;
1630 } elsif (s/^-d(.*)//s) {
1633 } elsif (s/^-C(.*)//s) {
1636 } elsif (s/^-k(.*)//s) {
1638 } elsif (s/^-wn//s) {
1640 $cleanmode = 'none';
1641 } elsif (s/^-wg//s) {
1644 } elsif (s/^-wd//s) {
1646 $cleanmode = 'dpkg-source';
1648 badusage "unknown short option \`$_'";
1655 if ($ENV{$fakeeditorenv}) {
1656 quilt_fixup_editor();
1659 delete $ENV{'DGET_UNPACK'};
1662 print STDERR "DRY RUN ONLY\n" if $dryrun;
1664 print STDERR $helpmsg or die $!;
1667 my $cmd = shift @ARGV;
1669 { no strict qw(refs); &{"cmd_$cmd"}(); }