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