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