chiark / gitweb /
nailing-cargo: provide more control command line options
[nailing-cargo.git] / nailing-cargo
1 #!/usr/bin/perl -w
2
3 #    nailing-cargo: wrapper to use unpublished local crates
4 #
5 #    Copyright (C) 2019-2020 Ian Jackson
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (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 Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 # example usages:
21 #   ../nailing-cargo/nailing-caretwgo make
22 #   ../nailing-cargo/nailing-cargo cargo build
23 #   CARGO='../nailing-cargo/nailing-cargo cargo' make
24
25 # Why do we need this ?
26 #
27 #  https://github.com/rust-lang/cargo/issues/6713
28 #  https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate
29 #  https://github.com/rust-lang/cargo/issues/1481
30
31 # Needs libtoml-perl
32
33 #: Cargo.nail:
34 #
35 #    [packages]
36 #    package = subdir
37 #    package = { subdir = ... }
38 #
39 #    [subdirs]
40 #    subdir
41
42 our $self;
43
44 use strict;
45 use POSIX;
46 use Types::Serialiser;
47
48 our %archmap = (
49     RPI => 'arm-unknown-linux-gnueabihf',
50 );
51
52 BEGIN {
53   $self = $0;  $self =~ s{^.*/(?=.)}{};
54   my $deref = $0;
55   while ($deref =~ m{^/}) {
56     my $link = readlink $deref;
57     if (!defined $link) {
58       $! == EINVAL
59         or die "$self: checking our script location $deref: $!\n";
60       $deref =~ s{/[^/]+$}{}
61         or die "$self: unexpected script path: $deref\n";
62       unshift @INC, $deref."/TOML-Tiny/lib";
63       last;
64     }
65     last if $link !~ m{^/};
66     $deref = $link;
67   }
68 }
69
70 use Fcntl qw(LOCK_EX);
71 use File::Compare;
72 use TOML::Tiny::Faithful;
73
74 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
75
76 our $worksphere = $src_absdir;
77 $worksphere =~ s{/([^/]+)$}{}
78   or die "$self: cwd \`$worksphere' unsupported!\n";
79 our $subdir = $1; # leafname
80
81 our $lockfile = "../.nailing-cargo.lock";
82
83 our $cargo_lock_update;
84 our $cargo_manifest_args;
85
86 our @configs;
87 our $verbose=1;
88 our ($noact,$dump);
89 our $target;
90
91 sub read_or_enoent ($) {
92   my ($fn) = @_;
93   if (!open R, '<', $fn) {
94     return undef if $!==ENOENT;
95     die "$self: open $fn: $!\n";
96   }
97   local ($/) = undef;
98   my ($r) = <R> // die "$self: read $fn: $!\n";
99   $r;
100 }
101
102 sub toml_or_enoent ($$) {
103   my ($f,$what) = @_;
104   my $toml = read_or_enoent($f) // return;
105   my ($v,$e) = from_toml($toml);
106   if (!defined $v) {
107     chomp $e;
108     die "$self: parse TOML: $what: $f: $e\n";
109   }
110   die "$e ?" if length $e;
111   $v;
112 }
113
114 sub load1config ($) {
115   my ($f) = @_;
116   my $toml = toml_or_enoent($f, "config file");
117   push @configs, $toml if defined $toml;
118 }
119
120 sub loadconfigs () {
121   my $cfgleaf = ".nailing-cargo-cfg.toml";
122   load1config("/etc/nailing-cargo/cfg.toml");
123   load1config("$worksphere/$cfgleaf");
124   load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
125 }
126
127 sub getcfg ($$) {
128   my ($k, $def) = @_;
129   foreach my $cfg (@configs) {
130     my $v = $cfg->{$k};
131     return $v if defined $v;
132   }
133   return $def;
134 }
135
136 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
137
138 sub takelock () {
139   for (;;) {
140     open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
141     flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
142     my @fstat = stat LOCK or die "$self: fstat: $!\n";
143     my @stat  = stat $lockfile;
144     if (!@stat) {
145       next if $! == ENOENT;
146       die "$self: stat $lockfile: $!\n";
147     }
148     last if "@fstat[0..5]" eq "@stat[0..5]";
149   }
150 }
151 sub unlock () {
152   unlink $lockfile or die "$self: removing lockfile: $!\n";
153 }
154
155 our $nail;
156
157 sub badcfg {
158   my $m = pop @_;
159   $" = '.';
160   die "$self: config key \`@_': $m\n";
161 }
162
163 sub cfg_uc {
164   my $v = $nail;
165   foreach my $k (@_) {
166     last unless defined $v;
167     ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
168     $v = $v->{$k};
169   }
170   return $v;
171 }
172
173 sub cfge {
174   my $exp = shift @_;
175   my $v = cfg_uc @_;
176   my $got = ref($v) || 'scalar';
177   return $v if !defined($v) || $got eq $exp;
178   badcfg @_, "found \L$got\E, expected \L$exp\E";
179   # ^ toml doesn't make refs to scalars, so this is unambiguous
180 }
181
182 sub cfgn {
183   my $exp = shift @_;
184   (cfge $exp, @_) // badcfg @_, "missing";
185 }
186
187 sub cfgs  { cfge 'scalar', @_ }
188 sub cfgsn { cfgn 'scalar', @_ }
189
190 sub cfgn_list {
191   my $l = cfge 'ARRAY', @_;
192   foreach my $x (@$l) {
193     !ref $x or badcfg @_, "list contains non-scalar element";
194   }
195   @$l
196 }
197
198 sub readnail () {
199   my $nailfile = "../Cargo.nail";
200   open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
201   local ($/) = undef;
202   my $toml = <N> // die "$self: read $nailfile: $!";
203   my $transformed;
204   if ($toml !~ m{^\s*\[/}m &&
205       $toml !~ m{^[^\n\#]*\=}m &&
206       # old non-toml syntax
207       $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
208     $toml =~ s{^}{[packages\]\n};
209     my @sd;
210     $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
211       push @sd, $1; '';
212     }mige;
213     $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
214     $transformed = 1;
215   }
216   my $e;
217   ($nail,$e) = from_toml($toml);
218   if (!defined $nail) {
219     if ($transformed) {
220       $toml =~ s/^/    /mg;
221       print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
222     }
223     $/="\n"; chomp $e;
224     die "$self: parse $nailfile: $e\n";
225   }
226   die "$e ?" if length $e;
227
228   if (!ref $nail->{subdirs}) {
229     $nail->{subdirs} = [
230       grep /^[^\#]/,
231       map { s/^\s+//; s/\s+$//; $_; }
232       split m{\n},
233       $nail->{subdirs}
234     ];
235   }
236 }
237
238 our $oot_dir;      # oot.dir or "Build"
239
240 sub consider_oot () {
241   $oot_dir = cfgs qw(oot dir);
242   my $use = cfgs qw(oot use);
243   unless (defined($oot_dir) || defined($use)) {
244     $cargo_lock_update//=0;
245     return;
246   }
247   $oot_dir //= 'Build';
248 }
249
250 our %manifests;
251 our %packagemap;
252
253 sub read_manifest ($) {
254   my ($subdir) = @_;
255   my $manifest = "../$subdir/Cargo.toml";
256   print STDERR "$self: reading $manifest...\n" if $verbose>=4;
257   if (defined $manifests{$manifest}) {
258     print STDERR
259  "$self: warning: $subdir: specified more than once!\n";
260     return undef;
261   }
262   foreach my $try ("$manifest.unnailed", "$manifest") {
263     my $toml = toml_or_enoent($try, "package manifest") // next;
264     my $p = $toml->{package}{name};
265     if (!defined $p) {
266       print STDERR
267  "$self: warning: $subdir: missing package.name in $try, ignoring\n";
268       next;
269     }
270     $manifests{$manifest} = $toml;
271     return $p;
272   }
273   return undef;
274 }
275
276 sub readorigs () {
277   foreach my $p (keys %{ $nail->{packages} }) {
278     my $v = $nail->{packages}{$p};
279     my $subdir = ref($v) ? $v->{subdir} : $v;
280     my $gotpackage = read_manifest($subdir) // '<nothing!>';
281     if ($gotpackage ne $p) {
282       print STDERR
283  "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
284     }
285     die if defined $packagemap{$p};
286     $packagemap{$p} = $subdir;
287   }
288   foreach my $subdir (@{ $nail->{subdirs} }) {
289     my $gotpackage = read_manifest($subdir);
290     if (!defined $gotpackage) {
291       print STDERR
292  "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
293       next;
294     }
295     $packagemap{$gotpackage} //= $subdir;
296   }
297 }
298
299 sub calculate () {
300   foreach my $p (sort keys %packagemap) {
301     print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
302   }
303   foreach my $mf (keys %manifests) {
304     my $toml = $manifests{$mf};
305     foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
306       my $deps = $toml->{$k};
307       next unless $deps;
308       foreach my $p (keys %packagemap) {
309         my $info = $deps->{$p};
310         next unless defined $info;
311         $deps->{$p} = $info = { } unless ref $info;
312         delete $info->{version};
313         $info->{path} = $worksphere.'/'.$packagemap{$p};
314       }
315     }
316     my $nailing = "$mf.nailing~";
317     unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
318     open N, '>', $nailing or die "$self: create new $nailing: $!\n";
319     print N to_toml($toml) or die "$self: write new $nailing: $!\n";
320     close N or die "$self: close new $nailing: $!\n";
321   }
322 }
323
324 sub addargs () {
325   if (@ARGV>=2 &&
326       $ARGV[0] =~ m{\bcargo\b} &&
327       $ARGV[1] =~ m/generate-lockfile|update/) {
328     $cargo_lock_update //= 1;
329   } else {
330     $cargo_lock_update //= 0;
331   }
332   $cargo_manifest_args //=
333     (defined $oot_dir) && !$cargo_lock_update;
334
335   if ($cargo_manifest_args) {
336     push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
337       qw(--locked --target-dir=target);
338   }
339
340   if (defined $target) {
341     if ($target =~ m{^[A-Z]}) {
342       $target = (cfgs 'arch', $target) // $archmap{$target}
343         // die "$self: --target=$target alias specified; not in cfg or map\n";
344     }
345     push @ARGV, "--target=$target";
346   }
347 }
348
349 our $oot_absdir;
350 our $build_absdir; # .../Build/<subdir>
351
352 sub oot_massage_cmdline () {
353   return unless defined $oot_dir;
354
355   my $use = cfgs qw(oot use);
356   $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
357   $build_absdir = "$oot_absdir/$subdir";
358
359   my ($pre,$post);
360   my @xargs;
361   if (!$cargo_lock_update) {
362     push @xargs, $build_absdir;
363     ($pre, $post) = ('cd "$1"; shift;', '');
364   } else {
365     push @xargs, $oot_absdir, $subdir, $src_absdir;
366     ($pre, $post) = (<<'END', <<'END');
367         cd "$1"; shift;
368         mkdir -p -- "$1"; cd "$1"; shift;
369         cp -- "$1"/Cargo.toml "$1"/Cargo.lock .; shift;
370         mkdir -p src; >src/lib.rs;
371 END
372         rm -r src Cargo.toml;
373 END
374     $pre  =~ s/^\s+//mg; $pre  =~ s/^\s+\n/ /g;
375     $post =~ s/^\s+//mg; $post =~ s/^\s+\n/ /g;
376   }
377   my $addpath = (cfg_uc qw(oot path_add)) //
378     $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
379   $addpath =
380     !Types::Serialiser::is_bool $addpath ? $addpath           :
381     $addpath                             ? '$HOME/.cargo/bin' :
382                                            undef;
383   if (defined $addpath) {
384     $pre .= <<END
385         PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
386         export PATH;
387 END
388   }
389
390   my $getuser = sub { cfgsn qw(oot user) };
391   my @command;
392   my $xe = $verbose >= 2 ? 'xe' : 'e';
393   my $sh_ec = sub {
394     if (!length $post) {
395       @command = (@_, 'sh',"-${xe}c",$pre.' exec "$@"','--',@xargs);
396     } else {
397       @command = (@_, 'sh',"-${xe}c",$pre.' "$@"; '.$post,'--',@xargs);
398     }
399     push @command, @ARGV;
400   };
401   my $command_sh = sub {
402     my $quoted = join ' ', map {
403       return $_ if !m/\W/;
404       s/\'/\'\\'\'/g;
405       "'$_'"
406     } @ARGV;
407     @command = @_, "set -${xe}; $pre $quoted; $post";
408   };
409   print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
410     if $verbose;
411   if ($use eq 'really') {
412     my $user = $getuser->();
413     my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
414     my $homedir = $pw[7];
415     $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
416     print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
417   } elsif ($use eq 'ssh') {
418     my $user = $getuser->();
419     $user .= '@localhost' unless $user =~ m/\@/;
420     $command_sh->('ssh',$user);
421     print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
422   } elsif ($use eq 'command_args') {
423     my @c = cfgn_list qw(oot command);
424     $sh_ec->(@c);
425     print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
426   } elsif ($use eq 'command_sh') {
427     my @c = cfgn_list qw(oot command);
428     $command_sh->(@c);
429     print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
430   } elsif ($use eq 'null') {
431     $sh_ec->();
432   } else {
433     die "$self: oot.use mode $use not recognised\n";
434   }
435   die unless @command;
436   @ARGV = @command;
437 }
438
439 sub setenvs () {
440   $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
441   $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
442   $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
443   delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
444   $ENV{NAILINGCARGO_BUILD_DIR}    = $build_absdir // $src_absdir;
445 }
446
447 our $want_uninstall;
448
449 END {
450   if ($want_uninstall) {
451     local ($?);
452     foreach my $mf (keys %manifests) {
453       eval { uninstall1($mf,1); 1; } or warn "$@";
454     }
455   }
456 }
457
458 sub makebackups () {
459   foreach my $mf (keys %manifests) {
460     link "$mf", "$mf.unnailed" or $!==EEXIST
461       or die "$self: make backup link $mf.unnailed: $!\n";
462   }
463 }
464
465 sub nailed ($) {
466   my ($mf) = @_;
467   my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
468   $nailed;
469 }    
470
471 sub install () {
472   foreach my $mf (keys %manifests) {
473     my $nailing = "$mf.nailing~";
474     my $nailed = nailed($mf);
475     my ($use, $rm);
476     my $diff;
477     if (open NN, '<', $nailed) {
478       $diff = compare($nailing, \*NN);
479       die "$self: compare $nailing and $nailed: $!" if $diff<0;
480     } else {
481       $!==ENOENT or die "$self: check previous $nailed: $!\n";
482       $diff = 1;
483     }
484     if ($diff) {
485       $use = $nailing;
486       $rm  = $nailed;
487     } else {
488       $use = $nailed;
489       $rm  = $nailing;
490     }
491     rename $use, $mf or die "$self: install nailed $use: $!\n";
492     unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
493     print STDERR "$self: nailed $mf\n" if $verbose>=3;
494   }
495 }
496
497 sub invoke () {
498   my $r = system @ARGV;
499   if (!$r) {
500     return 0;
501   } elsif ($r<0) {
502     print STDERR "$self: could not execute $ARGV[0]: $!\n";
503     return 127;
504   } elsif ($r & 0xff00) {
505     print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
506     return $r >> 8;
507   } else {
508     print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
509     return 125;
510   }
511 }
512
513 sub cargo_lock_update_after () {
514   return unless $cargo_lock_update;
515   # avoids importing File::Copy and the error handling is about as good
516   $!=0; $?=0;
517   my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
518   die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
519   die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
520 }
521
522 sub uninstall1 ($$) {
523   my ($mf, $enoentok) = @_;
524   my $unnailed = "$mf.unnailed";
525   rename $unnailed, $mf or ($enoentok && $!==ENOENT)
526     or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
527 }
528
529 sub uninstall () {
530   foreach my $mf (keys %manifests) {
531     my $nailed = nailed($mf);
532     link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
533     uninstall1($mf,0);
534   }
535 }
536
537 while (@ARGV && $ARGV[0] =~ m/^-/) {
538   $_ = shift @ARGV;
539   last if m{^--$};
540   if (m{^-[^-]}) {
541     while (m{^-.}) {
542       if (s{^-v}{-}) {
543         $verbose++;
544       } elsif (s{^-q}{-}) {
545         $verbose=0;
546       } elsif (s{^-n}{-}) {
547         $noact++;
548       } elsif (s{^-D}{-}) {
549         $dump++;
550       } elsif (s{^-T(.+)}{-}s) {
551         $target = $1;
552       } elsif (s{^-([uU])}{-}) {
553         $cargo_lock_update= $1=~m/[A-Z]/;
554       } elsif (s{^-([mM])}{-}) {
555         $cargo_manifest_args= $1=~m/[A-Z]/;
556       } else {
557         die "$self: unknown short option(s) $_\n";
558       }
559     }
560   } elsif (s{^--target=}{}) {
561     $target = $_;
562   } elsif (m{^--(no-)?cargo-lock-update}) {
563     $cargo_lock_update= !!$1;
564   } elsif (m{^--(no-)?cargo-manifest-args}) {
565     $cargo_manifest_args= !!$1;
566   } else {
567     die "$self: unknown long option $_\n";
568   }
569 }
570
571 die "$self: need command to run\n" unless @ARGV || $noact;
572
573 takelock();
574 readnail();
575 consider_oot();
576 readorigs();
577 calculate();
578 addargs();
579 our @display_cmd = @ARGV;
580 oot_massage_cmdline();
581 setenvs();
582
583 if ($dump) {
584   eval '
585     use Data::Dumper;
586     print STDERR Dumper(\%manifests) if $dump>=2;
587     print STDERR Dumper(\%packagemap, \@ARGV,
588                         { src_absdir => $src_absdir,
589                           worksphere => $worksphere,
590                           subdir => $subdir,
591                           oot_dir => $oot_dir,
592                           oot_absdir => $oot_absdir,
593                           build_absdir => $build_absdir });
594   ' or die $@;
595 }
596
597 exit 0 if $noact;
598
599 $want_uninstall = 1;
600 makebackups();
601 install();
602
603 printf STDERR "$self: nailed (%s manifests, %s packages)\n",
604   (scalar keys %manifests), (scalar keys %packagemap)
605   if $verbose;
606
607 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
608 my $estatus = invoke();
609
610 uninstall();
611 $want_uninstall = 1;
612
613 cargo_lock_update_after();
614
615 print STDERR "$self: unnailed.  status $estatus.\n" if $verbose;
616
617 exit $estatus;