3 # nailing-cargo: wrapper to use unpublished local crates
5 # Copyright (C) 2019-2020 Ian Jackson
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.
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.
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/>.
21 # ../nailing-cargo/nailing-caretwgo make
22 # ../nailing-cargo/nailing-cargo cargo build
23 # CARGO='../nailing-cargo/nailing-cargo cargo' make
25 # Why do we need this ?
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
37 # package = { subdir = ... }
46 use Types::Serialiser;
49 # RPI => 'arm-unknown-linux-gnueabihf', xxx
53 $self = $0; $self =~ s{^.*/(?=.)}{};
55 while ($deref =~ m{^/}) {
56 my $link = readlink $deref;
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";
65 last if $link !~ m{^/};
70 use Fcntl qw(LOCK_EX);
72 use TOML::Tiny::Faithful;
74 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
76 our $worksphere = $src_absdir;
77 $worksphere =~ s{/([^/]+)$}{}
78 or die "$self: cwd \`$worksphere' unsupported!\n";
79 our $subdir = $1; # leafname
81 our $lockfile = "../.nailing-cargo.lock";
83 our $cargo_lock_update;
84 our $cargo_manifest_args;
91 sub read_or_enoent ($) {
93 if (!open R, '<', $fn) {
94 return undef if $!==ENOENT;
95 die "$self: open $fn: $!\n";
98 my ($r) = <R> // die "$self: read $fn: $!\n";
102 sub toml_or_enoent ($$) {
104 my $toml = read_or_enoent($f) // return;
105 my ($v,$e) = from_toml($toml);
108 die "$self: parse TOML: $what: $f: $e\n";
110 die "$e ?" if length $e;
114 sub load1config ($) {
116 my $toml = toml_or_enoent($f, "config file");
117 push @configs, $toml if defined $toml;
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};
129 foreach my $cfg (@configs) {
131 return $v if defined $v;
136 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
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;
145 next if $! == ENOENT;
146 die "$self: stat $lockfile: $!\n";
148 last if "@fstat[0..5]" eq "@stat[0..5]";
152 unlink $lockfile or die "$self: removing lockfile: $!\n";
160 die "$self: config key \`@_': $m\n";
166 last unless defined $v;
167 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
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
184 (cfg $exp, @_) // badcfg @_, "missing";
187 sub cfgs { cfg 'scalar', @_ }
188 sub cfgsn { cfgn 'scalar', @_ }
191 my $l = cfg 'ARRAY', @_;
192 foreach my $x (@$l) {
193 !ref $x or badcfg @_, "list contains non-scalar element";
199 my $nailfile = "../Cargo.nail";
200 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
202 my $toml = <N> // die "$self: read $nailfile: $!";
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};
210 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
213 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
217 ($nail,$e) = from_toml($toml);
218 if (!defined $nail) {
221 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
224 die "$self: parse $nailfile: $e\n";
226 die "$e ?" if length $e;
228 if (!ref $nail->{subdirs}) {
231 map { s/^\s+//; s/\s+$//; $_; }
238 our $oot_dir; # oot.dir or "Build"
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;
247 $oot_dir //= 'Build';
253 sub read_manifest ($) {
255 my $manifest = "../$subdir/Cargo.toml";
256 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
257 if (defined $manifests{$manifest}) {
259 "$self: warning: $subdir: specified more than once!\n";
262 foreach my $try ("$manifest.unnailed", "$manifest") {
263 my $toml = toml_or_enoent($try, "package manifest") // next;
264 my $p = $toml->{package}{name};
267 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
270 $manifests{$manifest} = $toml;
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) {
283 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
285 die if defined $packagemap{$p};
286 $packagemap{$p} = $subdir;
288 foreach my $subdir (@{ $nail->{subdirs} }) {
289 my $gotpackage = read_manifest($subdir);
290 if (!defined $gotpackage) {
292 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
295 $packagemap{$gotpackage} //= $subdir;
300 foreach my $p (sort keys %packagemap) {
301 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
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};
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};
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";
326 $ARGV[0] =~ m{\bcargo\b} &&
327 $ARGV[1] =~ m/generate-lockfile|update/) {
328 $cargo_lock_update //= 1;
330 $cargo_lock_update //= 0;
332 $cargo_manifest_args //=
333 (defined $oot_dir) && !$cargo_lock_update;
335 if ($cargo_manifest_args) {
336 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
337 qw(--locked --target-dir=target);
340 if (defined $target) {
341 if ($target =~ m{^[A-Z]}) {
342 $target = (cfg 'arch', $target) // $archmap{$target}
343 // die "$self: --target=$target alias specified; not in cfg or map\n";
345 push @ARGV, "--target=$target";
350 our $build_absdir; # .../Build/<subdir>
352 sub oot_massage_cmdline () {
353 return unless defined $oot_dir;
355 my $use = cfgs qw(oot use);
356 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
357 $build_absdir = "$oot_absdir/$subdir";
361 if (!$cargo_lock_update) {
362 push @xargs, $build_absdir;
363 ($pre, $post) = ('cd "$1"; shift;', '');
365 push @xargs, $oot_absdir, $subdir, $src_absdir;
366 ($pre, $post) = (<<'END', <<'END');
368 mkdir -p -- "$1"; cd "$1"; shift;
369 cp -- "$1"/Cargo.toml "$1"/Cargo.lock .; shift;
370 mkdir -p src; >src/lib.rs;
372 rm -r src Cargo.toml;
374 $pre =~ s/^\s+//mg; $pre =~ s/^\s+\n/ /g;
375 $post =~ s/^\s+//mg; $post =~ s/^\s+\n/ /g;
377 my $addpath = (cfg qw(oot path_add)) //
378 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
380 !Types::Serialiser::is_bool $addpath ? $addpath :
381 $addpath ? '$HOME/.cargo/bin' :
383 if (defined $addpath) {
385 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
390 my $getuser = sub { cfgsn qw(oot user) };
392 my $xe = $verbose >= 2 ? 'xe' : 'e';
395 @command = (@_, 'sh',"-${xe}c",$pre.' exec "$@"','--',@xargs);
397 @command = (@_, 'sh',"-${xe}c",$pre.' "$@"; '.$post,'--',@xargs);
399 push @command, @ARGV;
401 my $command_sh = sub {
402 my $quoted = join ' ', map {
407 @command = @_, "set -${xe}; $pre $quoted; $post";
409 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
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);
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);
429 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
431 die "$self: oot.use mode $use not recognised\n";
438 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
439 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
440 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
441 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
442 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
448 if ($want_uninstall) {
450 foreach my $mf (keys %manifests) {
451 eval { uninstall1($mf,1); 1; } or warn "$@";
457 foreach my $mf (keys %manifests) {
458 link "$mf", "$mf.unnailed" or $!==EEXIST
459 or die "$self: make backup link $mf.unnailed: $!\n";
465 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
470 foreach my $mf (keys %manifests) {
471 my $nailing = "$mf.nailing~";
472 my $nailed = nailed($mf);
475 if (open NN, '<', $nailed) {
476 $diff = compare($nailing, \*NN);
477 die "$self: compare $nailing and $nailed: $!" if $diff<0;
479 $!==ENOENT or die "$self: check previous $nailed: $!\n";
489 rename $use, $mf or die "$self: install nailed $use: $!\n";
490 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
491 print STDERR "$self: nailed $mf\n" if $verbose>=3;
496 my $r = system @ARGV;
500 print STDERR "$self: could not execute $ARGV[0]: $!\n";
502 } elsif ($r & 0xff00) {
503 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
506 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
511 sub cargo_lock_update_after () {
512 return unless $cargo_lock_update;
513 # avoids importing File::Copy and the error handling is about as good
515 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
516 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
517 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
520 sub uninstall1 ($$) {
521 my ($mf, $enoentok) = @_;
522 my $unnailed = "$mf.unnailed";
523 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
524 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
528 foreach my $mf (keys %manifests) {
529 my $nailed = nailed($mf);
530 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
535 while (@ARGV && $ARGV[0] =~ m/^-/) {
542 } elsif (s{^-q}{-}) {
544 } elsif (s{^-n}{-}) {
546 } elsif (s{^-D}{-}) {
548 } elsif (s{^-T(.+)}{-}s) {
550 } elsif (s{^-([uU])}{-}) {
551 $cargo_lock_update= $1=~m/[A-Z]/;
552 } elsif (s{^-([mM])}{-}) {
553 $cargo_manifest_args= $1=~m/[A-Z]/;
555 die "$self: unknown short option(s) $_\n";
558 } elsif (s{^--target=}{}) {
560 } elsif (m{^--no-cargo-lock-update}) {
561 $cargo_lock_update=0;
563 die "$self: unknown long option $_\n";
567 die "$self: need command to run\n" unless @ARGV || $noact;
575 our @display_cmd = @ARGV;
576 oot_massage_cmdline();
582 print STDERR Dumper(\%manifests) if $dump>=2;
583 print STDERR Dumper(\%packagemap, \@ARGV,
584 { src_absdir => $src_absdir,
585 worksphere => $worksphere,
588 oot_absdir => $oot_absdir,
589 build_absdir => $build_absdir });
599 printf STDERR "$self: nailed (%s manifests, %s packages)\n",
600 (scalar keys %manifests), (scalar keys %packagemap)
603 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
604 my $estatus = invoke();
609 cargo_lock_update_after();
611 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;