chiark / gitweb /
12c06eb182112b0e3f7cc812ab09b61c70695d17
[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 $nopush = 0;
37
38 our $aliothname = 'iwj@git.debian.org';
39 our $aliothpath = '/git/dgit-test';
40 our $alioth_git = "git+ssh://$aliothname/$aliothpath";
41 our $alioth_sshtestbodge = [$aliothname,$aliothpath];
42
43 our (@dget_opts) = qw(-u);
44 our (@git_tag_opts);
45 our (@gpg_opts);
46
47 our $remotename = 'dgit';
48 our $ourdscfield = 'Vcs-git-master';
49 our $branchprefix = 'dgit';
50
51 sub uploadbranch () { return "$branchprefix/$suite"; }
52 sub lref ($) { return "refs/heads/$_[0]"; }
53 sub rref ($) { return "refs/remotes/$remotename/$_[0]"; }
54 sub debiantag ($) { return "debian/$_[0]"; }
55
56 our $ua;
57
58 sub url_get {
59     if (!$ua) {
60         $ua = LWP::UserAgent->new();
61         $ua->env_proxy;
62     }
63     print DEBUG "fetching @_...\n";
64     my $r = $ua->get(@_) or die $!;
65     die "$_[0]: ".$r->status_line."; failed.\n" unless $r->is_success;
66     return $r->decoded_content();
67 }
68
69 our ($dscdata,$dscurl,$dsc);
70
71 sub runcmd {
72     $!=0; $?=0;
73     die "@_ $! $?" if system @_;
74 }
75
76 sub cmdoutput {
77     open P, "-|", @_ or die $!;
78     my $d;
79     $!=0; $?=0;
80     { local $/ = undef; $d = <P>; }
81     die if P->error;
82     close P or die "@_ $? $!";
83     chomp $d;
84     return $d;
85 }
86
87 sub parsecontrol {
88     my $c = Dpkg::Control::Hash->new();
89     $c->load(@_) or return undef;
90     return $c;
91 }
92
93 sub parsechangelog {
94     my $c = Dpkg::Control::Hash->new();
95     my $p = new IO::Handle;
96     open $p, '-|', qw(dpkg-parsechangelog) or die $!;
97     $c->parse($p);
98     $?=0; $!=0; close $p or die "$! $?";
99     return $c;
100 }
101
102 sub get_archive_dsc () {
103     my $rmad = cmdoutput qw(rmadison -asource),"-s$suite",$package;
104     $rmad =~ m/^ \s*( [^ \t|]+ )\s* \|
105                  \s*( [^ \t|]+ )\s* \|
106                  \s*( [^ \t|]+ )\s* \|
107                  \s*( [^ \t|]+ )\s* /x or die "$rmad $?";
108     $1 eq $package or die "$rmad $package ?";
109     my $vsn = $2;
110     $3 eq $suite or die "$rmad $suite ?";
111     $4 eq 'source' or die "$rmad ?";
112     # fixme it does not show us the component ?
113     my $prefix = substr($package, 0, $package =~ m/^l/ ? 4 : 1);
114     $dscurl = "$mirror/pool/main/$prefix/$package/${package}_$vsn.dsc";
115 #print DEBUG Dumper($pdodata, $&, $dscurl);
116     $dscdata = url_get($dscurl);
117     my $dscfh = new IO::File \$dscdata, '<' or die $!;
118 #print DEBUG Dumper($dscdata, $dscfh);
119     $dsc = Dpkg::Control::Hash->new(allow_pgp=>1);
120     $dsc->parse($dscfh, 'dsc') or die "parsing of $dscurl failed\n";
121 #print DEBUG Dumper($dsc);
122     my $fmt = $dsc->{Format};
123     die "unsupported format $fmt, sorry\n" unless $fmt eq '1.0';
124 }
125
126 sub check_for_git () {
127     # returns 0 or 1
128     my $cmd= 
129         "ssh $alioth_sshtestbodge->[0] '".
130         " set -e; cd $aliothpath;".
131         " if test -d $package.git; then echo 1; else echo 0; fi".
132         "'";
133     #print DEBUG "$cmd\n";
134     open P, "$cmd |" or die $!;
135     $!=0; $?=0;
136     my $r = <P>; close P;
137 #print STDERR ">$r<\n";
138     die "$r $! $?" unless $r =~ m/^[01]$/;
139     return $r+0;
140 }
141
142 our ($dsc_hash,$upload_hash);
143
144 our $ud = '.git/dgit/unpack';
145
146 sub prep_ud () {
147     rmtree($ud);
148     mkpath '.git/dgit';
149     mkdir $ud or die $!;
150 }
151
152 sub mktree_in_ud_from_only_subdir () {
153     # changes into the subdir
154     my (@dirs) = <*/.>;
155     die unless @dirs==1;
156     $dirs[0] =~ m#^([^/]+)/\.$# or die;
157     my $dir = $1;
158     chdir $dir or die "$dir $!";
159     die if stat '.git';
160     die $! unless $!==&ENOENT;
161     runcmd qw(git init -q);
162     rmtree('.git/objects');
163     symlink '../../../../objects','.git/objects' or die $!;
164     runcmd qw(git add -Af);
165     my $tree = cmdoutput qw(git write-tree);
166     chomp $tree; $tree =~ m/^\w+$/ or die "$tree ?";
167     return ($tree,$dir);
168 }
169
170 sub dsc_files () {
171     map {
172         m/^\w+ \d+ (\S+)$/ or die "$_ ?";
173         $1;
174     } grep m/\S/, split /\n/, ($dsc->{'Checksums-Sha256'} || $dsc->{Files});
175 }
176
177 sub is_orig_file ($) {
178     local ($_) = @_;
179     m/\.orig\.tar\.\w+$/;
180 }
181
182 sub generate_commit_from_dsc () {
183     prep_ud();
184     chdir $ud or die $!;
185     my @files;
186     foreach my $f (dsc_files()) {
187         die if $f =~ m#/|^\.|\.dsc$|\.tmp$#;
188         push @files, $f;
189         link "../../../$f", $f
190             or $!==&ENOENT
191             or die "$f $!";
192     }
193     runcmd qw(dget), @dget_opts, qw(--), $dscurl;
194     foreach my $f (grep { is_orig_file($_) } @files) {
195         link $f, "../../../$f"
196             or $!==&EEXIST
197             or die "$f $!";
198     }
199     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
200     runcmd qw(sh -ec), 'dpkg-parsechangelog >../changelog.tmp';
201     my $clogp = parsecontrol('../changelog.tmp','changelog') or die;
202     my $date = cmdoutput qw(date), '+%s %z', qw(-d),$clogp->{Date};
203     my $author = $clogp->{Maintainer};
204     $author =~ s#,.*##ms;
205     my $authline = "$author $date";
206     $authline =~ m/^[^<>]+ \<\S+\> \d+ [-+]\d+$/ or die $authline;
207     open C, ">../commit.tmp" or die $!;
208     print C "tree $tree\n" or die $!;
209     print C "parent $upload_hash\n" or die $! if $upload_hash;
210     print C <<END or die $!;
211 author $authline
212 committer $authline
213
214 $clogp->{Changes}
215
216 # imported by dgit from the archive
217 END
218     close C or die $!;
219     print "synthesised git commit from .dsc $clogp->{Version}\n";
220     my $commithash = cmdoutput qw(git hash-object -w -t commit ../commit.tmp);
221     chdir '../../../..' or die $!;
222     cmdoutput qw(git update-ref -m),"dgit synthesise $clogp->{Version}",
223               'DGIT_ARCHIVE', $commithash;
224     cmdoutput qw(git log -n2), $commithash;
225     # ... gives git a chance to complain if our commit is malformed
226     my $outputhash = $commithash;
227     if ($upload_hash) {
228         chdir "$ud/$dir" or die $!;
229         runcmd qw(git reset --hard), $upload_hash;
230         runcmd qw(sh -ec), 'dpkg-parsechangelog >>../changelogold.tmp';
231         my $oldclogp = Dpkg::Control::Hash->new();
232         $oldclogp->parse('../changelogold.tmp','previous changelog') or die;
233         my $vcmp =
234             version_compare_string($oldclogp->{Version}, $clogp->{Version});
235         if ($vcmp < 0) {
236             # git upload/ is earlier vsn than archive, use archive
237         } elsif ($vcmp >= 0) {
238             print STDERR <<END or die $!;
239 Version actually in archive:    $clogp->{Version} (older)
240 Last allegedly pushed/uploaded: $oldclogp->{Version} (newer or same)
241 Perhaps the upload is stuck in incoming.  Using the version from git.
242 END
243         } else {
244             die "version in archive is same as version in git".
245                 " to-be-uploaded (upload/) branch but archive".
246                 " version hash no commit hash?!\n";
247         }
248         chdir '../../../..' or die $!;
249     }
250     rmtree($ud);
251     return $outputhash;
252 }
253
254 sub ensure_we_have_orig () {
255     foreach my $f (dsc_files()) {
256         next unless is_orig_file($f);
257         if (stat "../$f") {
258             die "$f ?" unless -f _;
259         } else {
260             die "$f $!" unless $!==&ENOENT;
261         }
262         my $origurl = $dscurl;
263         $origurl =~ s{/[^/]+$}{};
264         $origurl .= "/$f";
265         die "$f ?" unless $f =~ m/^${package}_/;
266         die "$f ?" if $f =~ m#/#;
267         runcmd qw(sh -ec),'cd ..; exec dget -- "$1"','x',$origurl;
268     }
269 }
270
271 sub rev_parse ($) {
272     return cmdoutput qw(git rev-parse --), "$_[0]~0";
273 }
274
275 sub is_fast_fwd ($$) {
276     my ($ancestor,$child) = @_;
277     my $mb = cmdoutput qw(git merge-base), $dsc_hash, $upload_hash;
278     return rev_parse($mb) eq rev_parse($ancestor);
279 }
280
281 sub fetch_from_archive () {
282     # ensures that rref(uploadbranch()) is what is actually in the archive,
283     #  one way or another
284     my $upload_ref = rref(uploadbranch());
285     $!=0; $upload_hash = `git show-ref --heads $upload_ref`;
286     die $! if $!;
287     die $? unless ($?==0 && chomp $upload_hash) 
288         or ($?==256 && !length $upload_hash);
289     my $hash;
290     if (defined $dsc_hash) {
291         die "missing git history even though dsc has hash"
292             unless $upload_hash;
293         $hash = $dsc_hash;
294         ensure_we_have_orig();
295     } else {
296         $hash = generate_commit_from_dsc();
297     }
298     if ($upload_hash) {
299         die "not fast forward on last upload branch!".
300             " (archive's version left in DGIT_ARCHIVE)"
301             unless is_fast_fwd($dsc_hash, $upload_hash);
302     }
303     if ($upload_hash ne $hash) {
304         cmdoutput qw(git update-ref -m), 'dgit fetch', $upload_ref, $hash;
305     }
306 }
307
308 sub clone () {
309     get_archive_dsc();
310     $dsc_hash = $dsc->{$ourdscfield};
311     if (defined $dsc_hash) {
312         $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
313         $dsc_hash = $&;
314         print "last upload to archive specified git hash\n";
315     } else {
316         print "last upload to archive has NO git hash\n";
317     }
318     my $dstdir = "$package";
319     my $branch = uploadbranch();
320     if (check_for_git()) {
321         print "cloning existing git history\n";
322         runcmd qw(git clone --origin),$remotename, qw(-b), $branch, '--',
323             $alioth_git, $dstdir;
324         chdir "$dstdir" or die "$dstdir $!";
325         fetch_from_archive();
326         runcmd qw(git reset --hard), rref(uploadbranch());
327     } else {
328         print "starting new git history\n";
329         mkdir $dstdir or die "$dstdir $!";
330         chdir "$dstdir" or die "$dstdir $!";
331         runcmd qw(git init -q);
332         open H, "> .git/HEAD" or die $!;
333         print H "ref: ".lref(uploadbranch())."\n" or die $!;
334         close H or die $!;
335         runcmd qw(git remote add), $remotename, $alioth_git;
336         runcmd "git config branch.$branch.remote $remotename";
337         runcmd "git config branch.$branch.merge ".lref(uploadbranch());
338         my $newhash = generate_commit_from_dsc();
339         runcmd qw(git reset --hard), $newhash;
340     }
341     print "ready for work in $dstdir\n";
342 }
343
344 sub fetch () {
345     get_archive_dsc();
346     if (check_for_git()) {
347         runcmd qw(git fetch -p),$remotename,
348             '+refs/heads/*:refs/remotes/origin/*';
349     }
350     fetch_from_archive();
351 }
352
353 sub pull () {
354     fetch();
355     runcmd qw(git merge -m),"Merge from $suite [dgit]",lref(uploadbranch());
356 }
357
358 sub dopush () {
359     runcmd qw(git diff --quiet HEAD);
360     my $clogp = parsechangelog();
361     $package = $clogp->{Source};
362     my $dscfn = "${package}_$clogp->{Version}.dsc";
363     stat $dscfn or die "$dscfn $!";
364     $dsc = parsecontrol("../$dscfn");
365     prep_ud();
366     chdir $ud or die $!;
367     print "checking that $dscfn corresponds to HEAD\n";
368     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
369     my $tree = mktree_in_ud_from_only_subdir();
370     chdir '../../../..' or die $!;
371     runcmd qw(git diff --exit-code), $tree;
372 #fetch from alioth
373 #do fast forward check and maybe fake merge
374 #    if (!is_fast_fwd(mainbranch
375 #    runcmd qw(git fetch -p ), $alioth_git,
376 #        map { lref($_).":".rref($_) }
377 #        (uploadbranch());
378     $dsc->{$ourdscfield} = rev_parse('HEAD');
379     $dsc->save("../$dscfn.tmp") or die $!;
380     rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
381     if ($sign) {
382         runcmd qw(git tag -s),@git_tag_opts,qw(-m),
383             "Release $dsc->{Version} for $suite [dgit]";
384         unlink "../$dscfn.asc" or $!==&ENOENT or die "$dscfn.asc $!";
385         runcmd qw(gpg --clearsign),@gpg_opts,"../$dscfn";
386         rename "../$dscfn.asc","../$dscfn" or die "$dscfn $!";
387     }
388     if (!$nopush) {
389         runcmd qw(git push),$remotename,"HEAD:".lref(uploadbranch());
390         runcmd qw(dput),"../$dscfn";
391     }
392 }
393
394 sub cmd_clone {
395     if (@ARGV==1) {
396         ($package) = @ARGV;
397     } elsif (@ARGV==2) {
398         ($package,$suite) = @ARGV;
399     } else {
400         die;
401     }
402     clone();
403 }
404
405 sub branchsuite () {
406     my $branch = `git-symbolic-ref HEAD`;
407     if ($branch =~ m#^refs/heads/$branchprefix/([^/.]+)$#o) {
408         return $1;
409     } else {
410         return undef;
411     }
412 }
413
414 sub cmd_fetch {
415     my $clogp = parsechangelog();
416     $package = $clogp->{Source};
417     if (@ARGV==0) {
418         $suite = branchsuite();
419         $suite ||= $clogp->{Distribution};
420         print "fetching from suite $suite\n";
421     } elsif (@ARGV==1) {
422         ($suite) = @ARGV;
423     } else {
424         die;
425     }
426     fetch();
427 }
428
429 sub cmd_push {
430     my $clogp = parsechangelog();
431     $package = $clogp->{Source};
432     if (@ARGV==0) {
433         $suite = $clogp->{Distribution};
434     } else {
435         die;
436     }
437     dopush();
438 }
439
440 sub parseopts () {
441     die if @ARGV && $ARGV[0] =~ m/^\-/;
442 }
443
444 parseopts();
445 die unless @ARGV;
446 my $cmd = shift @ARGV;
447 parseopts();
448
449 { no strict qw(refs); &{"cmd_$cmd"}(); }