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