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;
36 our $existing_package = 'dpkg';
38 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
41 our (@dget) = qw(dget);
42 our (@dput) = qw(dput);
43 our (@debsign) = qw(debsign);
47 open DEBUG, ">/dev/null" or die $!;
49 our %opts_opt_map = ('dget' => \@dget,
51 'debsign' => \@debsign);
53 our $remotename = 'dgit';
54 our $ourdscfield = 'Vcs-Dgit-Master';
55 our $branchprefix = 'dgit';
57 sub lbranch () { return "$branchprefix/$suite"; }
58 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
59 sub lref () { return "refs/heads/".lbranch(); }
60 sub lrref () { return "refs/remotes/$remotename/$suite"; }
61 sub rrref () { return "refs/$branchprefix/$suite"; }
62 sub debiantag ($) { return "debian/$_[0]"; }
66 return "+".rrref().":".lrref();
73 $ua = LWP::UserAgent->new();
76 print "downloading @_...\n";
77 my $r = $ua->get(@_) or die $!;
78 die "$_[0]: ".$r->status_line."; failed.\n" unless $r->is_success;
79 return $r->decoded_content();
82 our ($dscdata,$dscurl,$dsc);
87 print $fh $intro or die $!;
91 if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
92 print $fh " '$_'" or die $!;
94 print $fh " $_" or die $!;
97 print $fh "\n" or die $!;
101 printcmd(\*DEBUG,"+",@_) if $debug>0;
103 die "@_ $! $?" if system @_;
106 sub cmdoutput_errok {
107 die Dumper(\@_)." ?" if grep { !defined } @_;
108 printcmd(\*DEBUG,"|",@_) if $debug>0;
109 open P, "-|", @_ or die $!;
112 { local $/ = undef; $d = <P>; }
114 if (!close P) { print DEBUG "=>!$?\n" if $debug>0; return undef; }
117 print DEBUG "=> \`$&'",(length $' ? '...' : ''),"\n" if $debug>0; #';
122 my $d = cmdoutput_errok @_;
123 defined $d or die "@_ $? $!";
128 printcmd(\*STDOUT,"#",@_);
131 sub runcmd_ordryrun {
139 our %defcfg = ('dgit.default.distro' => 'debian',
140 'dgit.default.username' => '',
141 'dgit.default.archive-query-default-component' => 'main',
142 'dgit.default.ssh' => 'ssh',
143 'dgit-distro.debian.git-host' => 'git.debian.org',
144 'dgit-distro.debian.git-proto' => 'git+ssh://',
145 'dgit-distro.debian.git-path' => '/git/dgit-repos',
146 'dgit-distro.debian.git-check' => 'ssh-cmd',
147 'dgit-distro.debian.git-create' => 'ssh-cmd',
148 'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
154 local ($debug) = $debug-1;
155 $v = cmdoutput_errok(@git, qw(config --), $c);
162 my $dv = $defcfg{$c};
163 return $dv if defined $dv;
168 sub access_distro () {
169 return cfg("dgit-suite.$suite.distro",
170 "dgit.default.distro");
175 my $distro = access_distro();
176 my $value = cfg("dgit-distro.$distro.$key",
177 "dgit.default.$key");
181 sub access_gituserhost () {
182 my $user = access_cfg('git-user');
183 my $host = access_cfg('git-host');
184 return defined($user) && length($user) ? "$user\@$host" : $host;
187 sub access_giturl () {
188 my $url = access_cfg('git-url');
191 access_cfg('git-proto').
192 access_gituserhost().
193 access_cfg('git-path');
195 return "$url/$package.git";
199 my $c = Dpkg::Control::Hash->new();
200 $c->load(@_) or return undef;
205 my $c = Dpkg::Control::Hash->new();
206 my $p = new IO::Handle;
207 open $p, '-|', qw(dpkg-parsechangelog) or die $!;
209 $?=0; $!=0; close $p or die "$! $?";
215 sub archive_query () {
216 my $query = access_cfg('archive-query');
217 $query ||= "madison:".access_distro();
218 $query =~ s/^(\w+):// or die "$query ?";
221 die unless $proto eq 'madison';
222 $rmad{$package} ||= cmdoutput
223 qw(rmadison -asource),"-s$suite","-u$url",$package;
224 my $rmad = $rmad{$package};
228 $rmad =~ m{^ \s*( [^ \t|]+ )\s* \|
229 \s*( [^ \t|]+ )\s* \|
230 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
231 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
232 $1 eq $package or die "$rmad $package ?";
235 # madison canonicalises for us
236 print "canonical suite name for $suite is $3\n";
243 $component = access_cfg('archive-query-default-component');
245 $5 eq 'source' or die "$rmad ?";
246 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
247 my $subpath = "/pool/$component/$prefix/$package/${package}_$vsn.dsc";
248 return ($vsn,$subpath);
251 sub canonicalise_suite () {
252 archive_query() or die;
255 sub get_archive_dsc () {
256 my ($vsn,$subpath) = archive_query();
257 if (!defined $vsn) { $dsc=undef; return undef; }
258 $dscurl = access_cfg('mirror').$subpath;
259 $dscdata = url_get($dscurl);
260 my $dscfh = new IO::File \$dscdata, '<' or die $!;
261 print DEBUG Dumper($dscdata) if $debug>1;
262 $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
263 $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
264 print DEBUG Dumper($dsc) if $debug>1;
265 my $fmt = $dsc->{Format};
266 die "unsupported format $fmt, sorry\n" unless $format_ok{$fmt};
269 sub check_for_git () {
271 my $how = access_cfg('git-check');
272 if ($how eq 'ssh-cmd') {
274 (access_cfg('ssh'),access_gituserhost(),
275 " set -e; cd ".access_cfg('git-path').";".
276 " if test -d $package.git; then echo 1; else echo 0; fi");
277 print DEBUG "got \`$r'\n";
278 die "$r $! $?" unless $r =~ m/^[01]$/;
281 die "unknown git-check $how ?";
285 sub create_remote_git_repo () {
286 my $how = access_cfg('git-create');
287 if ($how eq 'ssh-cmd') {
289 (access_cfg('ssh'),access_gituserhost(),
290 "set -e; cd ".access_cfg('git-path').";".
291 " mkdir -p $package.git;".
293 " if ! test -d objects; then git init --bare; fi");
295 die "unknown git-create $how ?";
299 our ($dsc_hash,$upload_hash);
301 our $ud = '.git/dgit/unpack';
309 sub mktree_in_ud_from_only_subdir () {
310 # changes into the subdir
313 $dirs[0] =~ m#^([^/]+)/\.$# or die;
315 chdir $dir or die "$dir $!";
317 die $! unless $!==&ENOENT;
318 runcmd qw(git init -q);
319 rmtree('.git/objects');
320 symlink '../../../../objects','.git/objects' or die $!;
321 runcmd @git, qw(add -Af);
322 my $tree = cmdoutput @git, qw(write-tree);
323 $tree =~ m/^\w+$/ or die "$tree ?";
329 m/^\w+ \d+ (\S+)$/ or die "$_ ?";
331 } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
334 sub is_orig_file ($) {
336 m/\.orig(?:-\w+)?\.tar\.\w+$/;
339 sub make_commit ($) {
341 return cmdoutput @git, qw(hash-object -w -t commit), $file;
344 sub generate_commit_from_dsc () {
348 foreach my $f (dsc_files()) {
349 die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
351 link "../../../$f", $f
355 runcmd @dget, qw(--), $dscurl;
356 foreach my $f (grep { is_orig_file($_) } @files) {
357 link $f, "../../../../$f"
361 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
362 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
363 my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
364 my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
365 my $author = $clogp->{Maintainer};
366 $author =~ s#,.*##ms;
367 my $authline = "$author $date";
368 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
369 open C, ">../commit.tmp" or die $!;
370 print C <<END or die $!;
377 # imported from the archive
380 my $commithash = make_commit qw(../commit.tmp);
382 open C, ">../commit2.tmp" or die $!;
383 print C <<END or die $!;
390 Record $package ($clogp->{Version}) in archive suite $suite
392 $commithash = make_commit qw(../commit2.tmp);
394 print "synthesised git commit from .dsc $clogp->{Version}\n";
395 chdir '../../../..' or die $!;
396 cmdoutput @git, qw(update-ref -m),"dgit fetch import $clogp->{Version}",
397 'DGIT_ARCHIVE', $commithash;
398 cmdoutput @git, qw(log -n2), $commithash;
399 # ... gives git a chance to complain if our commit is malformed
400 my $outputhash = $commithash;
402 chdir "$ud/$dir" or die $!;
403 runcmd @git, qw(reset --hard), $upload_hash;
404 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
405 my $oldclogp = Dpkg::Control::Hash->new();
406 $oldclogp->parse('../changelogold.tmp','previous changelog') or die;
408 version_compare_string($oldclogp->{Version}, $clogp->{Version});
410 # git upload/ is earlier vsn than archive, use archive
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.
418 die "version in archive is same as version in git".
419 " to-be-uploaded (upload/) branch but archive".
420 " version hash no commit hash?!\n";
422 chdir '../../../..' or die $!;
428 sub ensure_we_have_orig () {
429 foreach my $f (dsc_files()) {
430 next unless is_orig_file($f);
432 die "$f ?" unless -f _;
434 die "$f $!" unless $!==&ENOENT;
436 my $origurl = $dscurl;
437 $origurl =~ s{/[^/]+$}{};
439 die "$f ?" unless $f =~ m/^${package}_/;
440 die "$f ?" if $f =~ m#/#;
441 runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
447 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
450 sub is_fast_fwd ($$) {
451 my ($ancestor,$child) = @_;
452 my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
453 return rev_parse($mb) eq rev_parse($ancestor);
456 sub git_fetch_us () {
457 die "cannot dry run with fetch" if $dryrun;
458 runcmd @git, qw(fetch),access_giturl(),fetchspec();
461 sub fetch_from_archive () {
462 # ensures that lrref() is what is actually in the archive,
464 get_archive_dsc() or return 0;
465 $dsc_hash = $dsc->{$ourdscfield};
466 if (defined $dsc_hash) {
467 $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
469 print "last upload to archive specified git hash\n";
471 print "last upload to archive has NO git hash\n";
474 my $lrref_fn = ".git/".lrref();
475 if (open H, $lrref_fn) {
478 die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
479 } elsif ($! == &ENOENT) {
484 print DEBUG "last upload hash $upload_hash\n";
486 if (defined $dsc_hash) {
487 die "missing git history even though dsc has hash"
490 ensure_we_have_orig();
492 $hash = generate_commit_from_dsc();
495 die "not fast forward on last upload branch!".
496 " (archive's version left in DGIT_ARCHIVE)"
497 unless is_fast_fwd($dsc_hash, $upload_hash);
499 if ($upload_hash ne $hash) {
500 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
504 dryrun_report @upd_cmd;
512 die "dry run makes no sense with clone" if $dryrun;
513 mkdir $dstdir or die "$dstdir $!";
514 chdir "$dstdir" or die "$dstdir $!";
515 runcmd @git, qw(init -q);
516 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
517 open H, "> .git/HEAD" or die $!;
518 print H "ref: ".lref()."\n" or die $!;
520 runcmd @git, qw(remote add), 'origin', access_giturl();
521 if (check_for_git()) {
522 print "fetching existing git history\n";
524 runcmd @git, qw(fetch origin);
526 print "starting new git history\n";
528 fetch_from_archive() or die;
529 runcmd @git, qw(reset --hard), lrref();
530 print "ready for work in $dstdir\n";
534 if (check_for_git()) {
537 fetch_from_archive() or die;
542 runcmd_ordryrun @git, qw(merge -m),"Merge from $suite [dgit]",
547 runcmd @git, qw(diff --quiet HEAD);
548 my $clogp = parsechangelog();
549 $package = $clogp->{Source};
550 my $dscfn = "${package}_$clogp->{Version}.dsc";
551 stat "../$dscfn" or die "$dscfn $!";
552 $dsc = parsecontrol("../$dscfn");
555 print "checking that $dscfn corresponds to HEAD\n";
556 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
557 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
558 chdir '../../../..' or die $!;
559 runcmd @git, qw(diff --exit-code), $tree;
561 #do fast forward check and maybe fake merge
562 # if (!is_fast_fwd(mainbranch
563 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
564 # map { lref($_).":".rref($_) }
566 $dsc->{$ourdscfield} = rev_parse('HEAD');
567 $dsc->save("../$dscfn.tmp") or die $!;
569 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
571 print "[new .dsc left in $dscfn.tmp]\n";
574 my $pat = "../${package}_$clogp->{Version}_*.changes";
576 die "$pat ?" unless @cs==1;
577 ($changesfile) = @cs;
579 my $tag = debiantag($dsc->{Version});
580 if (!check_for_git()) {
581 create_remote_git_repo();
583 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
585 my @tag_cmd = (@git, qw(tag -s -m),
586 "Release $dsc->{Version} for $suite [dgit]");
587 push @tag_cmd, qw(-u),$keyid if defined $keyid;
589 runcmd_ordryrun @tag_cmd;
590 my @debsign_cmd = @debsign;
591 push @debsign_cmd, "-k$keyid" if defined $keyid;
592 push @debsign_cmd, $changesfile;
593 runcmd_ordryrun @debsign_cmd;
595 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
596 my $host = access_cfg('upload-host');
597 my @hostarg = defined($host) ? ($host,) : ();
598 runcmd_ordryrun @dput, @hostarg, $changesfile;
604 die if defined $package;
607 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
608 ($package,$suite) = @ARGV;
609 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
610 ($package,$dstdir) = @ARGV;
612 ($package,$suite,$dstdir) = @ARGV;
616 $dstdir ||= "$package";
621 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
622 if ($branch =~ m#$lbranch_re#o) {
629 sub fetchpullargs () {
630 if (!defined $package) {
631 my $sourcep = parsecontrol('debian/control');
632 $package = $sourcep->{Source};
635 $suite = branchsuite();
637 my $clogp = parsechangelog();
638 $suite = $clogp->{Distribution};
640 canonicalise_suite();
641 print "fetching from suite $suite\n";
644 canonicalise_suite();
664 die if defined $package;
665 my $clogp = parsechangelog();
666 $package = $clogp->{Source};
668 $suite = $clogp->{Distribution};
670 local ($package) = $existing_package; # this is a hack
671 canonicalise_suite();
676 if (fetch_from_archive()) {
677 is_fast_fwd(lrref(), 'HEAD') or die;
679 die unless $new_package;
685 # we pass further options and args to git-buildpackage
686 die if defined $package;
687 my $clogp = parsechangelog();
688 $suite = $clogp->{Distribution};
689 $package = $clogp->{Source};
691 qw(git-buildpackage -us -uc --git-no-sign-tags),
692 '--git-builder=dpkg-buildpackage -i\.git/ -I.git',
693 "--git-debian-branch=".lbranch(),
700 last unless $ARGV[0] =~ m/^-/;
704 if (m/^--dry-run$/) {
706 } elsif (m/^--no-sign$/) {
708 } elsif (m/^--new$/) {
710 } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
712 } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
714 } elsif (m/^--existing-package=(.*)/s) {
715 $existing_package = $1;
724 open DEBUG, ">&STDERR" or die $!;
728 } elsif (s/^-c(.*=.*)//s) {
730 } elsif (s/^-C(.*)//s) {
732 } elsif (s/^-k(.*)//s) {
744 my $cmd = shift @ARGV;
746 { no strict qw(refs); &{"cmd_$cmd"}(); }