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);
48 open DEBUG, ">/dev/null" or die $!;
50 our %opts_opt_map = ('dget' => \@dget,
52 'debsign' => \@debsign);
54 our $remotename = 'dgit';
55 our $ourdscfield = 'Vcs-Dgit-Master';
56 our $branchprefix = 'dgit';
58 sub lbranch () { return "$branchprefix/$suite"; }
59 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
60 sub lref () { return "refs/heads/".lbranch(); }
61 sub lrref () { return "refs/remotes/$remotename/$suite"; }
62 sub rrref () { return "refs/$branchprefix/$suite"; }
63 sub debiantag ($) { return "debian/$_[0]"; }
67 return "+".rrref().":".lrref();
74 $ua = LWP::UserAgent->new();
77 print "downloading @_...\n";
78 my $r = $ua->get(@_) or die $!;
79 die "$_[0]: ".$r->status_line."; failed.\n" unless $r->is_success;
80 return $r->decoded_content();
83 our ($dscdata,$dscurl,$dsc);
88 print $fh $intro or die $!;
92 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
93 print $fh " '$_'" or die $!;
95 print $fh " $_" or die $!;
98 print $fh "\n" or die $!;
102 printcmd(\*DEBUG,"+",@_) if $debug>0;
104 die "@_ $! $?" if system @_;
109 print "dgit ok: @_\n";
111 print "would be ok: @_ (but dry run only)\n";
115 sub cmdoutput_errok {
116 die Dumper(\@_)." ?" if grep { !defined } @_;
117 printcmd(\*DEBUG,"|",@_) if $debug>0;
118 open P, "-|", @_ or die $!;
121 { local $/ = undef; $d = <P>; }
123 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
126 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
131 my $d = cmdoutput_errok @_;
132 defined $d or die "@_ $? $!";
137 printcmd(\*STDOUT,"#",@_);
140 sub runcmd_ordryrun {
148 our %defcfg = ('dgit.default.distro' => 'debian',
149 'dgit.default.username' => '',
150 'dgit.default.archive-query-default-component' => 'main',
151 'dgit.default.ssh' => 'ssh',
152 'dgit-distro.debian.git-host' => 'git.debian.org',
153 'dgit-distro.debian.git-proto' => 'git+ssh://',
154 'dgit-distro.debian.git-path' => '/git/dgit-repos',
155 'dgit-distro.debian.git-check' => 'ssh-cmd',
156 'dgit-distro.debian.git-create' => 'ssh-cmd',
157 'dgit-distro.debian.mirror' => 'http://http.debian.net/debian/');
163 local ($debug) = $debug-1;
164 $v = cmdoutput_errok(@git, qw(config --), $c);
171 my $dv = $defcfg{$c};
172 return $dv if defined $dv;
177 sub access_distro () {
178 return cfg("dgit-suite.$suite.distro",
179 "dgit.default.distro");
184 my $distro = access_distro();
185 my $value = cfg("dgit-distro.$distro.$key",
186 "dgit.default.$key");
190 sub access_gituserhost () {
191 my $user = access_cfg('git-user');
192 my $host = access_cfg('git-host');
193 return defined($user) && length($user) ? "$user\@$host" : $host;
196 sub access_giturl () {
197 my $url = access_cfg('git-url');
200 access_cfg('git-proto').
201 access_gituserhost().
202 access_cfg('git-path');
204 return "$url/$package.git";
208 my $c = Dpkg::Control::Hash->new();
209 $c->load(@_) or return undef;
214 my $c = Dpkg::Control::Hash->new();
215 my $p = new IO::Handle;
216 open $p, '-|', qw(dpkg-parsechangelog) or die $!;
218 $?=0; $!=0; close $p or die "$! $?";
224 sub archive_query () {
225 my $query = access_cfg('archive-query');
226 $query ||= "madison:".access_distro();
227 $query =~ s/^(\w+):// or die "$query ?";
230 die unless $proto eq 'madison';
231 $rmad{$package} ||= cmdoutput
232 qw(rmadison -asource),"-s$suite","-u$url",$package;
233 my $rmad = $rmad{$package};
237 $rmad =~ m{^ \s*( [^ \t|]+ )\s* \|
238 \s*( [^ \t|]+ )\s* \|
239 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
240 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
241 $1 eq $package or die "$rmad $package ?";
244 # madison canonicalises for us
245 print "canonical suite name for $suite is $3\n";
252 $component = access_cfg('archive-query-default-component');
254 $5 eq 'source' or die "$rmad ?";
255 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
256 my $subpath = "/pool/$component/$prefix/$package/${package}_$vsn.dsc";
257 return ($vsn,$subpath);
260 sub canonicalise_suite () {
261 archive_query() or die;
264 sub get_archive_dsc () {
265 my ($vsn,$subpath) = archive_query();
266 if (!defined $vsn) { $dsc=undef; return undef; }
267 $dscurl = access_cfg('mirror').$subpath;
268 $dscdata = url_get($dscurl);
269 my $dscfh = new IO::File \$dscdata, '<' or die $!;
270 print DEBUG Dumper($dscdata) if $debug>1;
271 $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
272 $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
273 print DEBUG Dumper($dsc) if $debug>1;
274 my $fmt = $dsc->{Format};
275 die "unsupported format $fmt, sorry\n" unless $format_ok{$fmt};
278 sub check_for_git () {
280 my $how = access_cfg('git-check');
281 if ($how eq 'ssh-cmd') {
283 (access_cfg('ssh'),access_gituserhost(),
284 " set -e; cd ".access_cfg('git-path').";".
285 " if test -d $package.git; then echo 1; else echo 0; fi");
286 die "$r $! $?" unless $r =~ m/^[01]$/;
289 die "unknown git-check $how ?";
293 sub create_remote_git_repo () {
294 my $how = access_cfg('git-create');
295 if ($how eq 'ssh-cmd') {
297 (access_cfg('ssh'),access_gituserhost(),
298 "set -e; cd ".access_cfg('git-path').";".
299 " mkdir -p $package.git;".
301 " if ! test -d objects; then git init --bare; fi");
303 die "unknown git-create $how ?";
307 our ($dsc_hash,$upload_hash);
309 our $ud = '.git/dgit/unpack';
317 sub mktree_in_ud_from_only_subdir () {
318 # changes into the subdir
321 $dirs[0] =~ m#^([^/]+)/\.$# or die;
323 chdir $dir or die "$dir $!";
325 die $! unless $!==&ENOENT;
326 runcmd qw(git init -q);
327 rmtree('.git/objects');
328 symlink '../../../../objects','.git/objects' or die $!;
329 runcmd @git, qw(add -Af);
330 my $tree = cmdoutput @git, qw(write-tree);
331 $tree =~ m/^\w+$/ or die "$tree ?";
337 m/^\w+ \d+ (\S+)$/ or die "$_ ?";
339 } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
342 sub is_orig_file ($) {
344 m/\.orig(?:-\w+)?\.tar\.\w+$/;
347 sub make_commit ($) {
349 return cmdoutput @git, qw(hash-object -w -t commit), $file;
352 sub generate_commit_from_dsc () {
356 foreach my $f (dsc_files()) {
357 die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
359 link "../../../$f", $f
363 runcmd @dget, qw(--), $dscurl;
364 foreach my $f (grep { is_orig_file($_) } @files) {
365 link $f, "../../../../$f"
369 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
370 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
371 my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
372 my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
373 my $author = $clogp->{Maintainer};
374 $author =~ s#,.*##ms;
375 my $authline = "$author $date";
376 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
377 open C, ">../commit.tmp" or die $!;
378 print C <<END or die $!;
385 # imported from the archive
388 my $outputhash = make_commit qw(../commit.tmp);
389 print "synthesised git commit from .dsc $clogp->{Version}\n";
391 runcmd @git, qw(reset --hard), $upload_hash;
392 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
393 my $oldclogp = Dpkg::Control::Hash->new();
394 $oldclogp->load('../changelogold.tmp','previous changelog') or die;
396 version_compare_string($oldclogp->{Version}, $clogp->{Version});
398 # git upload/ is earlier vsn than archive, use archive
399 open C, ">../commit2.tmp" or die $!;
400 print C <<END or die $!;
407 Record $package ($clogp->{Version}) in archive suite $suite
409 $outputhash = make_commit qw(../commit2.tmp);
410 } elsif ($vcmp > 0) {
411 print STDERR <<END or die $!;
412 Version actually in archive: $clogp->{Version} (older)
413 Last allegedly pushed/uploaded: $oldclogp->{Version} (newer or same)
414 Perhaps the upload is stuck in incoming. Using the version from git.
416 $outputhash = $upload_hash;
417 } elsif ($outputhash ne $upload_hash) {
418 die "version in archive ($clogp->{Version})".
419 " is same as version in git".
420 " to-be-uploaded (upload/) branch ($oldclogp->{Version})".
421 " but archive version hash no commit hash?!\n";
424 chdir '../../../..' or die $!;
425 runcmd @git, qw(update-ref -m),"dgit fetch import $clogp->{Version}",
426 'DGIT_ARCHIVE', $outputhash;
427 cmdoutput @git, qw(log -n2), $outputhash;
428 # ... gives git a chance to complain if our commit is malformed
433 sub ensure_we_have_orig () {
434 foreach my $f (dsc_files()) {
435 next unless is_orig_file($f);
437 die "$f ?" unless -f _;
439 die "$f $!" unless $!==&ENOENT;
441 my $origurl = $dscurl;
442 $origurl =~ s{/[^/]+$}{};
444 die "$f ?" unless $f =~ m/^${package}_/;
445 die "$f ?" if $f =~ m#/#;
446 runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
452 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
455 sub is_fast_fwd ($$) {
456 my ($ancestor,$child) = @_;
457 my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
458 return rev_parse($mb) eq rev_parse($ancestor);
461 sub git_fetch_us () {
462 die "cannot dry run with fetch" if $dryrun;
463 runcmd @git, qw(fetch),access_giturl(),fetchspec();
466 sub fetch_from_archive () {
467 # ensures that lrref() is what is actually in the archive,
469 get_archive_dsc() or return 0;
470 $dsc_hash = $dsc->{$ourdscfield};
471 if (defined $dsc_hash) {
472 $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
474 print "last upload to archive specified git hash\n";
476 print "last upload to archive has NO git hash\n";
479 my $lrref_fn = ".git/".lrref();
480 if (open H, $lrref_fn) {
483 die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
484 } elsif ($! == &ENOENT) {
489 print DEBUG "previous reference hash $upload_hash\n";
491 if (defined $dsc_hash) {
492 die "missing git history even though dsc has hash"
495 ensure_we_have_orig();
497 $hash = generate_commit_from_dsc();
499 print DEBUG "current hash $hash\n";
501 die "not fast forward on last upload branch!".
502 " (archive's version left in DGIT_ARCHIVE)"
503 unless is_fast_fwd($upload_hash, $hash);
505 if ($upload_hash ne $hash) {
506 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
510 dryrun_report @upd_cmd;
518 die "dry run makes no sense with clone" if $dryrun;
519 mkdir $dstdir or die "$dstdir $!";
520 chdir "$dstdir" or die "$dstdir $!";
521 runcmd @git, qw(init -q);
522 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
523 open H, "> .git/HEAD" or die $!;
524 print H "ref: ".lref()."\n" or die $!;
526 runcmd @git, qw(remote add), 'origin', access_giturl();
527 if (check_for_git()) {
528 print "fetching existing git history\n";
530 runcmd @git, qw(fetch origin);
532 print "starting new git history\n";
534 fetch_from_archive() or die;
535 runcmd @git, qw(reset --hard), lrref();
536 printdone "ready for work in $dstdir";
540 if (check_for_git()) {
543 fetch_from_archive() or die;
544 printdone "fetched into ".lrref();
549 runcmd_ordryrun @git, qw(merge -m),"Merge from $suite [dgit]",
551 printdone "fetched to ".lrref()." and merged into HEAD";
554 sub check_not_dirty () {
555 runcmd @git, qw(diff --quiet);
558 sub commit_quilty_patch () {
559 my $output = cmdoutput @git, qw(status --porcelain);
560 my $vsn = $dsc->{Version};
561 my %fixups = map {$_=>1}
562 (".pc/debian-changes-$vsn/","debian/patches/debian-changes-2.8-5");
564 foreach my $l (split /\n/, $output) {
565 next unless $l =~ s/^\?\? //;
566 next unless $fixups{$l};
569 print DEBUG "checking for quilty\n", Dumper(\@files);
571 my $m = "Commit Debian 3.0 (quilt) metadata";
573 runcmd_ordryrun @git, qw(add), @files;
574 runcmd_ordryrun @git, qw(commit -m), $m;
579 print DEBUG "actually entering push\n";
580 my $clogp = parsechangelog();
581 $package = $clogp->{Source};
582 my $dscfn = "${package}_$clogp->{Version}.dsc";
583 stat "../$dscfn" or die "$dscfn $!";
584 $dsc = parsecontrol("../$dscfn");
585 print DEBUG "format $dsc->{Format}\n";
586 if ($dsc->{Format} eq '3.0 (quilt)') {
587 commit_quilty_patch();
592 print "checking that $dscfn corresponds to HEAD\n";
593 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
594 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
595 chdir '../../../..' or die $!;
596 runcmd @git, qw(diff --exit-code), $tree;
598 #do fast forward check and maybe fake merge
599 # if (!is_fast_fwd(mainbranch
600 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
601 # map { lref($_).":".rref($_) }
603 $dsc->{$ourdscfield} = rev_parse('HEAD');
604 $dsc->save("../$dscfn.tmp") or die $!;
606 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
608 print "[new .dsc left in $dscfn.tmp]\n";
611 my $pat = "../${package}_$clogp->{Version}_*.changes";
613 die "$pat ?" unless @cs==1;
614 ($changesfile) = @cs;
616 my $tag = debiantag($dsc->{Version});
617 if (!check_for_git()) {
618 create_remote_git_repo();
620 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
622 my @tag_cmd = (@git, qw(tag -s -m),
623 "Release $dsc->{Version} for $suite [dgit]");
624 push @tag_cmd, qw(-u),$keyid if defined $keyid;
626 runcmd_ordryrun @tag_cmd;
627 my @debsign_cmd = @debsign;
628 push @debsign_cmd, "-k$keyid" if defined $keyid;
629 push @debsign_cmd, $changesfile;
630 runcmd_ordryrun @debsign_cmd;
632 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
633 my $host = access_cfg('upload-host');
634 my @hostarg = defined($host) ? ($host,) : ();
635 runcmd_ordryrun @dput, @hostarg, $changesfile;
636 printdone "pushed and uploaded $dsc->{Version}";
642 die if defined $package;
645 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
646 ($package,$suite) = @ARGV;
647 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
648 ($package,$dstdir) = @ARGV;
650 ($package,$suite,$dstdir) = @ARGV;
654 $dstdir ||= "$package";
659 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
660 if ($branch =~ m#$lbranch_re#o) {
667 sub fetchpullargs () {
668 if (!defined $package) {
669 my $sourcep = parsecontrol('debian/control');
670 $package = $sourcep->{Source};
673 $suite = branchsuite();
675 my $clogp = parsechangelog();
676 $suite = $clogp->{Distribution};
678 canonicalise_suite();
679 print "fetching from suite $suite\n";
682 canonicalise_suite();
702 die if defined $package;
703 runcmd @git, qw(diff --quiet HEAD);
704 my $clogp = parsechangelog();
705 $package = $clogp->{Source};
707 $suite = $clogp->{Distribution};
709 local ($package) = $existing_package; # this is a hack
710 canonicalise_suite();
715 if (fetch_from_archive()) {
716 is_fast_fwd(lrref(), 'HEAD') or die;
718 die unless $new_package;
724 # we pass further options and args to git-buildpackage
725 die if defined $package;
726 my $clogp = parsechangelog();
727 $suite = $clogp->{Distribution};
728 $package = $clogp->{Source};
729 canonicalise_suite() unless grep { m/^--git-debian-branch/ } @ARGV;
731 qw(git-buildpackage -us -uc --git-no-sign-tags),
732 '--git-builder=dpkg-buildpackage -i\.git/ -I.git',
733 "--git-debian-branch=".lbranch(),
740 last unless $ARGV[0] =~ m/^-/;
744 if (m/^--dry-run$/) {
746 } elsif (m/^--no-sign$/) {
748 } elsif (m/^--new$/) {
750 } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
752 } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
754 } elsif (m/^--existing-package=(.*)/s) {
755 $existing_package = $1;
764 open DEBUG, ">&STDERR" or die $!;
768 } elsif (s/^-c(.*=.*)//s) {
770 } elsif (s/^-C(.*)//s) {
772 } elsif (s/^-k(.*)//s) {
783 print STDERR "DRY RUN ONLY\n" if $dryrun;
785 my $cmd = shift @ARGV;
787 { no strict qw(refs); &{"cmd_$cmd"}(); }