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