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;
37 our $existing_package = 'dpkg';
39 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
42 our (@dget) = qw(dget);
43 our (@dput) = qw(dput);
44 our (@debsign) = qw(debsign);
45 our (@cleancmd) = qw(debian/rules clean);
49 open DEBUG, ">/dev/null" or die $!;
51 our %opts_opt_map = ('dget' => \@dget,
53 'debsign' => \@debsign);
55 our $remotename = 'dgit';
56 our $ourdscfield = 'Vcs-Dgit-Master';
57 our $branchprefix = 'dgit';
59 sub lbranch () { return "$branchprefix/$suite"; }
60 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
61 sub lref () { return "refs/heads/".lbranch(); }
62 sub lrref () { return "refs/remotes/$remotename/$suite"; }
63 sub rrref () { return "refs/$branchprefix/$suite"; }
64 sub debiantag ($) { return "debian/$_[0]"; }
68 return "+".rrref().":".lrref();
75 $ua = LWP::UserAgent->new();
78 print "downloading @_...\n";
79 my $r = $ua->get(@_) or die $!;
80 die "$_[0]: ".$r->status_line."; failed.\n" unless $r->is_success;
81 return $r->decoded_content();
84 our ($dscdata,$dscurl,$dsc);
89 print $fh $intro or die $!;
93 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
94 print $fh " '$_'" or die $!;
96 print $fh " $_" or die $!;
99 print $fh "\n" or die $!;
103 printcmd(\*DEBUG,"+",@_) if $debug>0;
105 die "@_ $! $?" if system @_;
110 print "dgit ok: @_\n";
112 print "would be ok: @_ (but dry run only)\n";
116 sub cmdoutput_errok {
117 die Dumper(\@_)." ?" if grep { !defined } @_;
118 printcmd(\*DEBUG,"|",@_) if $debug>0;
119 open P, "-|", @_ or die $!;
122 { local $/ = undef; $d = <P>; }
124 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
127 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
132 my $d = cmdoutput_errok @_;
133 defined $d or die "@_ $? $!";
138 printcmd(\*STDOUT,"#",@_);
141 sub runcmd_ordryrun {
149 our %defcfg = ('dgit.default.distro' => 'debian',
150 'dgit.default.username' => '',
151 'dgit.default.archive-query-default-component' => 'main',
152 'dgit.default.ssh' => 'ssh',
153 'dgit-distro.debian.git-host' => 'git.debian.org',
154 'dgit-distro.debian.git-proto' => 'git+ssh://',
155 'dgit-distro.debian.git-path' => '/git/dgit-repos',
156 'dgit-distro.debian.git-check' => 'ssh-cmd',
157 'dgit-distro.debian.git-create' => 'ssh-cmd',
158 'dgit-distro.debian.mirror' => 'http://http.debian.net/debian/');
164 local ($debug) = $debug-1;
165 $v = cmdoutput_errok(@git, qw(config --), $c);
172 my $dv = $defcfg{$c};
173 return $dv if defined $dv;
178 sub access_distro () {
179 return cfg("dgit-suite.$suite.distro",
180 "dgit.default.distro");
185 my $distro = access_distro();
186 my $value = cfg("dgit-distro.$distro.$key",
187 "dgit.default.$key");
191 sub access_gituserhost () {
192 my $user = access_cfg('git-user');
193 my $host = access_cfg('git-host');
194 return defined($user) && length($user) ? "$user\@$host" : $host;
197 sub access_giturl () {
198 my $url = access_cfg('git-url');
201 access_cfg('git-proto').
202 access_gituserhost().
203 access_cfg('git-path');
205 return "$url/$package.git";
209 my $c = Dpkg::Control::Hash->new();
210 $c->load(@_) or return undef;
215 my $c = Dpkg::Control::Hash->new();
216 my $p = new IO::Handle;
217 open $p, '-|', qw(dpkg-parsechangelog) or die $!;
219 $?=0; $!=0; close $p or die "$! $?";
225 sub archive_query () {
226 my $query = access_cfg('archive-query');
227 $query ||= "madison:".access_distro();
228 $query =~ s/^(\w+):// or die "$query ?";
231 die unless $proto eq 'madison';
232 $rmad{$package} ||= cmdoutput
233 qw(rmadison -asource),"-s$suite","-u$url",$package;
234 my $rmad = $rmad{$package};
238 $rmad =~ m{^ \s*( [^ \t|]+ )\s* \|
239 \s*( [^ \t|]+ )\s* \|
240 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
241 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
242 $1 eq $package or die "$rmad $package ?";
245 # madison canonicalises for us
246 print "canonical suite name for $suite is $3\n";
253 $component = access_cfg('archive-query-default-component');
255 $5 eq 'source' or die "$rmad ?";
256 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
257 my $subpath = "/pool/$component/$prefix/$package/${package}_$vsn.dsc";
258 return ($vsn,$subpath);
261 sub canonicalise_suite () {
262 archive_query() or die;
265 sub get_archive_dsc () {
266 my ($vsn,$subpath) = archive_query();
267 if (!defined $vsn) { $dsc=undef; return undef; }
268 $dscurl = access_cfg('mirror').$subpath;
269 $dscdata = url_get($dscurl);
270 my $dscfh = new IO::File \$dscdata, '<' or die $!;
271 print DEBUG Dumper($dscdata) if $debug>1;
272 $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
273 $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
274 print DEBUG Dumper($dsc) if $debug>1;
275 my $fmt = $dsc->{Format};
276 die "unsupported format $fmt, sorry\n" unless $format_ok{$fmt};
279 sub check_for_git () {
281 my $how = access_cfg('git-check');
282 if ($how eq 'ssh-cmd') {
284 (access_cfg('ssh'),access_gituserhost(),
285 " set -e; cd ".access_cfg('git-path').";".
286 " if test -d $package.git; then echo 1; else echo 0; fi");
287 die "$r $! $?" unless $r =~ m/^[01]$/;
290 die "unknown git-check $how ?";
294 sub create_remote_git_repo () {
295 my $how = access_cfg('git-create');
296 if ($how eq 'ssh-cmd') {
298 (access_cfg('ssh'),access_gituserhost(),
299 "set -e; cd ".access_cfg('git-path').";".
300 " mkdir -p $package.git;".
302 " if ! test -d objects; then git init --bare; fi");
304 die "unknown git-create $how ?";
308 our ($dsc_hash,$upload_hash);
310 our $ud = '.git/dgit/unpack';
318 sub mktree_in_ud_from_only_subdir () {
319 # changes into the subdir
322 $dirs[0] =~ m#^([^/]+)/\.$# or die;
324 chdir $dir or die "$dir $!";
326 die $! unless $!==&ENOENT;
327 runcmd qw(git init -q);
328 rmtree('.git/objects');
329 symlink '../../../../objects','.git/objects' or die $!;
330 runcmd @git, qw(add -Af);
331 my $tree = cmdoutput @git, qw(write-tree);
332 $tree =~ m/^\w+$/ or die "$tree ?";
338 m/^\w+ \d+ (\S+)$/ or die "$_ ?";
340 } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
343 sub is_orig_file ($) {
345 m/\.orig(?:-\w+)?\.tar\.\w+$/;
348 sub make_commit ($) {
350 return cmdoutput @git, qw(hash-object -w -t commit), $file;
353 sub generate_commit_from_dsc () {
357 foreach my $f (dsc_files()) {
358 die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
360 link "../../../$f", $f
364 runcmd @dget, qw(--), $dscurl;
365 foreach my $f (grep { is_orig_file($_) } @files) {
366 link $f, "../../../../$f"
370 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
371 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
372 my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
373 my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
374 my $author = $clogp->{Maintainer};
375 $author =~ s#,.*##ms;
376 my $authline = "$author $date";
377 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
378 open C, ">../commit.tmp" or die $!;
379 print C <<END or die $!;
386 # imported from the archive
389 my $outputhash = make_commit qw(../commit.tmp);
390 print "synthesised git commit from .dsc $clogp->{Version}\n";
392 runcmd @git, qw(reset --hard), $upload_hash;
393 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
394 my $oldclogp = Dpkg::Control::Hash->new();
395 $oldclogp->load('../changelogold.tmp','previous changelog') or die;
397 version_compare_string($oldclogp->{Version}, $clogp->{Version});
399 # git upload/ is earlier vsn than archive, use archive
400 open C, ">../commit2.tmp" or die $!;
401 print C <<END or die $!;
408 Record $package ($clogp->{Version}) in archive suite $suite
410 $outputhash = make_commit qw(../commit2.tmp);
411 } elsif ($vcmp > 0) {
412 print STDERR <<END or die $!;
413 Version actually in archive: $clogp->{Version} (older)
414 Last allegedly pushed/uploaded: $oldclogp->{Version} (newer or same)
415 Perhaps the upload is stuck in incoming. Using the version from git.
417 $outputhash = $upload_hash;
418 } elsif ($outputhash ne $upload_hash) {
419 die "version in archive ($clogp->{Version})".
420 " is same as version in git".
421 " to-be-uploaded (upload/) branch ($oldclogp->{Version})".
422 " but archive version hash no commit hash?!\n";
425 chdir '../../../..' or die $!;
426 runcmd @git, qw(update-ref -m),"dgit fetch import $clogp->{Version}",
427 'DGIT_ARCHIVE', $outputhash;
428 cmdoutput @git, qw(log -n2), $outputhash;
429 # ... gives git a chance to complain if our commit is malformed
434 sub ensure_we_have_orig () {
435 foreach my $f (dsc_files()) {
436 next unless is_orig_file($f);
438 die "$f ?" unless -f _;
440 die "$f $!" unless $!==&ENOENT;
442 my $origurl = $dscurl;
443 $origurl =~ s{/[^/]+$}{};
445 die "$f ?" unless $f =~ m/^${package}_/;
446 die "$f ?" if $f =~ m#/#;
447 runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
453 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
456 sub is_fast_fwd ($$) {
457 my ($ancestor,$child) = @_;
458 my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
459 return rev_parse($mb) eq rev_parse($ancestor);
462 sub git_fetch_us () {
463 die "cannot dry run with fetch" if $dryrun;
464 runcmd @git, qw(fetch),access_giturl(),fetchspec();
467 sub fetch_from_archive () {
468 # ensures that lrref() is what is actually in the archive,
470 get_archive_dsc() or return 0;
471 $dsc_hash = $dsc->{$ourdscfield};
472 if (defined $dsc_hash) {
473 $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
475 print "last upload to archive specified git hash\n";
477 print "last upload to archive has NO git hash\n";
480 my $lrref_fn = ".git/".lrref();
481 if (open H, $lrref_fn) {
484 die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
485 } elsif ($! == &ENOENT) {
490 print DEBUG "previous reference hash $upload_hash\n";
492 if (defined $dsc_hash) {
493 die "missing git history even though dsc has hash"
496 ensure_we_have_orig();
498 $hash = generate_commit_from_dsc();
500 print DEBUG "current hash $hash\n";
502 die "not fast forward on last upload branch!".
503 " (archive's version left in DGIT_ARCHIVE)"
504 unless is_fast_fwd($upload_hash, $hash);
506 if ($upload_hash ne $hash) {
507 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
511 dryrun_report @upd_cmd;
519 die "dry run makes no sense with clone" if $dryrun;
520 mkdir $dstdir or die "$dstdir $!";
521 chdir "$dstdir" or die "$dstdir $!";
522 runcmd @git, qw(init -q);
523 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
524 open H, "> .git/HEAD" or die $!;
525 print H "ref: ".lref()."\n" or die $!;
527 runcmd @git, qw(remote add), 'origin', access_giturl();
528 if (check_for_git()) {
529 print "fetching existing git history\n";
531 runcmd @git, qw(fetch origin);
533 print "starting new git history\n";
535 fetch_from_archive() or die;
536 runcmd @git, qw(reset --hard), lrref();
537 printdone "ready for work in $dstdir";
541 if (check_for_git()) {
544 fetch_from_archive() or die;
545 printdone "fetched into ".lrref();
550 runcmd_ordryrun @git, qw(merge -m),"Merge from $suite [dgit]",
552 printdone "fetched to ".lrref()." and merged into HEAD";
555 sub check_not_dirty () {
556 my $output = cmdoutput @git, qw(status --porcelain);
557 if (length $output) {
558 my $m = "tree dirty:\n$output\n";
567 sub commit_quilty_patch () {
568 my $output = cmdoutput @git, qw(status --porcelain);
569 my $vsn = $dsc->{Version};
570 my %fixups = map {$_=>1}
571 (".pc/debian-changes-$vsn/","debian/patches/debian-changes-2.8-5");
573 foreach my $l (split /\n/, $output) {
574 next unless $l =~ s/^\?\? //;
575 next unless $fixups{$l};
578 print DEBUG "checking for quilty\n", Dumper(\@files);
580 runcmd_ordryrun @git, qw(add), @files;
582 @git, qw(commit -m), "Commit Debian 3.0 (quilt) metadata";
587 print DEBUG "actually entering push\n";
589 my $clogp = parsechangelog();
590 $package = $clogp->{Source};
591 my $dscfn = "${package}_$clogp->{Version}.dsc";
592 stat "../$dscfn" or die "$dscfn $!";
593 $dsc = parsecontrol("../$dscfn");
594 print DEBUG "format $dsc->{Format}\n";
595 if ($dsc->{Format} eq '3.0 (quilt)') {
596 commit_quilty_patch();
601 print "checking that $dscfn corresponds to HEAD\n";
602 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
603 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
604 chdir '../../../..' or die $!;
605 runcmd @git, qw(diff --exit-code), $tree;
607 #do fast forward check and maybe fake merge
608 # if (!is_fast_fwd(mainbranch
609 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
610 # map { lref($_).":".rref($_) }
612 $dsc->{$ourdscfield} = rev_parse('HEAD');
613 $dsc->save("../$dscfn.tmp") or die $!;
615 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
617 print "[new .dsc left in $dscfn.tmp]\n";
620 my $pat = "../${package}_$clogp->{Version}_*.changes";
622 die "$pat ?" unless @cs==1;
623 ($changesfile) = @cs;
625 my $tag = debiantag($dsc->{Version});
626 if (!check_for_git()) {
627 create_remote_git_repo();
629 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
631 my @tag_cmd = (@git, qw(tag -s -m),
632 "Release $dsc->{Version} for $suite [dgit]");
633 push @tag_cmd, qw(-u),$keyid if defined $keyid;
635 runcmd_ordryrun @tag_cmd;
636 my @debsign_cmd = @debsign;
637 push @debsign_cmd, "-k$keyid" if defined $keyid;
638 push @debsign_cmd, $changesfile;
639 runcmd_ordryrun @debsign_cmd;
641 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
642 my $host = access_cfg('upload-host');
643 my @hostarg = defined($host) ? ($host,) : ();
644 runcmd_ordryrun @dput, @hostarg, $changesfile;
645 printdone "pushed and uploaded $dsc->{Version}";
651 die if defined $package;
654 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
655 ($package,$suite) = @ARGV;
656 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
657 ($package,$dstdir) = @ARGV;
659 ($package,$suite,$dstdir) = @ARGV;
663 $dstdir ||= "$package";
668 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
669 if ($branch =~ m#$lbranch_re#o) {
676 sub fetchpullargs () {
677 if (!defined $package) {
678 my $sourcep = parsecontrol('debian/control');
679 $package = $sourcep->{Source};
682 $suite = branchsuite();
684 my $clogp = parsechangelog();
685 $suite = $clogp->{Distribution};
687 canonicalise_suite();
688 print "fetching from suite $suite\n";
691 canonicalise_suite();
711 die if defined $package;
712 runcmd @git, qw(diff --quiet HEAD);
713 my $clogp = parsechangelog();
714 $package = $clogp->{Source};
716 $suite = $clogp->{Distribution};
718 local ($package) = $existing_package; # this is a hack
719 canonicalise_suite();
724 if (fetch_from_archive()) {
725 is_fast_fwd(lrref(), 'HEAD') or die;
727 die unless $new_package;
733 # we pass further options and args to git-buildpackage
734 die if defined $package;
735 my $clogp = parsechangelog();
736 $suite = $clogp->{Distribution};
737 $package = $clogp->{Source};
738 canonicalise_suite() unless grep { m/^--git-debian-branch/ } @ARGV;
740 qw(git-buildpackage -us -uc --git-no-sign-tags),
741 '--git-builder=dpkg-buildpackage -i\.git/ -I.git',
742 "--git-debian-branch=".lbranch(),
749 last unless $ARGV[0] =~ m/^-/;
753 if (m/^--dry-run$/) {
755 } elsif (m/^--no-sign$/) {
757 } elsif (m/^--new$/) {
759 } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
761 } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
763 } elsif (m/^--existing-package=(.*)/s) {
764 $existing_package = $1;
765 } elsif (m/^--clean-command=(.*)/s) {
766 @cleancmd = split /\s+/, $1;
775 open DEBUG, ">&STDERR" or die $!;
779 } elsif (s/^-c(.*=.*)//s) {
781 } elsif (s/^-C(.*)//s) {
783 } elsif (s/^-k(.*)//s) {
794 print STDERR "DRY RUN ONLY\n" if $dryrun;
796 my $cmd = shift @ARGV;
798 { no strict qw(refs); &{"cmd_$cmd"}(); }