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