chiark / gitweb /
0fb928906f06833c553a8d7fc2c9b47d64f484cc
[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     runcmd_ordryrun @git, qw(fetch),$remotename,fetchspec();
350 }
351
352 sub fetch_from_archive () {
353     # ensures that lrref() is what is actually in the archive,
354     #  one way or another
355     get_archive_dsc();
356     $dsc_hash = $dsc->{$ourdscfield};
357     if (defined $dsc_hash) {
358         $dsc_hash =~ m/\w+/ or die "$dsc_hash $?";
359         $dsc_hash = $&;
360         print "last upload to archive specified git hash\n";
361     } else {
362         print "last upload to archive has NO git hash\n";
363     }
364
365     $!=0; $upload_hash =
366         cmdoutput_errok @git, qw(show-ref --heads), lrref();
367     die $! if $!;
368     die $? unless ($?==0 && chomp $upload_hash) 
369         or ($?==256 && !length $upload_hash);
370     $upload_hash ||= '';
371     my $hash;
372     if (defined $dsc_hash) {
373         die "missing git history even though dsc has hash"
374             unless $upload_hash;
375         $hash = $dsc_hash;
376         ensure_we_have_orig();
377     } else {
378         $hash = generate_commit_from_dsc();
379     }
380     if ($upload_hash) {
381         die "not fast forward on last upload branch!".
382             " (archive's version left in DGIT_ARCHIVE)"
383             unless is_fast_fwd($dsc_hash, $upload_hash);
384     }
385     if ($upload_hash ne $hash) {
386         my @upd_cmd = (@git, qw(update-ref -m), 'dgit fetch', lrref(), $hash);
387         if (!$dryrun) {
388             cmdoutput @upd_cmd;
389         } else {
390             dryrun_report @upd_cmd;
391         }
392     }
393 }
394
395 sub clone ($) {
396     my ($dstdir) = @_;
397     die "dry run makes no sense with clone" if $dryrun;
398     mkdir $dstdir or die "$dstdir $!";
399     chdir "$dstdir" or die "$dstdir $!";
400     runcmd @git, qw(init -q);
401     runcmd @git, qw(config), "remote.$remotename.fetch", fetchspec();
402     open H, "> .git/HEAD" or die $!;
403     print H "ref: ".lref()."\n" or die $!;
404     close H or die $!;
405     runcmd @git, qw(remote add), 'origin', "$alioth_git/$package.git";
406     if (check_for_git()) {
407         print "fetching existing git history\n";
408         git_fetch_us();
409         runcmd @git, qw(fetch origin);
410     } else {
411         print "starting new git history\n";
412     }
413     fetch_from_archive();
414     runcmd @git, qw(reset --hard), lrref();
415     print "ready for work in $dstdir\n";
416 }
417
418 sub fetch () {
419     if (check_for_git()) {
420         git_fetch_us();
421     }
422     fetch_from_archive();
423 }
424
425 sub pull () {
426     fetch();
427     runcmd_ordryrun @git, qw(merge -m),"Merge from $suite [dgit]",
428         lrref();
429 }
430
431 sub dopush () {
432     runcmd @git, qw(diff --quiet HEAD);
433     my $clogp = parsechangelog();
434     $package = $clogp->{Source};
435     my $dscfn = "${package}_$clogp->{Version}.dsc";
436     stat "../$dscfn" or die "$dscfn $!";
437     $dsc = parsecontrol("../$dscfn");
438     prep_ud();
439     chdir $ud or die $!;
440     print "checking that $dscfn corresponds to HEAD\n";
441     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
442     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
443     chdir '../../../..' or die $!;
444     runcmd @git, qw(diff --exit-code), $tree;
445 #fetch from alioth
446 #do fast forward check and maybe fake merge
447 #    if (!is_fast_fwd(mainbranch
448 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
449 #        map { lref($_).":".rref($_) }
450 #        (uploadbranch());
451     $dsc->{$ourdscfield} = rev_parse('HEAD');
452     $dsc->save("../$dscfn.tmp") or die $!;
453     if (!$dryrun) {
454         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
455     } else {
456         print "[new .dsc left in $dscfn.tmp]\n";
457     }
458     if (!$changesfile) {
459         my $pat = "../${package}_$clogp->{Version}_*.changes";
460         my @cs = glob $pat;
461         die "$pat ?" unless @cs==1;
462         ($changesfile) = @cs;
463     }
464     my $tag = debiantag($dsc->{Version});
465     if (!check_for_git()) {
466         runcmd_ordryrun qw(ssh),$alioth_sshtestbodge->[0],
467         "set -e; cd $alioth_sshtestbodge->[1];".
468             " mkdir -p $package.git;".
469             " cd $package.git;".
470             " if ! test -d objects; then git init --bare; fi";
471     }
472     runcmd_ordryrun @git, qw(push),$remotename,"HEAD:".rrref();
473     if ($sign) {
474         my @tag_cmd = (@git, qw(tag -s -m),
475                        "Release $dsc->{Version} for $suite [dgit]");
476         push @tag_cmd, qw(-u),$keyid if defined $keyid;
477         push @tag_cmd, $tag;
478         runcmd_ordryrun @tag_cmd;
479         my @debsign_cmd = @debsign;
480         push @debsign_cmd, "-k$keyid" if defined $keyid;
481         push @debsign_cmd, $changesfile;
482         runcmd_ordryrun @debsign_cmd;
483     }
484     runcmd_ordryrun @git, qw(push),$remotename,"refs/tags/$tag";
485     runcmd_ordryrun @dput, $changesfile;
486 }
487
488 sub cmd_clone {
489     my $dstdir;
490     if (@ARGV==1) {
491         ($package) = @ARGV;
492     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
493         ($package,$suite) = @ARGV;
494     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
495         ($package,$dstdir) = @ARGV;
496     } elsif (@ARGV==3) {
497         ($package,$suite,$dstdir) = @ARGV;
498     } else {
499         die;
500     }
501     $dstdir ||= "$package";
502     clone($dstdir);
503 }
504
505 sub branchsuite () {
506     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
507     chomp $branch;
508     if ($branch =~ m#$lbranch_re#o) {
509         return $1;
510     } else {
511         return undef;
512     }
513 }
514
515 sub fetchpullargs () {
516     my $clogp = parsechangelog();
517     $package = $clogp->{Source};
518     if (@ARGV==0) {
519         $suite = branchsuite();
520         $suite ||= $clogp->{Distribution};
521         canonicalise_suite();
522         print "fetching from suite $suite\n";
523     } elsif (@ARGV==1) {
524         ($suite) = @ARGV;
525         canonicalise_suite();
526     } else {
527         die;
528     }
529 }
530
531 sub cmd_fetch {
532     fetchpullargs();
533     fetch();
534 }
535
536 sub cmd_pull {
537     fetchpullargs();
538     pull();
539 }
540
541 sub cmd_push {
542     my $clogp = parsechangelog();
543     $package = $clogp->{Source};
544     if (@ARGV==0) {
545         $suite = $clogp->{Distribution};
546         canonicalise_suite();
547     } else {
548         die;
549     }
550     dopush();
551 }
552
553 sub cmd_build {
554     my $clogp = parsechangelog();
555     $suite = $clogp->{Distribution};
556     $package = $clogp->{Source};
557     canonicalise_suite();
558     runcmd_ordryrun
559         qw(git-buildpackage -us -uc --git-no-sign-tags),
560             "--git-debian-branch=".lbranch(),
561             @ARGV;
562 }
563
564 sub parseopts () {
565     my $om;
566     while (@ARGV) {
567         last unless $ARGV[0] =~ m/^-/;
568         $_ = shift @ARGV;
569         last if m/^--?$/;
570         if (m/^--/) {
571             if (m/^--dry-run$/) {
572                 $dryrun=1;
573             } elsif (m/^--no-sign$/) {
574                 $sign=0;
575             } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
576                 $om->[0] = $2;
577             } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
578                 push @$om, $2;
579             } else {
580                 die "$_ ?";
581             }
582         } else {
583             while (m/^-./s) {
584                 if (s/^-n/-/) {
585                     $dryrun=1;
586                 } elsif (s/^-D/-/) {
587                     open DEBUG, ">&STDERR" or die $!;
588                 } elsif (s/^-c(.*=.*)//s) {
589                     push @git, $1;
590                 } elsif (s/^-C(.*)//s) {
591                     $changesfile = $1;
592                 } elsif (s/^-k(.*)//s) {
593                     $keyid=$1;
594                 } else {
595                     die "$_ ?";
596                 }
597             }
598         }
599     }
600 }
601
602 parseopts();
603 die unless @ARGV;
604 my $cmd = shift @ARGV;
605 parseopts();
606
607 { no strict qw(refs); &{"cmd_$cmd"}(); }