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',
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;
92 sub read_or_enoent ($) {
94 if (!open R, '<', $fn) {
95 return undef if $!==ENOENT;
96 die "$self: open $fn: $!\n";
99 my ($r) = <R> // die "$self: read $fn: $!\n";
103 sub stat_exists ($$) {
104 my ($fn, $what) = @_;
105 if (stat $fn) { return 1; }
106 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
110 sub toml_or_enoent ($$) {
112 my $toml = read_or_enoent($f) // return;
113 my ($v,$e) = from_toml($toml);
116 die "$self: parse TOML: $what: $f: $e\n";
118 die "$e ?" if length $e;
122 sub load1config ($) {
124 my $toml = toml_or_enoent($f, "config file");
125 push @configs, $toml if defined $toml;
129 my $cfgleaf = ".nailing-cargo-cfg.toml";
130 load1config("/etc/nailing-cargo/cfg.toml");
131 load1config("$worksphere/$cfgleaf");
132 load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
137 foreach my $cfg (@configs) {
139 return $v if defined $v;
144 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
148 "@$x[0..5]" eq "@$y[0..5]";
153 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
154 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
155 my @fstat = stat LOCK or die "$self: fstat: $!\n";
156 my @stat = stat $lockfile;
158 next if $! == ENOENT;
159 die "$self: stat $lockfile: $!\n";
161 last if same_file(\@fstat,\@stat);
165 unlink $lockfile or die "$self: removing lockfile: $!\n";
173 die "$self: config key \`@_': $m\n";
179 last unless defined $v;
180 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
189 my $got = ref($v) || 'scalar';
190 return $v if !defined($v) || $got eq $exp;
191 badcfg @_, "found \L$got\E, expected \L$exp\E";
192 # ^ toml doesn't make refs to scalars, so this is unambiguous
197 (cfge $exp, @_) // badcfg @_, "missing";
200 sub cfgs { cfge 'scalar', @_ }
201 sub cfgsn { cfgn 'scalar', @_ }
204 my $l = cfge 'ARRAY', @_;
205 foreach my $x (@$l) {
206 !ref $x or badcfg @_, "list contains non-scalar element";
212 my $nailfile = "../Cargo.nail";
213 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
215 my $toml = <N> // die "$self: read $nailfile: $!";
217 if ($toml !~ m{^\s*\[/}m &&
218 $toml !~ m{^[^\n\#]*\=}m &&
219 # old non-toml syntax
220 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
221 $toml =~ s{^}{[packages\]\n};
223 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
226 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
230 ($nail,$e) = from_toml($toml);
231 if (!defined $nail) {
234 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
237 die "$self: parse $nailfile: $e\n";
239 die "$e ?" if length $e;
241 if (!ref $nail->{subdirs}) {
244 map { s/^\s+//; s/\s+$//; $_; }
251 our @alt_cargo_lock_stat;
253 sub consider_alt_cargo_lock () {
254 my @ck = qw(alt_cargo_lock);
255 # User should *either* have Cargo.lock in .gitignore,
256 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
258 $alt_cargo_lock = (cfg_uc @ck) // Types::Serialiser::true;
260 if (Types::Serialiser::is_bool $alt_cargo_lock) {
261 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
262 $alt_cargo_lock = 'Cargo.lock.example';
265 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
266 badcfg @ck, "expected boolean, or leafname";
269 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
270 $alt_cargo_lock = undef;
274 @alt_cargo_lock_stat = stat _;
277 our $oot_dir; # oot.dir or "Build"
279 sub consider_oot () {
280 $oot_dir = cfgs qw(oot dir);
281 my $use = cfgs qw(oot use);
282 unless (defined($oot_dir) || defined($use)) {
283 $cargo_lock_update//=0;
286 $oot_dir //= 'Build';
292 sub read_manifest ($) {
294 my $manifest = "../$subdir/Cargo.toml";
295 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
296 if (defined $manifests{$manifest}) {
298 "$self: warning: $subdir: specified more than once!\n";
301 foreach my $try ("$manifest.unnailed", "$manifest") {
302 my $toml = toml_or_enoent($try, "package manifest") // next;
303 my $p = $toml->{package}{name};
306 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
309 $manifests{$manifest} = $toml;
316 foreach my $p (keys %{ $nail->{packages} }) {
317 my $v = $nail->{packages}{$p};
318 my $subdir = ref($v) ? $v->{subdir} : $v;
319 my $gotpackage = read_manifest($subdir) // '<nothing!>';
320 if ($gotpackage ne $p) {
322 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
324 die if defined $packagemap{$p};
325 $packagemap{$p} = $subdir;
327 foreach my $subdir (@{ $nail->{subdirs} }) {
328 my $gotpackage = read_manifest($subdir);
329 if (!defined $gotpackage) {
331 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
334 $packagemap{$gotpackage} //= $subdir;
339 foreach my $p (sort keys %packagemap) {
340 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
342 foreach my $mf (keys %manifests) {
343 my $toml = $manifests{$mf};
344 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
345 my $deps = $toml->{$k};
347 foreach my $p (keys %packagemap) {
348 my $info = $deps->{$p};
349 next unless defined $info;
350 $deps->{$p} = $info = { } unless ref $info;
351 delete $info->{version};
352 $info->{path} = $worksphere.'/'.$packagemap{$p};
355 my $nailing = "$mf.nailing~";
356 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
357 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
358 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
359 close N or die "$self: close new $nailing: $!\n";
365 $ARGV[0] =~ m{\bcargo\b} &&
366 $ARGV[1] =~ m/generate-lockfile|update/) {
367 $cargo_lock_update //= 1;
369 $cargo_lock_update //= 0;
371 $cargo_manifest_args //=
372 (defined $oot_dir) && !$cargo_lock_update;
374 if ($cargo_manifest_args) {
375 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
376 qw(--locked --target-dir=target);
379 if (defined $target) {
380 if ($target =~ m{^[A-Z]}) {
381 $target = (cfgs 'arch', $target) // $archmap{$target}
382 // die "$self: --target=$target alias specified; not in cfg or map\n";
384 push @ARGV, "--target=$target";
389 our $build_absdir; # .../Build/<subdir>
391 sub oot_massage_cmdline () {
392 return unless defined $oot_dir;
394 my $use = cfgs qw(oot use);
395 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
396 $build_absdir = "$oot_absdir/$subdir";
400 if (!$cargo_lock_update) {
401 push @xargs, $build_absdir;
402 ($pre, $post) = ('cd "$1"; shift; ', '');
404 push @xargs, $oot_absdir, $subdir, $src_absdir;
407 mkdir -p -- "$1"; cd "$1"; shift;
408 cp -- "$1"/Cargo.toml
410 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
418 mkdir -p src; >src/lib.rs;
421 rm -r src Cargo.toml;
424 my $addpath = (cfg_uc qw(oot path_add)) //
425 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
427 !Types::Serialiser::is_bool $addpath ? $addpath :
428 $addpath ? '$HOME/.cargo/bin' :
430 if (defined $addpath) {
432 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
436 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
437 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
439 my $getuser = sub { cfgsn qw(oot user) };
441 my $xe = $verbose >= 2 ? 'xe' : 'e';
444 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
446 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
448 push @command, @ARGV;
450 my $command_sh = sub {
451 my $quoted = join ' ', map {
456 @command = @_, "set -${xe}; $pre $quoted; $post";
458 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
460 if ($use eq 'really') {
461 my $user = $getuser->();
462 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
463 my $homedir = $pw[7];
464 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
465 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
466 } elsif ($use eq 'ssh') {
467 my $user = $getuser->();
468 $user .= '@localhost' unless $user =~ m/\@/;
469 $command_sh->('ssh',$user);
470 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
471 } elsif ($use eq 'command_args') {
472 my @c = cfgn_list qw(oot command);
474 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
475 } elsif ($use eq 'command_sh') {
476 my @c = cfgn_list qw(oot command);
478 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
479 } elsif ($use eq 'null') {
482 die "$self: oot.use mode $use not recognised\n";
489 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
490 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
491 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
492 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
493 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
499 if ($want_uninstall) {
501 foreach my $mf (keys %manifests) {
502 eval { uninstall1($mf,1); 1; } or warn "$@";
504 unaltcargolock(1) or warn "$@";
508 our $cleanup_remove_cargo_lock;
510 foreach my $mf (keys %manifests) {
511 link "$mf", "$mf.unnailed" or $!==EEXIST
512 or die "$self: make backup link $mf.unnailed: $!\n";
515 if (defined $alt_cargo_lock) {
516 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
518 if (link $alt_cargo_lock, 'Cargo.lock') {
519 print STDERR " linked\n" if $verbose>=3;
520 } elsif ($! != EEXIST) {
521 print STDERR "\n" if $verbose>=3;
522 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
524 print STDERR "checking quality." if $verbose>=3;
525 my @lock_stat = stat 'Cargo.lock'
526 or die "$self: stat Cargo.lock (for alt check: $!\n";
527 same_file(\@alt_cargo_lock_stat, \@lock_stat)
529 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
531 $cleanup_remove_cargo_lock = 1;
537 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
542 foreach my $mf (keys %manifests) {
543 my $nailing = "$mf.nailing~";
544 my $nailed = nailed($mf);
547 if (open NN, '<', $nailed) {
548 $diff = compare($nailing, \*NN);
549 die "$self: compare $nailing and $nailed: $!" if $diff<0;
551 $!==ENOENT or die "$self: check previous $nailed: $!\n";
561 rename $use, $mf or die "$self: install nailed $use: $!\n";
562 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
563 print STDERR "$self: nailed $mf\n" if $verbose>=3;
568 my $r = system @ARGV;
572 print STDERR "$self: could not execute $ARGV[0]: $!\n";
574 } elsif ($r & 0xff00) {
575 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
578 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
583 sub cargo_lock_update_after () {
584 return unless $cargo_lock_update;
585 # avoids importing File::Copy and the error handling is about as good
587 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
588 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
589 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
592 sub uninstall1 ($$) {
593 my ($mf, $enoentok) = @_;
594 my $unnailed = "$mf.unnailed";
595 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
596 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
599 sub unaltcargolock ($) {
601 return unless $cleanup_remove_cargo_lock;
602 die 'internal error!' unless defined $alt_cargo_lock;
603 unlink 'Cargo.lock' or ($enoentok && $!==ENOENT) or die
604 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
608 foreach my $mf (keys %manifests) {
609 my $nailed = nailed($mf);
610 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
616 while (@ARGV && $ARGV[0] =~ m/^-/) {
623 } elsif (s{^-q}{-}) {
625 } elsif (s{^-n}{-}) {
627 } elsif (s{^-D}{-}) {
629 } elsif (s{^-T(.+)}{-}s) {
631 } elsif (s{^-([uU])}{-}) {
632 $cargo_lock_update= $1=~m/[a-z]/;
633 } elsif (s{^-([mM])}{-}) {
634 $cargo_manifest_args= $1=~m/[a-z]/;
636 die "$self: unknown short option(s) $_\n";
639 } elsif (s{^--target=}{}) {
641 } elsif (m{^--(no-)?cargo-lock-update}) {
642 $cargo_lock_update= !!$1;
643 } elsif (m{^--(no-)?cargo-manifest-args}) {
644 $cargo_manifest_args= !!$1;
646 die "$self: unknown long option $_\n";
650 die "$self: need command to run\n" unless @ARGV || $noact;
654 consider_alt_cargo_lock();
659 our @display_cmd = @ARGV;
660 oot_massage_cmdline();
666 print STDERR Dumper(\%manifests) if $dump>=2;
667 print STDERR Dumper(\%packagemap, \@ARGV,
668 { src_absdir => $src_absdir,
669 worksphere => $worksphere,
672 oot_absdir => $oot_absdir,
673 build_absdir => $build_absdir });
683 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
684 (scalar keys %manifests), (scalar keys %packagemap),
685 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
688 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
689 my $estatus = invoke();
691 cargo_lock_update_after();
696 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;