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