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;
30 our $isuite = 'unstable';
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';
59 sub lbranch () { return "$branchprefix/$csuite"; }
60 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
61 sub lref () { return "refs/heads/".lbranch(); }
62 sub lrref () { return "refs/remotes/$remotename/$csuite"; }
63 sub rrref () { return "refs/$branchprefix/$csuite"; }
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 $helpmsg = <<END;
151 dgit [dgit-opts] clone [dgit-opts] package [suite] [./dir|/dir]
152 dgit [dgit-opts] fetch|pull [dgit-opts] [suite]
153 dgit [dgit-opts] build [git-buildpackage-opts|dpkg-buildpackage-opts]
154 dgit [dgit-opts] push [dgit-opts] [suite]
155 important dgit options:
156 -k<keyid> sign tag and package with <keyid> instead of default
157 --dry-run -n do not change anything, but go through the motions
158 --new -N allow introducing a new package
159 --debug -D increase debug level
160 -c<name>=<value> set git config option (used directly by dgit too)
164 print $helpmsg or die $!;
168 our %defcfg = ('dgit.default.distro' => 'debian',
169 'dgit.default.username' => '',
170 'dgit.default.archive-query-default-component' => 'main',
171 'dgit.default.ssh' => 'ssh',
172 'dgit-distro.debian.git-host' => 'dgit.debian.net',
173 'dgit-distro.debian.git-proto' => 'git+ssh://',
174 'dgit-distro.debian.git-path' => '/git/dgit-repos',
175 'dgit-distro.debian.git-check' => 'ssh-cmd',
176 'dgit-distro.debian.git-create' => 'ssh-cmd',
177 'dgit-distro.debian.sshdakls-host' => 'coccia.debian.org',
178 'dgit-distro.debian.sshdakls-dir' =>
179 '/srv/ftp-master.debian.org/ftp/dists',
180 'dgit-distro.debian.mirror' => 'http://http.debian.net/debian/');
186 local ($debug) = $debug-1;
187 $v = cmdoutput_errok(@git, qw(config --), $c);
194 my $dv = $defcfg{$c};
195 return $dv if defined $dv;
200 sub access_distro () {
201 return cfg("dgit-suite.$isuite.distro",
202 "dgit.default.distro");
207 my $distro = access_distro();
208 my $value = cfg(map { ("dgit-distro.$distro.$_",
209 "dgit.default.$_") } @keys);
213 sub access_someuserhost ($) {
215 my $user = access_cfg("$some-user",'username');
216 my $host = access_cfg("$some-host");
217 return defined($user) && length($user) ? "$user\@$host" : $host;
220 sub access_gituserhost () {
221 return access_someuserhost('git');
224 sub access_giturl () {
225 my $url = access_cfg('git-url');
228 access_cfg('git-proto').
229 access_gituserhost().
230 access_cfg('git-path');
232 return "$url/$package.git";
236 my $c = Dpkg::Control::Hash->new();
237 $c->load(@_) or return undef;
242 my $c = Dpkg::Control::Hash->new();
243 my $p = new IO::Handle;
244 open $p, '-|', qw(dpkg-parsechangelog) or die $!;
246 $?=0; $!=0; close $p or die "$! $?";
252 sub archive_query ($) {
254 my $query = access_cfg('archive-query');
256 my $distro = access_distro();
257 if ($distro eq 'debian') {
258 $query = "sshdakls:".
259 access_someuserhost('sshdakls').':'.
260 access_cfg('sshdakls-dir');
262 $query = "madison:$distro";
265 $query =~ s/^(\w+):// or die "$query ?";
268 { no strict qw(refs); &{"${method}_${proto}"}($proto,$data); }
271 sub archive_query_madison ($$) {
272 my ($proto,$data) = @_;
273 die unless $proto eq 'madison';
274 $rmad{$package} ||= cmdoutput
275 qw(rmadison -asource),"-s$isuite","-u$data",$package;
276 my $rmad = $rmad{$package};
277 return madison_parse($rmad);
280 sub archive_query_sshdakls ($$) {
281 my ($proto,$data) = @_;
282 $data =~ s/:.*// or die "$data ?";
283 my $dakls = cmdoutput
284 access_cfg('ssh'), $data, qw(dak ls -asource),"-s$isuite",$package;
285 return madison_parse($dakls);
288 sub canonicalise_suite_sshdakls ($$) {
289 my ($proto,$data) = @_;
290 $data =~ m/:/ or die "$data ?";
291 my $dakls = cmdoutput
292 access_cfg('ssh'), $`,
294 " if test -h $isuite; then readlink $isuite; exit 0; fi;".
295 " if test -d $isuite; then echo $isuite; exit 0; fi;".
297 die unless $dakls =~ m/^\w/;
301 sub madison_parse ($) {
306 $rmad =~ m{^ \s*( [^ \t|]+ )\s* \|
307 \s*( [^ \t|]+ )\s* \|
308 \s*( [^ \t|/]+ )(?:/([^ \t|/]+))? \s* \|
309 \s*( [^ \t|]+ )\s* }x or die "$rmad $?";
310 $1 eq $package or die "$rmad $package ?";
317 $component = access_cfg('archive-query-default-component');
319 $5 eq 'source' or die "$rmad ?";
320 my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
321 my $subpath = "/pool/$component/$prefix/$package/${package}_$vsn.dsc";
322 return ($vsn,$subpath,$newsuite);
325 sub canonicalise_suite_madison ($$) {
326 my @r = archive_query_madison($_[0],$_[1]);
331 sub canonicalise_suite () {
332 $csuite = archive_query('canonicalise_suite');
333 if ($isuite ne $csuite) {
334 # madison canonicalises for us
335 print "canonical suite name for $isuite is $csuite\n";
339 sub get_archive_dsc () {
340 my ($vsn,$subpath) = archive_query('archive_query');
341 canonicalise_suite();
342 if (!defined $vsn) { $dsc=undef; return undef; }
343 $dscurl = access_cfg('mirror').$subpath;
344 $dscdata = url_get($dscurl);
345 my $dscfh = new IO::File \$dscdata, '<' or die $!;
346 print DEBUG Dumper($dscdata) if $debug>1;
347 $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
348 $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
349 print DEBUG Dumper($dsc) if $debug>1;
350 my $fmt = $dsc->{Format};
351 die "unsupported format $fmt, sorry\n" unless $format_ok{$fmt};
354 sub check_for_git () {
356 my $how = access_cfg('git-check');
357 if ($how eq 'ssh-cmd') {
359 (access_cfg('ssh'),access_gituserhost(),
360 " set -e; cd ".access_cfg('git-path').";".
361 " if test -d $package.git; then echo 1; else echo 0; fi");
362 die "$r $! $?" unless $r =~ m/^[01]$/;
365 die "unknown git-check $how ?";
369 sub create_remote_git_repo () {
370 my $how = access_cfg('git-create');
371 if ($how eq 'ssh-cmd') {
373 (access_cfg('ssh'),access_gituserhost(),
374 "set -e; cd ".access_cfg('git-path').";".
375 " mkdir -p $package.git;".
377 " if ! test -d objects; then git init --bare; fi");
379 die "unknown git-create $how ?";
383 our ($dsc_hash,$upload_hash);
385 our $ud = '.git/dgit/unpack';
393 sub mktree_in_ud_from_only_subdir () {
394 # changes into the subdir
397 $dirs[0] =~ m#^([^/]+)/\.$# or die;
399 chdir $dir or die "$dir $!";
401 die $! unless $!==&ENOENT;
402 runcmd qw(git init -q);
403 rmtree('.git/objects');
404 symlink '../../../../objects','.git/objects' or die $!;
405 runcmd @git, qw(add -Af);
406 my $tree = cmdoutput @git, qw(write-tree);
407 $tree =~ m/^\w+$/ or die "$tree ?";
413 m/^\w+ \d+ (\S+)$/ or die "$_ ?";
415 } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
418 sub is_orig_file ($) {
420 m/\.orig(?:-\w+)?\.tar\.\w+$/;
423 sub make_commit ($) {
425 return cmdoutput @git, qw(hash-object -w -t commit), $file;
428 sub generate_commit_from_dsc () {
432 foreach my $f (dsc_files()) {
433 die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
435 link "../../../$f", $f
439 runcmd @dget, qw(--), $dscurl;
440 foreach my $f (grep { is_orig_file($_) } @files) {
441 link $f, "../../../../$f"
445 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
446 runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
447 my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
448 my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
449 my $author = $clogp->{Maintainer};
450 $author =~ s#,.*##ms;
451 my $authline = "$author $date";
452 $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
453 open C, ">../commit.tmp" or die $!;
454 print C <<END or die $!;
461 # imported from the archive
464 my $outputhash = make_commit qw(../commit.tmp);
465 print "synthesised git commit from .dsc $clogp->{Version}\n";
467 runcmd @git, qw(reset --hard), $upload_hash;
468 runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
469 my $oldclogp = Dpkg::Control::Hash->new();
470 $oldclogp->load('../changelogold.tmp','previous changelog') or die;
472 version_compare_string($oldclogp->{Version}, $clogp->{Version});
474 # git upload/ is earlier vsn than archive, use archive
475 open C, ">../commit2.tmp" or die $!;
476 print C <<END or die $!;
483 Record $package ($clogp->{Version}) in archive suite $csuite
485 $outputhash = make_commit qw(../commit2.tmp);
486 } elsif ($vcmp > 0) {
487 print STDERR <<END or die $!;
488 Version actually in archive: $clogp->{Version} (older)
489 Last allegedly pushed/uploaded: $oldclogp->{Version} (newer or same)
490 Perhaps the upload is stuck in incoming. Using the version from git.
492 $outputhash = $upload_hash;
493 } elsif ($outputhash ne $upload_hash) {
494 die "version in archive ($clogp->{Version})".
495 " is same as version in git".
496 " to-be-uploaded (upload/) branch ($oldclogp->{Version})".
497 " but archive version hash no commit hash?!\n";
500 chdir '../../../..' or die $!;
501 runcmd @git, qw(update-ref -m),"dgit fetch import $clogp->{Version}",
502 'DGIT_ARCHIVE', $outputhash;
503 cmdoutput @git, qw(log -n2), $outputhash;
504 # ... gives git a chance to complain if our commit is malformed
509 sub ensure_we_have_orig () {
510 foreach my $f (dsc_files()) {
511 next unless is_orig_file($f);
513 die "$f ?" unless -f _;
515 die "$f $!" unless $!==&ENOENT;
517 my $origurl = $dscurl;
518 $origurl =~ s{/[^/]+$}{};
520 die "$f ?" unless $f =~ m/^${package}_/;
521 die "$f ?" if $f =~ m#/#;
522 runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
528 return cmdoutput @git, qw(rev-parse), "$_[0]~0";
531 sub is_fast_fwd ($$) {
532 my ($ancestor,$child) = @_;
533 my $mb = cmdoutput @git, qw(merge-base), $ancestor, $child;
534 return rev_parse($mb) eq rev_parse($ancestor);
537 sub git_fetch_us () {
538 die "cannot dry run with fetch" if $dryrun;
539 runcmd @git, qw(fetch),access_giturl(),fetchspec();
542 sub fetch_from_archive () {
543 # ensures that lrref() is what is actually in the archive,
545 get_archive_dsc() or return 0;
546 $dsc_hash = $dsc->{$ourdscfield};
547 if (defined $dsc_hash) {
548 $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
550 print "last upload to archive specified git hash\n";
552 print "last upload to archive has NO git hash\n";
555 my $lrref_fn = ".git/".lrref();
556 if (open H, $lrref_fn) {
559 die "$lrref_fn $upload_hash ?" unless $upload_hash =~ m/^\w+$/;
560 } elsif ($! == &ENOENT) {
565 print DEBUG "previous reference hash $upload_hash\n";
567 if (defined $dsc_hash) {
568 die "missing git history even though dsc has hash"
571 ensure_we_have_orig();
573 $hash = generate_commit_from_dsc();
575 print DEBUG "current hash $hash\n";
577 die "not fast forward on last upload branch!".
578 " (archive's version left in DGIT_ARCHIVE)"
579 unless is_fast_fwd($upload_hash, $hash);
581 if ($upload_hash ne $hash) {
582 my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
586 dryrun_report @upd_cmd;
594 canonicalise_suite();
595 die "dry run makes no sense with clone" if $dryrun;
596 mkdir $dstdir or die "$dstdir $!";
597 chdir "$dstdir" or die "$dstdir $!";
598 runcmd @git, qw(init -q);
599 runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
600 open H, "> .git/HEAD" or die $!;
601 print H "ref: ".lref()."\n" or die $!;
603 runcmd @git, qw(remote add), 'origin', access_giturl();
604 if (check_for_git()) {
605 print "fetching existing git history\n";
607 runcmd @git, qw(fetch origin);
609 print "starting new git history\n";
611 fetch_from_archive() or die;
612 runcmd @git, qw(reset --hard), lrref();
613 printdone "ready for work in $dstdir";
617 if (check_for_git()) {
620 fetch_from_archive() or die;
621 printdone "fetched into ".lrref();
626 runcmd_ordryrun @git, qw(merge -m),"Merge from $csuite [dgit]",
628 printdone "fetched to ".lrref()." and merged into HEAD";
631 sub check_not_dirty () {
632 runcmd @git, qw(diff --quiet);
635 sub commit_quilty_patch ($) {
637 my $output = cmdoutput @git, qw(status --porcelain);
638 my %fixups = map {$_=>1}
639 (".pc/debian-changes-$vsn/","debian/patches/debian-changes-$vsn");
641 foreach my $l (split /\n/, $output) {
642 next unless $l =~ s/^\?\? //;
643 next unless $fixups{$l};
646 print DEBUG "checking for quilty\n", Dumper(\@files);
648 my $m = "Commit Debian 3.0 (quilt) metadata";
650 runcmd_ordryrun @git, qw(add), @files;
651 runcmd_ordryrun @git, qw(commit -m), $m;
656 print DEBUG "actually entering push\n";
657 my $clogp = parsechangelog();
658 $package = $clogp->{Source};
659 my $dscfn = "${package}_$clogp->{Version}.dsc";
660 stat "../$dscfn" or die "$dscfn $!";
661 $dsc = parsecontrol("../$dscfn");
662 print DEBUG "format $dsc->{Format}\n";
663 if ($dsc->{Format} eq '3.0 (quilt)') {
664 print "Format \`$dsc->{Format}', urgh\n";
665 commit_quilty_patch($dsc->{Version});
670 print "checking that $dscfn corresponds to HEAD\n";
671 runcmd qw(dpkg-source -x --), "../../../../$dscfn";
672 my ($tree,$dir) = mktree_in_ud_from_only_subdir();
673 chdir '../../../..' or die $!;
674 runcmd @git, qw(diff --exit-code), $tree;
676 #do fast forward check and maybe fake merge
677 # if (!is_fast_fwd(mainbranch
678 # runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
679 # map { lref($_).":".rref($_) }
681 $dsc->{$ourdscfield} = rev_parse('HEAD');
682 $dsc->save("../$dscfn.tmp") or die $!;
684 rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
686 print "[new .dsc left in $dscfn.tmp]\n";
689 my $pat = "../${package}_$clogp->{Version}_*.changes";
691 die "$pat ?" unless @cs==1;
692 ($changesfile) = @cs;
694 my $tag = debiantag($dsc->{Version});
695 if (!check_for_git()) {
696 create_remote_git_repo();
698 runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
700 my @tag_cmd = (@git, qw(tag -s -m),
701 "Release $dsc->{Version} for $csuite [dgit]");
702 push @tag_cmd, qw(-u),$keyid if defined $keyid;
704 runcmd_ordryrun @tag_cmd;
705 my @debsign_cmd = @debsign;
706 push @debsign_cmd, "-k$keyid" if defined $keyid;
707 push @debsign_cmd, $changesfile;
708 runcmd_ordryrun @debsign_cmd;
710 runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
711 my $host = access_cfg('upload-host');
712 my @hostarg = defined($host) ? ($host,) : ();
713 runcmd_ordryrun @dput, @hostarg, $changesfile;
714 printdone "pushed and uploaded $dsc->{Version}";
720 die if defined $package;
723 } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
724 ($package,$isuite) = @ARGV;
725 } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
726 ($package,$dstdir) = @ARGV;
728 ($package,$isuite,$dstdir) = @ARGV;
732 $dstdir ||= "$package";
737 my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
738 if ($branch =~ m#$lbranch_re#o) {
745 sub fetchpullargs () {
746 if (!defined $package) {
747 my $sourcep = parsecontrol('debian/control');
748 $package = $sourcep->{Source};
751 # $isuite = branchsuite(); # this doesn't work because dak hates canons
753 my $clogp = parsechangelog();
754 $isuite = $clogp->{Distribution};
756 canonicalise_suite();
757 print "fetching from suite $csuite\n";
760 canonicalise_suite();
780 die if defined $package;
781 runcmd @git, qw(diff --quiet HEAD);
782 my $clogp = parsechangelog();
783 $package = $clogp->{Source};
785 $isuite = $clogp->{Distribution};
787 local ($package) = $existing_package; # this is a hack
788 canonicalise_suite();
793 if (fetch_from_archive()) {
794 is_fast_fwd(lrref(), 'HEAD') or die;
796 die unless $new_package;
802 # we pass further options and args to git-buildpackage
803 die if defined $package;
804 my $clogp = parsechangelog();
805 $isuite = $clogp->{Distribution};
806 $package = $clogp->{Source};
808 (qw(git-buildpackage -us -uc --git-no-sign-tags),
809 '--git-builder=dpkg-buildpackage -i\.git/ -I.git');
810 unless (grep { m/^--git-debian-branch/ } @ARGV) {
811 canonicalise_suite();
812 push @cmd, "--git-debian-branch=".lbranch();
814 runcmd_ordryrun @cmd, @ARGV;
817 sub cmd_quilt_fixup {
819 my $clogp = parsechangelog();
820 commit_quilty_patch($clogp->{Version});
826 last unless $ARGV[0] =~ m/^-/;
830 if (m/^--dry-run$/) {
832 } elsif (m/^--no-sign$/) {
834 } elsif (m/^--help$/) {
836 } elsif (m/^--new$/) {
838 } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
840 } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
842 } elsif (m/^--existing-package=(.*)/s) {
843 $existing_package = $1;
854 open DEBUG, ">&STDERR" or die $!;
858 } elsif (s/^-c(.*=.*)//s) {
860 } elsif (s/^-C(.*)//s) {
862 } elsif (s/^-k(.*)//s) {
873 print STDERR "DRY RUN ONLY\n" if $dryrun;
875 print STDERR $helpmsg or die $!;
878 my $cmd = shift @ARGV;
880 { no strict qw(refs); &{"cmd_$cmd"}(); }