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