chiark / gitweb /
dry run fetch really does not update ref
[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     $package = $clogp->{Source};
436     my $dscfn = "${package}_$clogp->{Version}.dsc";
437     stat "../$dscfn" or die "$dscfn $!";
438     $dsc = parsecontrol("../$dscfn");
439     prep_ud();
440     chdir $ud or die $!;
441     print "checking that $dscfn corresponds to HEAD\n";
442     runcmd qw(dpkg-source -x --), "../../../../$dscfn";
443     my ($tree,$dir) = mktree_in_ud_from_only_subdir();
444     chdir '../../../..' or die $!;
445     runcmd @git, qw(diff --exit-code), $tree;
446 #fetch from alioth
447 #do fast forward check and maybe fake merge
448 #    if (!is_fast_fwd(mainbranch
449 #    runcmd @git, qw(fetch -p ), "$alioth_git/$package.git",
450 #        map { lref($_).":".rref($_) }
451 #        (uploadbranch());
452     $dsc->{$ourdscfield} = rev_parse('HEAD');
453     $dsc->save("../$dscfn.tmp") or die $!;
454     if (!$dryrun) {
455         rename "../$dscfn.tmp","../$dscfn" or die "$dscfn $!";
456     } else {
457         print "[new .dsc left in $dscfn.tmp]\n";
458     }
459     if (!$changesfile) {
460         my $pat = "../${package}_$clogp->{Version}_*.changes";
461         my @cs = glob $pat;
462         die "$pat ?" unless @cs==1;
463         ($changesfile) = @cs;
464     }
465     my $tag = debiantag($dsc->{Version});
466     if (!check_for_git()) {
467         runcmd_ordryrun qw(ssh),$alioth_sshtestbodge->[0],
468         "set -e; cd $alioth_sshtestbodge->[1];".
469             " mkdir -p $package.git;".
470             " cd $package.git;".
471             " if ! test -d objects; then git init --bare; fi";
472     }
473     runcmd_ordryrun @git, qw(push),$remotename,"HEAD:".rrref();
474     if ($sign) {
475         my @tag_cmd = (@git, qw(tag -s -m),
476                        "Release $dsc->{Version} for $suite [dgit]");
477         push @tag_cmd, qw(-u),$keyid if defined $keyid;
478         push @tag_cmd, $tag;
479         runcmd_ordryrun @tag_cmd;
480         my @debsign_cmd = @debsign;
481         push @debsign_cmd, "-k$keyid" if defined $keyid;
482         push @debsign_cmd, $changesfile;
483         runcmd_ordryrun @debsign_cmd;
484     }
485     runcmd_ordryrun @git, qw(push),$remotename,"refs/tags/$tag";
486     runcmd_ordryrun @dput, $changesfile;
487 }
488
489 sub cmd_clone {
490     my $dstdir;
491     if (@ARGV==1) {
492         ($package) = @ARGV;
493     } elsif (@ARGV==2 && $ARGV[1] =~ m#^\w#) {
494         ($package,$suite) = @ARGV;
495     } elsif (@ARGV==2 && $ARGV[1] =~ m#^[./]#) {
496         ($package,$dstdir) = @ARGV;
497     } elsif (@ARGV==3) {
498         ($package,$suite,$dstdir) = @ARGV;
499     } else {
500         die;
501     }
502     $dstdir ||= "$package";
503     clone($dstdir);
504 }
505
506 sub branchsuite () {
507     my $branch = cmdoutput_errok @git, qw(symbolic-ref HEAD);
508     chomp $branch;
509     if ($branch =~ m#$lbranch_re#o) {
510         return $1;
511     } else {
512         return undef;
513     }
514 }
515
516 sub fetchpullargs () {
517     my $clogp = parsechangelog();
518     $package = $clogp->{Source};
519     if (@ARGV==0) {
520         $suite = branchsuite();
521         $suite ||= $clogp->{Distribution};
522         canonicalise_suite();
523         print "fetching from suite $suite\n";
524     } elsif (@ARGV==1) {
525         ($suite) = @ARGV;
526         canonicalise_suite();
527     } else {
528         die;
529     }
530 }
531
532 sub cmd_fetch {
533     fetchpullargs();
534     fetch();
535 }
536
537 sub cmd_pull {
538     fetchpullargs();
539     pull();
540 }
541
542 sub cmd_push {
543     my $clogp = parsechangelog();
544     $package = $clogp->{Source};
545     if (@ARGV==0) {
546         $suite = $clogp->{Distribution};
547         canonicalise_suite();
548     } else {
549         die;
550     }
551     dopush();
552 }
553
554 sub cmd_build {
555     my $clogp = parsechangelog();
556     $suite = $clogp->{Distribution};
557     $package = $clogp->{Source};
558     canonicalise_suite();
559     runcmd_ordryrun
560         qw(git-buildpackage -us -uc --git-no-sign-tags),
561             "--git-debian-branch=".lbranch(),
562             @ARGV;
563 }
564
565 sub parseopts () {
566     my $om;
567     while (@ARGV) {
568         last unless $ARGV[0] =~ m/^-/;
569         $_ = shift @ARGV;
570         last if m/^--?$/;
571         if (m/^--/) {
572             if (m/^--dry-run$/) {
573                 $dryrun=1;
574             } elsif (m/^--no-sign$/) {
575                 $sign=0;
576             } elsif (m/^--(\w+)=(.*)/s && ($om = $opts_opt_map{$1})) {
577                 $om->[0] = $2;
578             } elsif (m/^--(\w+):(.*)/s && ($om = $opts_opt_map{$1})) {
579                 push @$om, $2;
580             } else {
581                 die "$_ ?";
582             }
583         } else {
584             while (m/^-./s) {
585                 if (s/^-n/-/) {
586                     $dryrun=1;
587                 } elsif (s/^-D/-/) {
588                     open DEBUG, ">&STDERR" or die $!;
589                 } elsif (s/^-c(.*=.*)//s) {
590                     push @git, $1;
591                 } elsif (s/^-C(.*)//s) {
592                     $changesfile = $1;
593                 } elsif (s/^-k(.*)//s) {
594                     $keyid=$1;
595                 } else {
596                     die "$_ ?";
597                 }
598             }
599         }
600     }
601 }
602
603 parseopts();
604 die unless @ARGV;
605 my $cmd = shift @ARGV;
606 parseopts();
607
608 { no strict qw(refs); &{"cmd_$cmd"}(); }