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_read_bytes ($$) {
195 my ($fh, $nbytes) = @_;
196 $nbytes =~ m/^\d{1,6}$/ or badproto \*RO, "bad byte count";
198 my $got = read $fh, $d, $nbytes;
199 $got==$nbytes or badproto $fh, "eof during data block";
203 sub protocol_receive_file ($$) {
204 my ($fh, $ourfn) = @_;
205 open PF, ">", $ourfn or die "$ourfn: $!";
207 protocol_expect \*STDIN, { m/^data-block (.*})$|data-end$/ };
209 my $d = protocol_read_bytes \*STDIN, $1;
210 print PF $d or die $!;
214 #---------- remote protocol support, responder ----------
216 sub responder_send_command ($) {
218 return unless $we_are_responder;
219 # called even without $we_are_responder
220 print DEBUG "<< $command\n";
221 print $command, "\n" or die $!;
224 sub responder_send_file ($$) {
225 my ($keyword, $ourfn) = @_;
226 return unless $we_are_responder;
227 responder_send_command "file begin $cmdprefix";
228 protocol_send_file \*STDOUT, $ourfn;
231 sub responder_receive_files ($@) {
232 my ($keyword, @ourfns) = @_;
233 die unless $we_are_responder;
234 responder_send_command "want $keyword";
235 foreach my $fn (@ourfns) {
236 protocol_receive_file \*STDIN, $fn;
238 protocol_expect \*STDIN, { m/^files-end$/ };
241 #---------- remote protocol support, initiator ----------
243 sub initiator_expect (&) {
245 protocol_expect \*RO, &$match;
248 #---------- end remote code ----------
251 if ($we_are_responder) {
253 responder_send_command "progress ".length($m) or die $!;
264 $ua = LWP::UserAgent->new();
268 progress "downloading $what...";
269 my $r = $ua->get(@_) or die $!;
270 return undef if $r->code == 404;
271 $r->is_success or fail "failed to fetch $what: ".$r->status_line;
272 return $r->decoded_content();
275 our ($dscdata,$dscurl,$dsc,$skew_warning_vsn);
282 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
288 return join '', @out;
293 my $intro = shift @_;
294 print $fh $intro or die $!;
295 print $fh shellquote @_ or die $!;
296 print $fh "\n" or die $!;
300 { local ($!); printcmd \*STDERR, "$_[0]: failed command:", @_ or die $!; };
302 fail "failed to fork/exec: $!";
303 } elsif (!($? & 0xff)) {
304 fail "subprocess failed with error exit status ".($?>>8);
306 fail "subprocess crashed (wait status $?)";
308 fail "subprocess produced invalid output";
313 printcmd(\*DEBUG,"+",@_) if $debug>0;
315 failedcmd @_ if system @_;
320 progress "dgit ok: @_";
322 progress "would be ok: @_ (but dry run only)";
326 sub cmdoutput_errok {
327 die Dumper(\@_)." ?" if grep { !defined } @_;
328 printcmd(\*DEBUG,"|",@_) if $debug>0;
329 open P, "-|", @_ or die $!;
332 { local $/ = undef; $d = <P>; }
334 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
337 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
342 my $d = cmdoutput_errok @_;
343 defined $d or failedcmd @_;
348 printcmd(\*STDERR,"#",@_);
351 sub runcmd_ordryrun {
360 my ($first_shell, @cmd) = @_;
361 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
364 our $helpmsg = <<END;
366 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
367 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
368 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
369 dgit [dgit-opts] push [dgit-opts] [suite]
370 important dgit options:
371 -k<keyid> sign tag and package with <keyid> instead of default
372 --dry-run -n do not change anything, but go through the motions
373 --new -N allow introducing a new package
374 --debug -D increase debug level
375 -c<name>=<value> set git config option (used directly by dgit too)
378 our $later_warning_msg = <<END;
379 Perhaps the upload is stuck in incoming. Using the version from git.
383 print STDERR "$us: @_\n", $helpmsg or die $!;
388 @ARGV or badusage "too few arguments";
389 return scalar shift @ARGV;
393 print $helpmsg or die $!;
397 our %defcfg = ('dgit.default.distro' => 'debian',
398 'dgit.default.username' => '',
399 'dgit.default.archive-query-default-component' => 'main',
400 'dgit.default.ssh' => 'ssh',
401 'dgit-distro.debian.git-host' => 'git.debian.org',
402 'dgit-distro.debian.git-proto' => 'git+ssh://',
403 'dgit-distro.debian.git-path' => '/git/dgit-repos/repos',
404 'dgit-distro.debian.git-check' => 'ssh-cmd',
405 'dgit-distro.debian.git-create' => 'ssh-cmd',
406 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
407 'dgit-distro.debian.sshdakls-dir' =>
408 '/srv/ftp-master.debian.org/ftp/dists',
409 'dgit-distro.debian.upload-host' => 'ftp-master', # for dput
410 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
414 return undef if $c =~ /RETURN-UNDEF/;
415 my @cmd = (@git, qw(config --), $c);
418 local ($debug) = $debug-1;
419 $v = cmdoutput_errok @cmd;
426 my $dv = $defcfg{$c};
427 return $dv if defined $dv;
429 badcfg "need value for one of: @_";
432 sub access_distro () {
433 return cfg("dgit-suite.$isuite.distro",
434 "dgit.default.distro");
439 my $distro = $idistro || access_distro();
440 my $value = cfg(map { ("dgit-distro.$distro.$_",
441 "dgit.default.$_") } @keys);
445 sub access_someuserhost ($) {
447 my $user = access_cfg("$some-user",'username');
448 my $host = access_cfg("$some-host");
449 return length($user) ? "$user\@$host" : $host;
452 sub access_gituserhost () {
453 return access_someuserhost('git');
456 sub access_giturl () {
457 my $url = access_cfg('git-url','RETURN-UNDEF');
460 access_cfg('git-proto').
461 access_gituserhost().
462 access_cfg('git-path');
464 return "$url/$package.git";
467 sub parsecontrolfh ($$@) {
468 my ($fh, $desc, @opts) = @_;
469 my %opts = ('name' => $desc, @opts);
470 my $c = Dpkg::Control::Hash->new(%opts);
471 $c->parse($fh) or die "parsing of $desc failed";
476 my ($file, $desc) = @_;
477 my $fh = new IO::Handle;
478 open $fh, '<', $file or die "$file: $!";
479 my $c = parsecontrolfh($fh,$desc);
480 $fh->error and die $!;
486 my ($dctrl,$field) = @_;
487 my $v = $dctrl->{$field};
488 return $v if defined $v;
489 fail "missing field $field in ".$v->get_option('name');
493 my $c = Dpkg::Control::Hash->new();
494 my $p = new IO::Handle;
495 my @cmd = (qw(dpkg-parsechangelog), @_);
496 open $p, '-|', @cmd or die $!;
498 $?=0; $!=0; close $p or failedcmd @cmd;
504 sub archive_query ($) {
506 my $query = access_cfg('archive-query','RETURN-UNDEF');
507 if (!defined $query) {
508 my $distro = access_distro();
509 if ($distro eq 'debian') {
510 $query = "sshdakls:".
511 access_someuserhost('sshdakls').':'.
512 access_cfg('sshdakls-dir');
514 $query = "madison:$distro";
517 $query =~ s/^(\w+):// or badcfg "invalid archive-query method \`$query'";
520 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
523 sub archive_query_madison ($$) {
524 my ($proto,$data) = @_;
525 die unless $proto eq 'madison';
526 $rmad{$package} ||= cmdoutput
527 qw(rmadison -asource),"-s$isuite","-u$data",$package;
528 my $rmad = $rmad{$package};
529 return madison_parse($rmad);
532 sub archive_query_sshdakls ($$) {
533 my ($proto,$data) = @_;
534 $data =~ s/:.*// or badcfg "invalid sshdakls method string \`$data'";
535 my $dakls = cmdoutput
536 access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
537 return madison_parse($dakls);
540 sub canonicalise_suite_sshdakls ($$) {
541 my ($proto,$data) = @_;
542 $data =~ m/:/ or badcfg "invalid sshdakls method string \`$data'";
544 (access_cfg('ssh'), $`,
546 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
547 " if test -d $isuite; then echo $isuite; exit 0; fi;".
549 my $dakls = cmdoutput @cmd;
550 failedcmd @cmd unless $dakls =~ m/^\w/;
554 sub madison_parse ($) {
557 foreach my $l (split /\n/, $rmad) {
558 $l =~ m{^ \s*( [^ \t|]+ )\s* \|
559 \s*( [^ \t|]+ )\s* \|
560 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
561 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
562 $1 eq $package or die "$rmad $package ?";
569 $component = access_cfg('archive-query-default-component');
571 $5 eq 'source' or die "$rmad ?";
572 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
573 my $subpath = "/pool/$component/$prefix/$package/".dscfn($vsn);
574 push @out, [$vsn,$subpath,$newsuite];
576 return sort { -version_compare_string($a->[0],$b->[0]); } @out;
579 sub canonicalise_suite_madison ($$) {
580 my @r = archive_query_madison($_[0],$_[1]);
582 "unable to canonicalise suite using package $package".
583 " which does not appear to exist in suite $isuite;".
584 " --existing-package may help";
588 sub canonicalise_suite () {
589 return if defined $csuite;
590 fail "cannot operate on $isuite suite" if $isuite eq 'UNRELEASED';
591 $csuite = archive_query('canonicalise_suite');
592 if ($isuite ne $csuite) {
593 # madison canonicalises for us
594 progress "canonical suite name for $isuite is $csuite";
598 sub get_archive_dsc () {
599 canonicalise_suite();
600 my @vsns = archive_query('archive_query');
601 foreach my $vinfo (@vsns) {
602 my ($vsn,$subpath) = @$vinfo;
603 $dscurl = access_cfg('mirror').$subpath;
604 $dscdata = url_get($dscurl);
606 $skew_warning_vsn = $vsn if !defined $skew_warning_vsn;
609 my $dscfh = new IO::File \$dscdata, '<' or die $!;
610 print DEBUG Dumper($dscdata) if $debug>1;
611 $dsc = parsecontrolfh($dscfh,$dscurl, allow_pgp=>1);
612 print DEBUG Dumper($dsc) if $debug>1;
613 my $fmt = getfield $dsc, 'Format';
614 fail "unsupported source format $fmt, sorry" unless $format_ok{$fmt};
620 sub check_for_git () {
622 my $how = access_cfg('git-check');
623 if ($how eq 'ssh-cmd') {
625 (access_cfg('ssh'),access_gituserhost(),
626 " set -e; cd ".access_cfg('git-path').";".
627 " if test -d $package.git; then echo 1; else echo 0; fi");
628 my $r= cmdoutput @cmd;
629 failedcmd @cmd unless $r =~ m/^[01]$/;
632 badcfg "unknown git-check \`$how'";
636 sub create_remote_git_repo () {
637 my $how = access_cfg('git-create');
638 if ($how eq 'ssh-cmd') {
640 (access_cfg('ssh'),access_gituserhost(),
641 "set -e; cd ".access_cfg('git-path').";".
642 " cp -a _template $package.git");
644 badcfg "unknown git-create \`$how'";
648 our ($dsc_hash,$lastpush_hash);
650 our $ud = '.git/dgit/unpack';
658 sub mktree_in_ud_from_only_subdir () {
659 # changes into the subdir
662 $dirs[0] =~ m#^([^/]+)/\.$# or die;
664 chdir $dir or die "$dir $!";
665 fail "source package contains .git directory" if stat '.git';
666 die $! unless $!==&ENOENT;
667 runcmd qw(git init -q);
668 rmtree('.git/objects');
669 symlink '../../../../objects','.git/objects' or die $!;
670 runcmd @git, qw(add -Af);
671 my $tree = cmdoutput @git, qw(write-tree);
672 $tree =~ m/^\w+$/ or die "$tree ?";
676 sub dsc_files_info () {
677 foreach my $csumi (['Checksums-Sha256','Digest::SHA', 'new(256)'],
678 ['Checksums-Sha1', 'Digest::SHA', 'new(1)'],
679 ['Files', 'Digest::MD5', 'new()']) {
680 my ($fname, $module, $method) = @$csumi;
681 my $field = $dsc->{$fname};
682 next unless defined $field;
683 eval "use $module; 1;" or die $@;
685 foreach (split /\n/, $field) {
687 m/^(\w+) (\d+) (\S+)$/ or
688 fail "could not parse .dsc $fname line \`$_'";
689 my $digester = eval "$module"."->$method;" or die $@;
694 Digester => $digester,
699 fail "missing any supported Checksums-* or Files field in ".
700 $dsc->get_option('name');
704 map { $_->{Filename} } dsc_files_info();
707 sub is_orig_file ($) {
709 m/\.orig(?:-\w+)?\.tar\.\w+$/;
712 sub make_commit ($) {
714 return cmdoutput @git, qw(hash-object -w -t commit), $file;
717 sub clogp_authline ($) {
719 my $author = getfield $clogp, 'Maintainer';
720 $author =~ s#,.*##ms;
721 my $date = cmdoutput qw(date), '+%s %z', qw(-d), getfield($clogp,'Date');
722 my $authline = "$author $date";
723 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or
724 fail "unexpected commit author line format \`$authline'".
725 " (was generated from changelog Maintainer field)";
729 sub generate_commit_from_dsc () {
733 foreach my $f (dsc_files()) {
734 die "$f ?" if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
736 link "../../../$f", $f
740 runcmd @dget, qw(--), $dscurl;
741 foreach my $f (grep { is_orig_file($_) } @files) {
742 link $f, "../../../../$f"
746 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
747 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
748 my $clogp = parsecontrol('../changelog.tmp',"commit's changelog");
749 my $authline = clogp_authline $clogp;
750 my $changes = getfield $clogp, 'Changes';
751 open C, ">../commit.tmp" or die $!;
752 print C <<END or die $!;
759 # imported from the archive
762 my $outputhash = make_commit qw(../commit.tmp);
763 my $cversion = getfield $clogp, 'Version';
764 progress "synthesised git commit from .dsc $cversion";
765 if ($lastpush_hash) {
766 runcmd @git, qw(reset --hard), $lastpush_hash;
767 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
768 my $oldclogp = parsecontrol('../changelogold.tmp','previous changelog');
769 my $oversion = getfield $oldclogp, 'Version';
771 version_compare_string($oversion, $cversion);
773 # git upload/ is earlier vsn than archive, use archive
774 open C, ">../commit2.tmp" or die $!;
775 print C <<END or die $!;
777 parent $lastpush_hash
782 Record $package ($cversion) in archive suite $csuite
784 $outputhash = make_commit qw(../commit2.tmp);
785 } elsif ($vcmp > 0) {
786 print STDERR <<END or die $!;
788 Version actually in archive: $cversion (older)
789 Last allegedly pushed/uploaded: $oversion (newer or same)
792 $outputhash = $lastpush_hash;
794 $outputhash = $lastpush_hash;
797 chdir '../../../..' or die $!;
798 runcmd @git, qw(update-ref -m),"dgit fetch import $cversion",
799 'DGIT_ARCHIVE', $outputhash;
800 cmdoutput @git, qw(log -n2), $outputhash;
801 # ... gives git a chance to complain if our commit is malformed
806 sub ensure_we_have_orig () {
807 foreach my $fi (dsc_files_info()) {
808 my $f = $fi->{Filename};
809 next unless is_orig_file($f);
810 if (open F, "<", "../$f") {
811 $fi->{Digester}->reset();
812 $fi->{Digester}->addfile(*F);
814 my $got = $fi->{Digester}->hexdigest();
815 $got eq $fi->{Hash} or
816 fail "existing file $f has hash $got but .dsc".
817 " demands hash $fi->{Hash}".
818 " (perhaps you should delete this file?)";
819 progress "using existing $f";
822 die "$f $!" unless $!==&ENOENT;
824 my $origurl = $dscurl;
825 $origurl =~ s{/[^/]+$}{};
827 die "$f ?" unless $f =~ m/^${package}_/;
828 die "$f ?" if $f =~ m#/#;
829 runcmd_ordryrun shell_cmd 'cd ..', @dget,'--',$origurl;
834 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
837 sub is_fast_fwd ($$) {
838 my ($ancestor,$child) = @_;
839 my @cmd = (@git, qw(merge-base), $ancestor, $child);
840 my $mb = cmdoutput_errok @cmd;
842 return rev_parse($mb) eq rev_parse($ancestor);
844 $?==256 or failedcmd @cmd;
849 sub git_fetch_us () {
850 runcmd_ordryrun @git, qw(fetch),access_giturl(),fetchspec();
853 sub fetch_from_archive () {
854 # ensures that lrref() is what is actually in the archive,
859 foreach my $field (@ourdscfield) {
860 $dsc_hash = $dsc->{$field};
861 last if defined $dsc_hash;
863 if (defined $dsc_hash) {
864 $dsc_hash =~ m/\w+/ or fail "invalid hash in .dsc \`$dsc_hash'";
866 progress "last upload to archive specified git hash";
868 progress "last upload to archive has NO git hash";
871 progress "no version available from the archive";
874 my $lrref_fn = ".git/".lrref();
875 if (open H, $lrref_fn) {
876 $lastpush_hash = <H>;
877 chomp $lastpush_hash;
878 die "$lrref_fn $lastpush_hash ?" unless $lastpush_hash =~ m/^\w+$/;
879 } elsif ($! == &ENOENT) {
884 print DEBUG "previous reference hash=$lastpush_hash\n";
886 if (defined $dsc_hash) {
887 fail "missing git history even though dsc has hash -".
888 " could not find commit $dsc_hash".
889 " (should be in ".access_giturl()."#".rrref().")"
890 unless $lastpush_hash;
892 ensure_we_have_orig();
893 if ($dsc_hash eq $lastpush_hash) {
894 } elsif (is_fast_fwd($dsc_hash,$lastpush_hash)) {
895 print STDERR <<END or die $!;
897 Git commit in archive is behind the last version allegedly pushed/uploaded.
898 Commit referred to by archive: $dsc_hash
899 Last allegedly pushed/uploaded: $lastpush_hash
902 $hash = $lastpush_hash;
904 fail "archive's .dsc refers to ".$dsc_hash.
905 " but this is an ancestor of ".$lastpush_hash;
908 $hash = generate_commit_from_dsc();
909 } elsif ($lastpush_hash) {
910 # only in git, not in the archive yet
911 $hash = $lastpush_hash;
912 print STDERR <<END or die $!;
914 Package not found in the archive, but has allegedly been pushed using dgit.
918 print DEBUG "nothing found!\n";
919 if (defined $skew_warning_vsn) {
920 print STDERR <<END or die $!;
922 Warning: relevant archive skew detected.
923 Archive allegedly contains $skew_warning_vsn
924 But we were not able to obtain any version from the archive or git.
930 print DEBUG "current hash=$hash\n";
931 if ($lastpush_hash) {
932 fail "not fast forward on last upload branch!".
933 " (archive's version left in DGIT_ARCHIVE)"
934 unless is_fast_fwd($lastpush_hash, $hash);
936 if (defined $skew_warning_vsn) {
938 print DEBUG "SKEW CHECK WANT $skew_warning_vsn\n";
939 my $clogf = ".git/dgit/changelog.tmp";
940 runcmd shell_cmd "exec >$clogf",
941 @git, qw(cat-file blob), "$hash:debian/changelog";
942 my $gotclogp = parsechangelog("-l$clogf");
943 my $got_vsn = getfield $gotclogp, 'Version';
944 print DEBUG "SKEW CHECK GOT $got_vsn\n";
945 if (version_compare_string($got_vsn, $skew_warning_vsn) < 0) {
946 print STDERR <<END or die $!;
948 Warning: archive skew detected. Using the available version:
949 Archive allegedly contains $skew_warning_vsn
950 We were able to obtain only $got_vsn
955 if ($lastpush_hash ne $hash) {
956 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
960 dryrun_report @upd_cmd;
968 canonicalise_suite();
969 badusage "dry run makes no sense with clone" if $dryrun;
970 mkdir $dstdir or die "$dstdir $!";
971 chdir "$dstdir" or die "$dstdir $!";
972 runcmd @git, qw(init -q);
973 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
974 open H, "> .git/HEAD" or die $!;
975 print H "ref: ".lref()."\n" or die $!;
977 runcmd @git, qw(remote add), 'origin', access_giturl();
978 if (check_for_git()) {
979 progress "fetching existing git history";
981 runcmd_ordryrun @git, qw(fetch origin);
983 progress "starting new git history";
985 fetch_from_archive() or no_such_package;
986 runcmd @git, qw(reset --hard), lrref();
987 printdone "ready for work in $dstdir";
991 if (check_for_git()) {
994 fetch_from_archive() or no_such_package();
995 printdone "fetched into ".lrref();
1000 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
1002 printdone "fetched to ".lrref()." and merged into HEAD";
1005 sub check_not_dirty () {
1006 return if $ignoredirty;
1007 my @cmd = (@git, qw(diff --quiet HEAD));
1008 printcmd(\*DEBUG,"+",@cmd) if $debug>0;
1009 $!=0; $?=0; system @cmd;
1010 return if !$! && !$?;
1011 if (!$! && $?==256) {
1012 fail "working tree is dirty (does not match HEAD)";
1018 sub commit_quilty_patch () {
1019 my $output = cmdoutput @git, qw(status --porcelain);
1022 foreach my $l (split /\n/, $output) {
1023 next unless $l =~ m/\S/;
1024 if ($l =~ m{^(?:\?\?| M) (.pc|debian/patches)}) {
1027 print STDERR "git status: $l\n";
1031 fail "unexpected output from git status (is tree clean?)" if $bad;
1033 progress "nothing quilty to commit, ok.";
1036 runcmd_ordryrun @git, qw(add), sort keys %adds;
1037 my $m = "Commit Debian 3.0 (quilt) metadata";
1039 runcmd_ordryrun @git, qw(commit -m), $m;
1044 return 0 unless $format eq '3.0 (quilt)';
1045 progress "Format \`$format', urgh";
1047 progress "Not doing any fixup of \`$format' due to --no-quilt-fixup";
1053 sub push_parse_changelog ($) {
1056 my $clogp = Dpkg::Control::Hash->new();
1057 $clogp->load($clogpfn);
1059 $package = getfield $clogp, 'Source';
1060 my $cversion = getfield $clogp, 'Version';
1061 my $tag = debiantag($cversion);
1062 runcmd @git, qw(check-ref-format), $tag;
1064 my $dscfn = dscfn($cversion);
1066 return ($clogp, $cversion, $tag, $dscfn);
1069 sub push_parse_dsc ($$) {
1070 my ($dscfn,$dscfnwhat, $cversion) = @_;
1071 $dsc = parsecontrol($dscfn,$dscfnwhat);
1072 my $dversion = getfield $dsc, 'Version';
1073 my $dscpackage = getfield $dsc, 'Source';
1074 ($dscpackage eq $package && $dversion eq $cversion) or
1075 fail "$dsc is for $dscpackage $dversion".
1076 " but debian/changelog is for $package $cversion";
1079 sub push_mktag ($$$$$$$$) {
1080 my ($head,$clogp,$tag,
1082 $changesfile,$changesfilewhat,
1085 $dsc->{$ourdscfield[0]} = $head;
1086 $dsc->save("$dscfn.tmp") or die $!;
1088 my $changes = parsecontrol($changesfile,$changesfilewhat);
1089 foreach my $field (qw(Source Distribution Version)) {
1090 $changes->{$field} eq $clogp->{$field} or
1091 fail "changes field $field \`$changes->{$field}'".
1092 " does not match changelog \`$clogp->{$field}'";
1095 # We make the git tag by hand because (a) that makes it easier
1096 # to control the "tagger" (b) we can do remote signing
1097 my $authline = clogp_authline $clogp;
1098 open TO, '>', $tfn->('.tmp') or die $!;
1099 print TO <<END or die $!;
1105 $package release $cversion for $csuite [dgit]
1109 my $tagobjfn = $tfn->('.tmp');
1111 if (!defined $keyid) {
1112 $keyid = access_cfg('keyid','RETURN-UNDEF');
1114 unlink $tfn->('.tmp.asc') or $!==&ENOENT or die $!;
1115 my @sign_cmd = (@gpg, qw(--detach-sign --armor));
1116 push @sign_cmd, qw(-u),$keyid if defined $keyid;
1117 push @sign_cmd, $tfn->('.tmp');
1118 runcmd_ordryrun @sign_cmd;
1120 $tagobjfn = $tfn->('.signed.tmp');
1121 runcmd shell_cmd "exec >$tagobjfn", qw(cat --),
1122 $tfn->('.tmp'), $tfn->('.tmp.asc');
1130 print DEBUG "actually entering push\n";
1133 my $clogpfn = ".git/dgit/changelog.822.tmp";
1134 runcmd shell_cmd "exec >$clogpfn", qw(dpkg-parsechangelog);
1136 responder_send_file('parsed-changelog', $clogpfn);
1138 my ($clogp, $cversion, $tag, $dscfn) =
1139 push_parse_changelog("$clogpfn");
1142 fail "looked for .dsc $dscfn, but $!;".
1143 " maybe you forgot to build";
1145 responder_send_file('dsc', "../$dscfn");
1147 push_parse_dsc("../$dscfn", $dscfn, $cversion);
1149 my $format = getfield $dsc, 'Format';
1150 print DEBUG "format $format\n";
1151 if (madformat($format)) {
1152 commit_quilty_patch();
1155 chdir $ud or die $!;
1156 progress "checking that $dscfn corresponds to HEAD";
1157 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
1158 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
1159 chdir '../../../..' or die $!;
1160 printcmd \*DEBUG,"+",@_;
1161 my @diffcmd = (@git, qw(diff --exit-code), $tree);
1163 if (system @diffcmd) {
1164 if ($! && $?==256) {
1165 fail "$dscfn specifies a different tree to your HEAD commit;".
1166 " perhaps you forgot to build";
1172 #do fast forward check and maybe fake merge
1173 # if (!is_fast_fwd(mainbranch
1174 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
1175 # map { lref($_).":".rref($_) }
1177 my $head = rev_parse('HEAD');
1178 if (!$changesfile) {
1179 my $multi = "../${package}_".(stripepoch $cversion)."_multi.changes";
1180 if (stat "$multi") {
1181 $changesfile = $multi;
1183 $!==&ENOENT or die "$multi: $!";
1184 my $pat = "${package}_".(stripepoch $cversion)."_*.changes";
1185 my @cs = glob "../$pat";
1186 fail "failed to find unique changes file".
1187 " (looked for $pat in .., or $multi);".
1188 " perhaps you need to use dgit -C"
1190 ($changesfile) = @cs;
1194 responder_send_file('changes',$changesfn);
1196 my $tfn = sub { ".git/dgit/tag$_[0]"; };
1199 ? responder_receive_files('signed-tag', $tfn->('.signed.tmp'))
1200 : push_mktag($head,$clogp,$tag,
1202 $changesfile,$changesfile,
1205 my $tag_obj_hash = cmdoutput @git, qw(hash-object -w -t tag), $tagobjfn;
1206 runcmd_ordryrun @git, qw(verify-tag), $tag_obj_hash;
1207 runcmd_ordryrun @git, qw(update-ref), "refs/tags/$tag", $tag_obj_hash;
1208 runcmd_ordryrun @git, qw(tag -v --), $tag;
1210 if (!check_for_git()) {
1211 create_remote_git_repo();
1213 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
1214 runcmd_ordryrun @git, qw(update-ref -m), 'dgit push', lrref(), 'HEAD';
1216 if (!$we_are_responder) {
1218 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
1220 progress "[new .dsc left in $dscfn.tmp]";
1225 if ($we_are_responder) {
1226 my $dryrunsuffix = $dryrun ? ".tmp" : "";
1227 responder_receive_files('signed-changes-dsc',
1228 "$changesfile$dryrunsuffix",
1229 "../$dscfn$dryrunsuffix");
1231 my @debsign_cmd = @debsign;
1232 push @debsign_cmd, "-k$keyid" if defined $keyid;
1233 push @debsign_cmd, $changesfile;
1234 runcmd_ordryrun @debsign_cmd;
1237 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
1238 my $host = access_cfg('upload-host','RETURN-UNDEF');
1239 my @hostarg = defined($host) ? ($host,) : ();
1240 runcmd_ordryrun @dput, @hostarg, $changesfile;
1241 printdone "pushed and uploaded $cversion";
1243 responder_send_command("complete");
1249 badusage "-p is not allowed with clone; specify as argument instead"
1250 if defined $package;
1253 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
1254 ($package,$isuite) = @ARGV;
1255 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
1256 ($package,$dstdir) = @ARGV;
1257 } elsif (@ARGV==3) {
1258 ($package,$isuite,$dstdir) = @ARGV;
1260 badusage "incorrect arguments to dgit clone";
1262 $dstdir ||= "$package";
1266 sub branchsuite () {
1267 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
1268 if ($branch =~ m#$lbranch_re#o) {
1275 sub fetchpullargs () {
1276 if (!defined $package) {
1277 my $sourcep = parsecontrol('debian/control','debian/control');
1278 $package = getfield $sourcep, 'Source';
1281 # $isuite = branchsuite(); # this doesn't work because dak hates canons
1283 my $clogp = parsechangelog();
1284 $isuite = getfield $clogp, 'Distribution';
1286 canonicalise_suite();
1287 progress "fetching from suite $csuite";
1288 } elsif (@ARGV==1) {
1290 canonicalise_suite();
1292 badusage "incorrect arguments to dgit fetch or dgit pull";
1310 badusage "-p is not allowed with dgit push" if defined $package;
1312 my $clogp = parsechangelog();
1313 $package = getfield $clogp, 'Source';
1316 } elsif (@ARGV==1) {
1317 ($specsuite) = (@ARGV);
1319 badusage "incorrect arguments to dgit push";
1321 $isuite = getfield $clogp, 'Distribution';
1323 local ($package) = $existing_package; # this is a hack
1324 canonicalise_suite();
1326 if (defined $specsuite && $specsuite ne $isuite) {
1327 canonicalise_suite();
1328 $csuite eq $specsuite or
1329 fail "dgit push: changelog specifies $isuite ($csuite)".
1330 " but command line specifies $specsuite";
1332 if (check_for_git()) {
1335 if (fetch_from_archive()) {
1336 is_fast_fwd(lrref(), 'HEAD') or
1337 fail "dgit push: HEAD is not a descendant".
1338 " of the archive's version.\n".
1339 "$us: To overwrite it, use git-merge -s ours ".lrref().".";
1342 fail "package appears to be new in this suite;".
1343 " if this is intentional, use --new";
1348 #---------- remote commands' implementation ----------
1350 sub cmd_remote_push_responder {
1351 my ($nrargs) = shift @ARGV;
1352 my (@rargs) = @ARGV[0..$nrargs-1];
1353 @ARGV = @ARGV[$nrargs..$#ARGV];
1356 chdir $dir or die "$dir: $!";
1359 responder_send_command("dgit-remote-push-ready");
1366 if ($host =~ m/^((?:[^][]|\[[^][]*\])*)\:/) {
1376 push @rdgit, @ropts;
1377 push @rdgit, (scalar @rargs), @rargs;
1379 my @cmd = (@ssh, $host, shellquote @rdgit);
1380 my $pid = open2(\*RO, \*RI, @cmd);
1381 initiator_expect { m/^dgit-remote-push-ready/ };
1383 initiator_expect { m/^(\S+)\s+(.*)$/ };
1384 my ($icmd,$iargs) = ($1, $2);
1386 { no strict qw(refs); &{"i_resp_$icmd"}($iargs); }
1390 #---------- building etc. ----------
1396 our $fakeeditorenv = 'DGIT_FAKE_EDITOR_QUILT';
1398 sub build_maybe_quilt_fixup () {
1399 if (!open F, "debian/source/format") {
1400 die $! unless $!==&ENOENT;
1404 F->error and die $!;
1406 return unless madformat($_);
1408 my $clogp = parsechangelog();
1409 my $version = getfield $clogp, 'Version';
1410 my $author = getfield $clogp, 'Maintainer';
1411 my $headref = rev_parse('HEAD');
1414 my $patchname = "auto-$version-$headref-$time";
1415 my $msg = cmdoutput @git, qw(log), "-n$ncommits";
1417 my $descfn = ".git/dgit/quilt-description.tmp";
1418 open O, '>', $descfn or die "$descfn: $!";
1420 $msg =~ s/^\s+$/ ./mg;
1421 print O <<END or die $!;
1422 Description: Automatically generated patch ($clogp->{Version})
1423 Last (up to) $ncommits git changes, FYI:
1433 local $ENV{'EDITOR'} = cmdoutput qw(realpath --), $0;
1434 local $ENV{'VISUAL'} = $ENV{'EDITOR'};
1435 local $ENV{$fakeeditorenv} = cmdoutput qw(realpath --), $descfn;
1436 runcmd_ordryrun @dpkgsource, qw(--commit .), $patchname;
1439 if (!open P, '>>', ".pc/applied-patches") {
1440 $!==&ENOENT or die $!;
1445 commit_quilty_patch();
1448 sub quilt_fixup_editor () {
1449 my $descfn = $ENV{$fakeeditorenv};
1450 my $editing = $ARGV[$#ARGV];
1451 open I1, '<', $descfn or die "$descfn: $!";
1452 open I2, '<', $editing or die "$editing: $!";
1453 unlink $editing or die "$editing: $!";
1454 open O, '>', $editing or die "$editing: $!";
1455 while (<I1>) { print O or die $!; } I1->error and die $!;
1458 $copying ||= m/^\-\-\- /;
1459 next unless $copying;
1462 I2->error and die $!;
1468 badusage "-p is not allowed when building" if defined $package;
1470 my $clogp = parsechangelog();
1471 $isuite = getfield $clogp, 'Distribution';
1472 $package = getfield $clogp, 'Source';
1473 $version = getfield $clogp, 'Version';
1474 build_maybe_quilt_fixup();
1478 badusage "dgit build implies --clean=dpkg-source"
1479 if $cleanmode ne 'dpkg-source';
1481 runcmd_ordryrun @dpkgbuildpackage, qw(-us -uc), changesopts(), @ARGV;
1482 printdone "build successful\n";
1486 badusage "dgit git-build implies --clean=dpkg-source"
1487 if $cleanmode ne 'dpkg-source';
1490 (qw(git-buildpackage -us -uc --git-no-sign-tags),
1491 "--git-builder=@dpkgbuildpackage");
1492 unless (grep { m/^--git-debian-branch|^--git-ignore-branch/ } @ARGV) {
1493 canonicalise_suite();
1494 push @cmd, "--git-debian-branch=".lbranch();
1496 push @cmd, changesopts();
1497 runcmd_ordryrun @cmd, @ARGV;
1498 printdone "build successful\n";
1503 $sourcechanges = "${package}_".(stripepoch $version)."_source.changes";
1504 $dscfn = dscfn($version);
1505 if ($cleanmode eq 'dpkg-source') {
1506 runcmd_ordryrun (@dpkgbuildpackage, qw(-us -uc -S)), changesopts();
1508 if ($cleanmode eq 'git') {
1509 runcmd_ordryrun @git, qw(clean -xdf);
1510 } elsif ($cleanmode eq 'none') {
1514 my $pwd = cmdoutput qw(env - pwd);
1515 my $leafdir = basename $pwd;
1516 chdir ".." or die $!;
1517 runcmd_ordryrun @dpkgsource, qw(-b --), $leafdir;
1518 chdir $pwd or die $!;
1519 runcmd_ordryrun qw(sh -ec),
1520 'exec >$1; shift; exec "$@"','x',
1521 "../$sourcechanges",
1522 @dpkggenchanges, qw(-S), changesopts();
1526 sub cmd_build_source {
1527 badusage "build-source takes no additional arguments" if @ARGV;
1529 printdone "source built, results in $dscfn and $sourcechanges";
1534 chdir ".." or die $!;
1535 my $pat = "${package}_".(stripepoch $version)."_*.changes";
1537 stat $dscfn or fail "$dscfn (in parent directory): $!";
1538 stat $sourcechanges or fail "$sourcechanges (in parent directory): $!";
1539 foreach my $cf (glob $pat) {
1540 next if $cf eq $sourcechanges;
1541 unlink $cf or fail "remove $cf: $!";
1544 runcmd_ordryrun @sbuild, @ARGV, qw(-d), $isuite, $dscfn;
1545 runcmd_ordryrun @mergechanges, glob $pat;
1546 my $multichanges = "${package}_".(stripepoch $version)."_multi.changes";
1548 stat $multichanges or fail "$multichanges: $!";
1550 printdone "build successful, results in $multichanges\n" or die $!;
1553 sub cmd_quilt_fixup {
1554 badusage "incorrect arguments to dgit quilt-fixup" if @ARGV;
1555 my $clogp = parsechangelog();
1556 $version = getfield $clogp, 'Version';
1557 build_maybe_quilt_fixup();
1560 #---------- argument parsing and main program ----------
1563 print "dgit version $our_version\n" or die $!;
1570 last unless $ARGV[0] =~ m/^-/;
1574 if (m/^--dry-run$/) {
1577 } elsif (m/^--no-sign$/) {
1580 } elsif (m/^--help$/) {
1582 } elsif (m/^--version$/) {
1584 } elsif (m/^--new$/) {
1587 } elsif (m/^--(\w+)=(.*)/s &&
1588 ($om = $opts_opt_map{$1}) &&
1592 } elsif (m/^--(\w+):(.*)/s &&
1593 ($om = $opts_opt_map{$1})) {
1596 } elsif (m/^--existing-package=(.*)/s) {
1598 $existing_package = $1;
1599 } elsif (m/^--distro=(.*)/s) {
1602 } elsif (m/^--clean=(dpkg-source|git|none)$/s) {
1605 } elsif (m/^--clean=(.*)$/s) {
1606 badusage "unknown cleaning mode \`$1'";
1607 } elsif (m/^--ignore-dirty$/s) {
1610 } elsif (m/^--no-quilt-fixup$/s) {
1614 badusage "unknown long option \`$_'";
1621 } elsif (s/^-h/-/) {
1623 } elsif (s/^-D/-/) {
1625 open DEBUG, ">&STDERR" or die $!;
1627 } elsif (s/^-N/-/) {
1630 } elsif (m/^-[vm]/) {
1632 push @changesopts, $_;
1634 } elsif (s/^-c(.*=.*)//s) {
1636 push @git, '-c', $1;
1637 } elsif (s/^-d(.*)//s) {
1640 } elsif (s/^-C(.*)//s) {
1643 } elsif (s/^-k(.*)//s) {
1645 } elsif (s/^-wn//s) {
1647 $cleanmode = 'none';
1648 } elsif (s/^-wg//s) {
1651 } elsif (s/^-wd//s) {
1653 $cleanmode = 'dpkg-source';
1655 badusage "unknown short option \`$_'";
1662 if ($ENV{$fakeeditorenv}) {
1663 quilt_fixup_editor();
1666 delete $ENV{'DGET_UNPACK'};
1669 print STDERR "DRY RUN ONLY\n" if $dryrun;
1671 print STDERR $helpmsg or die $!;
1674 my $cmd = shift @ARGV;
1676 { no strict qw(refs); &{"cmd_$cmd"}(); }