chiark / gitweb /
configurable mirror
[dgit.git] / dgit
1 #!/usr/bin/perl -w
2 # dgit
3 # Integration between git and Debian-style archives
4 #
5 # Copyright (C)2013 Ian Jackson
6 #
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.
11 #
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.
16 #
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/>.
19
20 use strict;
21
22 use IO::Handle;
23 use Data::Dumper;
24 use LWP::UserAgent;
25 use Dpkg::Control::Hash;
26 use File::Path;
27 use POSIX;
28
29 our $suite = 'sid';
30 our $package;
31
32 our $sign = 1;
33 our $dryrun = 0;
34 our $changesfile;
35
36 our %format_ok = map { $_=>1 } ("1.0","3.0 (native)","3.0 (quilt)");
37
38 our (@git) = qw(git);
39 our (@dget) = qw(dget);
40 our (@dput) = qw(dput);
41 our (@debsign) = qw(debsign);
42 our $keyid;
43
44 open DEBUG, ">/dev/null" or die $!;
45
46 our %opts_opt_map = ('dget' => \@dget,
47                      'dput' => \@dput,
48                      'debsign' => \@debsign);
49
50 our $remotename = 'dgit';
51 our $ourdscfield = 'Vcs-Git-Master';
52 our $branchprefix = 'dgit';
53
54 sub lbranch () { return "$branchprefix/$suite"; }
55 my $lbranch_re = '^refs/heads/'.$branchprefix.'/([^/.]+)$';
56 sub lref () { return "refs/heads/".lbranch(); }
57 sub lrref () { return "refs/remotes/$remotename/$suite"; }
58 sub rrref () { return "refs/$branchprefix/$suite"; }
59 sub debiantag ($) { return "debian/$_[0]"; }
60
61 sub fetchspec () {
62     local $suite = '*';
63     return  "+".rrref().":".lrref();
64 }
65
66 our $ua;
67
68 sub url_get {
69     if (!$ua) {
70         $ua = LWP::UserAgent->new();
71         $ua->env_proxy;
72     }
73     print "downloading @_...\n";
74     my $r = $ua->get(@_) or die $!;
75     die "$_[0]: ".$r->status_line."; failed.\n" unless $r->is_success;
76     return $r->decoded_content();
77 }
78
79 our ($dscdata,$dscurl,$dsc);
80
81 sub printcmd {
82     my $fh = shift @_;
83     my $intro = shift @_;
84     print $fh $intro or die $!;
85     local $_;
86     foreach my $a (@_) {
87         $_ = $a;
88         if (s{['\\]}{\\$&}g || m{\s} || m{[^-_./0-9a-z]}i) {
89             print $fh " '$_'" or die $!;
90         } else {
91             print $fh " $_" or die $!;
92         }
93     }
94     print $fh "\n" or die $!;
95 }
96
97 sub runcmd {
98     printcmd(\*DEBUG,"+",@_);
99     $!=0; $?=0;
100     die "@_ $! $?" if system @_;
101 }
102
103 sub cmdoutput_errok {
104     die Dumper(\@_)." ?" if grep { !defined } @_;
105     printcmd(\*DEBUG,"|",@_);
106     open P, "-|", @_ or die $!;
107     my $d;
108     $!=0; $?=0;
109     { local $/ = undef; $d = <P>; }
110     die if P->error;
111     close P or return undef;
112     chomp $d;
113     return $d;
114 }
115
116 sub cmdoutput {
117     my $d = cmdoutput_errok @_;
118     defined $d or die "@_ $? $!";
119     return $d;
120 }
121
122 sub dryrun_report {
123     printcmd(\*STDOUT,"#",@_);
124 }
125
126 sub runcmd_ordryrun {
127     if (!$dryrun) {
128         runcmd @_;
129     } else {
130         dryrun_report @_;
131     }
132 }
133
134 our %defcfg = ('dgit.default.distro' => 'debian',
135                'dgit.default.username' => '',
136                'dgit.default.ssh' => 'ssh',
137                'dgit-distro.debian.git-host' => 'git.debian.org',
138                'dgit-distro.debian.git-proto' => 'git+ssh://',
139                'dgit-distro.debian.git-path' => '/git/dgit-repos',
140                'dgit-distro.debian.git-check' => 'ssh-cmd',
141                'dgit-distro.debian.git-create' => 'ssh-cmd',
142                'dgit-distro.debian.mirror' => 'http://ftp.debian.org/debian/');
143
144 sub cfg {
145     foreach my $c (@_) {
146         my $v = cmdoutput_errok(@git, qw(config --), $c);
147         if ($?==0) {
148             chomp $v;
149             return $v;
150         } elsif ($?!=256) {
151             die "$c $?";
152         }
153         my $dv = $defcfg{$c};
154         return $dv if defined $dv;
155     }
156     return undef;
157 }
158
159 sub access_cfg ($) {
160     my ($key) = @_;
161     my $distro = cfg("dgit-suite.$suite.distro",
162                      "dgit.default.distro");
163     my $value = cfg("dgit-distro.$distro.$key",
164                     "dgit.default.$key");
165     return $value;
166 }
167
168 sub access_gituserhost () {
169     my $user = access_cfg('git-user');
170     my $host = access_cfg('git-host');
171     return defined($user) && length($user) ? "$user\@$host" : $host;
172 }
173
174 sub access_giturl () {
175     my $url = access_cfg('git-url');
176     if (!defined $url) {
177         $url =
178             access_cfg('git-proto').
179             access_gituserhost().
180             access_cfg('git-path');
181     }
182     return "$url/$package.git";
183 }              
184
185 sub parsecontrol {
186     my $c = Dpkg::Control::Hash->new();
187     $c->load(@_) or return undef;
188     return $c;
189 }
190
191 sub parsechangelog {
192     my $c = Dpkg::Control::Hash->new();
193     my $p = new IO::Handle;
194     open $p, '-|', qw(dpkg-parsechangelog) or die $!;
195     $c->parse($p);
196     $?=0; $!=0; close $p or die "$! $?";
197     return $c;
198 }
199
200 our $rmad;
201
202 sub askmadison () {
203     $rmad ||= cmdoutput qw(rmadison -asource),"-s$suite",$package;
204     $rmad =~ m/^ \s*( [^ \t|]+ )\s* \|
205                  \s*( [^ \t|]+ )\s* \|
206                  \s*( [^ \t|]+ )\s* \|
207                  \s*( [^ \t|]+ )\s* /x or die "$rmad $?";
208     $1 eq $package or die "$rmad $package ?";
209     my $vsn = $2;
210     if ($suite ne $3) {
211         # madison canonicalises for us
212         print "canonical suite name for $suite is $3\n";
213         $suite = $3;
214     }
215     $4 eq 'source' or die "$rmad ?";
216     return $vsn;
217 }
218
219 sub canonicalise_suite () {
220     askmadison();
221 }
222
223 sub get_archive_dsc () {
224     my $vsn = askmadison();
225     # fixme madison does not show us the component
226     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
227     $dscurl = access_cfg('mirror').
228         "/pool/main/$prefix/$package/${package}_$vsn.dsc";
229     $dscdata = url_get($dscurl);
230     my $dscfh = new IO::File \$dscdata, '<' or die $!;
231     print DEBUG Dumper($dscdata);
232     $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
233     $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
234     print DEBUG Dumper($dsc);
235     my $fmt = $dsc->{Format};
236     die "unsupported format $fmt, sorry\n" unless $format_ok{$fmt};
237 }
238
239 sub check_for_git () {
240     # returns 0 or 1
241     my $how = access_cfg('git-check');
242     if ($how eq 'ssh-cmd') {
243         my $r= cmdoutput
244             (access_cfg('ssh'),access_gituserhost(),
245              " set -e; cd ".access_cfg('git-path').";".
246              " if test -d $package.git; then echo 1; else echo 0; fi");
247         print DEBUG ">$r<\n";
248         die "$r $! $?" unless $r =~ m/^[01]$/;
249         return $r+0;
250     } else {
251         die "unknown git-check $how ?";
252     }
253 }
254
255 sub create_remote_git_repo () {
256     my $how = access_cfg('git-create');
257     if ($how eq 'ssh-cmd') {
258         runcmd_ordryrun
259             (access_cfg('ssh'),access_gituserhost(),
260              "set -e; cd ".access_cfg('git-path').";".
261              " mkdir -p $package.git;".
262              " cd $package.git;".
263              " if ! test -d objects; then git init --bare; fi");
264     } else {
265         die "unknown git-create $how ?";
266     }
267 }
268
269 our ($dsc_hash,$upload_hash);
270
271 our $ud = '.git/dgit/unpack';
272
273 sub prep_ud () {
274     rmtree($ud);
275     mkpath '.git/dgit';
276     mkdir $ud or die $!;
277 }
278
279 sub mktree_in_ud_from_only_subdir () {
280     # changes into the subdir
281     my (@dirs) = <*/.>;
282     die unless @dirs==1;
283     $dirs[0] =~ m#^([^/]+)/\.$# or die;
284     my $dir = $1;
285     chdir $dir or die "$dir $!";
286     die if stat '.git';
287     die $! unless $!==&ENOENT;
288     runcmd qw(git init -q);
289     rmtree('.git/objects');
290     symlink '../../../../objects','.git/objects' or die $!;
291     runcmd @git, qw(add -Af);
292     my $tree = cmdoutput @git, qw(write-tree);
293     chomp $tree; $tree =~ m/^\w+$/ or die "$tree ?";
294     return ($tree,$dir);
295 }
296
297 sub dsc_files () {
298     map {
299         m/^\w+ \d+ (\S+)$/ or die "$_ ?";
300         $1;
301     } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
302 }
303
304 sub is_orig_file ($) {
305     local ($_) = @_;
306     m/\.orig(?:-\w+)?\.tar\.\w+$/;
307 }
308
309 sub generate_commit_from_dsc () {
310     prep_ud();
311     chdir $ud or die $!;
312     my @files;
313     foreach my $f (dsc_files()) {
314         die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
315         push @files, $f;
316         link "../../../$f", $f
317             or $!==&ENOENT
318             or die "$f $!";
319     }
320     runcmd @dget, qw(--), $dscurl;
321     foreach my $f (grep { is_orig_file($_) } @files) {
322         link $f, "../../../../$f"
323             or $!==&EEXIST
324             or die "$f $!";
325     }
326     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
327     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
328     my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
329     my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
330     my $author = $clogp->{Maintainer};
331     $author =~ s#,.*##ms;
332     my $authline = "$author $date";
333     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
334     open C, ">../commit.tmp" or die $!;
335     print C "tree $tree\n" or die $!;
336     print C "parent $upload_hash\n" or die $! if $upload_hash;
337     print C <<END or die $!;
338 author $authline
339 committer $authline
340
341 $clogp->{Changes}
342
343 # imported by dgit from the archive
344 END
345     close C or die $!;
346     my $commithash = cmdoutput @git, qw(hash-object -w -t commit ../commit.tmp);
347     print "synthesised git commit from .dsc $clogp->{Version}\n";
348     chdir '../../../..' or die $!;
349     cmdoutput @git, qw(update-ref -m),"dgit synthesise $clogp->{Version}",
350               'DGIT_ARCHIVE', $commithash;
351     cmdoutput @git, qw(log -n2), $commithash;
352     # ... gives git a chance to complain if our commit is malformed
353     my $outputhash = $commithash;
354     if ($upload_hash) {
355         chdir "$ud/$dir" or die $!;
356         runcmd @git, qw(reset --hard), $upload_hash;
357         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
358         my $oldclogp = Dpkg::Control::Hash->new();
359         $oldclogp->parse('../changelogold.tmp','previous changelog') or die;
360         my $vcmp =
361             version_compare_string($oldclogp->{Version}, $clogp->{Version});
362         if ($vcmp < 0) {
363             # git upload/ is earlier vsn than archive, use archive
364         } elsif ($vcmp >= 0) {
365             print STDERR <<END or die $!;
366 Version actually in archive:    $clogp->{Version} (older)
367 Last allegedly pushed/uploaded: $oldclogp->{Version} (newer or same)
368 Perhaps the upload is stuck in incoming.  Using the version from git.
369 END
370         } else {
371             die "version in archive is same as version in git".
372                 " to-be-uploaded (upload/) branch but archive".
373                 " version hash no commit hash?!\n";
374         }
375         chdir '../../../..' or die $!;
376     }
377     rmtree($ud);
378     return $outputhash;
379 }
380
381 sub ensure_we_have_orig () {
382     foreach my $f (dsc_files()) {
383         next unless is_orig_file($f);
384         if (stat "../$f") {
385             die "$f ?" unless -f _;
386         } else {
387             die "$f $!" unless $!==&ENOENT;
388         }
389         my $origurl = $dscurl;
390         $origurl =~ s{/[^/]+$}{};
391         $origurl .= "/$f";
392         die "$f ?" unless $f =~ m/^${package}_/;
393         die "$f ?" if $f =~ m#/#;
394         runcmd_ordryrun qw(sh -ec),'cd ..; exec "$@"','x',
395             @dget,'--',$origurl;
396     }
397 }
398
399 sub rev_parse ($) {
400     return cmdoutput @git, qw(rev-parse), "$_[0]~0";
401 }
402
403 sub is_fast_fwd ($$) {
404     my ($ancestor,$child) = @_;
405     my $mb = cmdoutput @git, qw(merge-base), $dsc_hash, $upload_hash;
406     return rev_parse($mb) eq rev_parse($ancestor);
407 }
408
409 sub git_fetch_us () {
410     die "cannot dry run with fetch" if $dryrun;
411     runcmd @git, qw(fetch),access_giturl(),fetchspec();
412 }
413
414 sub fetch_from_archive () {
415     # ensures that lrref() is what is actually in the archive,
416     #  one way or another
417     get_archive_dsc();
418     $dsc_hash = $dsc->{$ourdscfield};
419     if (defined $dsc_hash) {
420         $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
421         $dsc_hash = $&;
422         print "last upload to archive specified git hash\n";
423     } else {
424         print "last upload to archive has NO git hash\n";
425     }
426
427     $!=0; $upload_hash =
428         cmdoutput_errok @git, qw(show-ref --heads), lrref();
429     if ($?==0) {
430         die unless chomp $upload_hash;
431     } elsif ($?==256) {
432         $upload_hash = '';
433     } else {
434         die $?;
435     }
436     my $hash;
437     if (defined $dsc_hash) {
438         die "missing git history even though dsc has hash"
439             unless $upload_hash;
440         $hash = $dsc_hash;
441         ensure_we_have_orig();
442     } else {
443         $hash = generate_commit_from_dsc();
444     }
445     if ($upload_hash) {
446         die "not fast forward on last upload branch!".
447             " (archive's version left in DGIT_ARCHIVE)"
448             unless is_fast_fwd($dsc_hash, $upload_hash);
449     }
450     if ($upload_hash ne $hash) {
451         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
452         if (!$dryrun) {
453             cmdoutput @upd_cmd;
454         } else {
455             dryrun_report @upd_cmd;
456         }
457     }
458 }
459
460 sub clone ($) {
461     my ($dstdir) = @_;
462     die "dry run makes no sense with clone" if $dryrun;
463     mkdir $dstdir or die "$dstdir $!";
464     chdir "$dstdir" or die "$dstdir $!";
465     runcmd @git, qw(init -q);
466     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
467     open H, "> .git/HEAD" or die $!;
468     print H "ref: ".lref()."\n" or die $!;
469     close H or die $!;
470     runcmd @git, qw(remote add), 'origin', access_giturl();
471     if (check_for_git()) {
472         print "fetching existing git history\n";
473         git_fetch_us();
474         runcmd @git, qw(fetch origin);
475     } else {
476         print "starting new git history\n";
477     }
478     fetch_from_archive();
479     runcmd @git, qw(reset --hard), lrref();
480     print "ready for work in $dstdir\n";
481 }
482
483 sub fetch () {
484     if (check_for_git()) {
485         git_fetch_us();
486     }
487     fetch_from_archive();
488 }
489
490 sub pull () {
491     fetch();
492     runcmd_ordryrun @git, qw(merge -m),"Merge from $suite [dgit]",
493         lrref();
494 }
495
496 sub dopush () {
497     runcmd @git, qw(diff --quiet HEAD);
498     my $clogp = parsechangelog();
499     $package = $clogp->{Source};
500     my $dscfn = "${package}_$clogp->{Version}.dsc";
501     stat "../$dscfn" or die "$dscfn $!";
502     $dsc = parsecontrol("../$dscfn");
503     prep_ud();
504     chdir $ud or die $!;
505     print "checking that $dscfn corresponds to HEAD\n";
506     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
507     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
508     chdir '../../../..' or die $!;
509     runcmd @git, qw(diff --exit-code), $tree;
510 #fetch from alioth
511 #do fast forward check and maybe fake merge
512 #    if (!is_fast_fwd(mainbranch
513 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
514 #        map { lref($_).":".rref($_) }
515 #        (uploadbranch());
516     $dsc->{$ourdscfield} = rev_parse('HEAD');
517     $dsc->save("../$dscfn.tmp") or die $!;
518     if (!$dryrun) {
519         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
520     } else {
521         print "[new .dsc left in $dscfn.tmp]\n";
522     }
523     if (!$changesfile) {
524         my $pat = "../${package}_$clogp->{Version}_*.changes";
525         my @cs = glob $pat;
526         die "$pat ?" unless @cs==1;
527         ($changesfile) = @cs;
528     }
529     my $tag = debiantag($dsc->{Version});
530     if (!check_for_git()) {
531         create_remote_git_repo();
532     }
533     runcmd_ordryrun @git, qw(push),access_giturl(),"HEAD:".rrref();
534     if ($sign) {
535         my @tag_cmd = (@git, qw(tag -s -m),
536                        "Release $dsc->{Version} for $suite [dgit]");
537         push @tag_cmd, qw(-u),$keyid if defined $keyid;
538         push @tag_cmd, $tag;
539         runcmd_ordryrun @tag_cmd;
540         my @debsign_cmd = @debsign;
541         push @debsign_cmd, "-k$keyid" if defined $keyid;
542         push @debsign_cmd, $changesfile;
543         runcmd_ordryrun @debsign_cmd;
544     }
545     runcmd_ordryrun @git, qw(push),access_giturl(),"refs/tags/$tag";
546     my $host = access_cfg('upload-host');
547     my @hostarg = defined($host) ? ($host,) : ();
548     runcmd_ordryrun @dput, @hostarg, $changesfile;
549 }
550
551 sub cmd_clone {
552     my $dstdir;
553     die if defined $package;
554     if (@ARGV==1) {
555         ($package) = @ARGV;
556     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
557         ($package,$suite) = @ARGV;
558     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
559         ($package,$dstdir) = @ARGV;
560     } elsif (@ARGV==3) {
561         ($package,$suite,$dstdir) = @ARGV;
562     } else {
563         die;
564     }
565     $dstdir ||= "$package";
566     clone($dstdir);
567 }
568
569 sub branchsuite () {
570     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
571     chomp $branch;
572     if ($branch =~ m#$lbranch_re#o) {
573         return $1;
574     } else {
575         return undef;
576     }
577 }
578
579 sub fetchpullargs () {
580     if (!defined $package) {
581         my $sourcep = parsecontrol('debian/control');
582         $package = $sourcep->{Source};
583     }
584     if (@ARGV==0) {
585         $suite = branchsuite();
586         if (!$suite) {
587             my $clogp = parsechangelog();
588             $suite = $clogp->{Distribution};
589         }
590         canonicalise_suite();
591         print "fetching from suite $suite\n";
592     } elsif (@ARGV==1) {
593         ($suite) = @ARGV;
594         canonicalise_suite();
595     } else {
596         die;
597     }
598 }
599
600 sub cmd_fetch {
601     fetchpullargs();
602     fetch();
603 }
604
605 sub cmd_pull {
606     fetchpullargs();
607     pull();
608 }
609
610 sub cmd_push {
611     die if defined $package;
612     my $clogp = parsechangelog();
613     $package = $clogp->{Source};
614     if (@ARGV==0) {
615         $suite = $clogp->{Distribution};
616         canonicalise_suite();
617     } else {
618         die;
619     }
620     dopush();
621 }
622
623 sub cmd_build {
624     die if defined $package;
625     my $clogp = parsechangelog();
626     $suite = $clogp->{Distribution};
627     $package = $clogp->{Source};
628     canonicalise_suite();
629     runcmd_ordryrun
630         qw(git-buildpackage -us -uc --git-no-sign-tags),
631             "--git-debian-branch=".lbranch(),
632             @ARGV;
633 }
634
635 sub parseopts () {
636     my $om;
637     while (@ARGV) {
638         last unless $ARGV[0] =~ m/^-/;
639         $_ = shift @ARGV;
640         last if m/^--?$/;
641         if (m/^--/) {
642             if (m/^--dry-run$/) {
643                 $dryrun=1;
644             } elsif (m/^--no-sign$/) {
645                 $sign=0;
646             } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
647                 $om->[0] = $2;
648             } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
649                 push @$om, $2;
650             } else {
651                 die "$_ ?";
652             }
653         } else {
654             while (m/^-./s) {
655                 if (s/^-n/-/) {
656                     $dryrun=1;
657                 } elsif (s/^-D/-/) {
658                     open DEBUG, ">&STDERR" or die $!;
659                 } elsif (s/^-c(.*=.*)//s) {
660                     push @git, '-c', $1;
661                 } elsif (s/^-C(.*)//s) {
662                     $changesfile = $1;
663                 } elsif (s/^-k(.*)//s) {
664                     $keyid=$1;
665                 } else {
666                     die "$_ ?";
667                 }
668             }
669         }
670     }
671 }
672
673 parseopts();
674 die unless @ARGV;
675 my $cmd = shift @ARGV;
676 parseopts();
677
678 { no strict qw(refs); &{"cmd_$cmd"}(); }