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', @_ }
205 return $v if !defined($v) || Types::Serialiser::is_bool $v;
206 badcfg @_, "expected boolean";
210 my $l = cfge 'ARRAY', @_;
211 foreach my $x (@$l) {
212 !ref $x or badcfg @_, "list contains non-scalar element";
218 my $nailfile = "../Cargo.nail";
219 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
221 my $toml = <N> // die "$self: read $nailfile: $!";
223 if ($toml !~ m{^\s*\[/}m &&
224 $toml !~ m{^[^\n\#]*\=}m &&
225 # old non-toml syntax
226 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
227 $toml =~ s{^}{[packages\]\n};
229 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
232 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
236 ($nail,$e) = from_toml($toml);
237 if (!defined $nail) {
240 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
243 die "$self: parse $nailfile: $e\n";
245 die "$e ?" if length $e;
247 if (!ref $nail->{subdirs}) {
250 map { s/^\s+//; s/\s+$//; $_; }
257 our @alt_cargo_lock_stat;
259 sub consider_alt_cargo_lock () {
260 my @ck = qw(alt_cargo_lock);
261 # User should *either* have Cargo.lock in .gitignore,
262 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
264 $alt_cargo_lock = (cfg_uc @ck);
267 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
268 $force = cfg_bool qw(alt_cargo_lock force);
269 my @ck = qw(alt_cargo_lock file);
270 $alt_cargo_lock = cfg_uc @ck;
272 $alt_cargo_lock //= Types::Serialiser::true;
274 if (Types::Serialiser::is_bool $alt_cargo_lock) {
275 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
276 $alt_cargo_lock = 'Cargo.lock.example';
279 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
280 badcfg @ck, "expected boolean, or leafname";
283 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
284 $alt_cargo_lock = undef unless $force;
288 @alt_cargo_lock_stat = stat _;
291 our $oot_dir; # oot.dir or "Build"
293 sub consider_oot () {
294 $oot_dir = cfgs qw(oot dir);
295 my $use = cfgs qw(oot use);
296 unless (defined($oot_dir) || defined($use)) {
297 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
298 if $cargo_lock_update;
299 $cargo_lock_update=0;
302 $oot_dir //= 'Build';
308 sub read_manifest ($) {
310 my $manifest = "../$subdir/Cargo.toml";
311 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
312 if (defined $manifests{$manifest}) {
314 "$self: warning: $subdir: specified more than once!\n";
317 foreach my $try ("$manifest.unnailed", "$manifest") {
318 my $toml = toml_or_enoent($try, "package manifest") // next;
319 my $p = $toml->{package}{name};
322 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
325 $manifests{$manifest} = $toml;
332 foreach my $p (keys %{ $nail->{packages} }) {
333 my $v = $nail->{packages}{$p};
334 my $subdir = ref($v) ? $v->{subdir} : $v;
335 my $gotpackage = read_manifest($subdir) // '<nothing!>';
336 if ($gotpackage ne $p) {
338 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
340 die if defined $packagemap{$p};
341 $packagemap{$p} = $subdir;
343 foreach my $subdir (@{ $nail->{subdirs} }) {
344 my $gotpackage = read_manifest($subdir);
345 if (!defined $gotpackage) {
347 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
350 $packagemap{$gotpackage} //= $subdir;
355 foreach my $p (sort keys %packagemap) {
356 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
358 foreach my $mf (keys %manifests) {
359 my $toml = $manifests{$mf};
360 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
361 my $deps = $toml->{$k};
363 foreach my $p (keys %packagemap) {
364 my $info = $deps->{$p};
365 next unless defined $info;
366 $deps->{$p} = $info = { } unless ref $info;
367 delete $info->{version};
368 $info->{path} = $worksphere.'/'.$packagemap{$p};
371 my $nailing = "$mf.nailing~";
372 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
373 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
374 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
375 close N or die "$self: close new $nailing: $!\n";
381 $ARGV[0] =~ m{\bcargo\b} &&
382 $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
383 $cargo_lock_update //= 1;
386 $cargo_lock_update //= 0;
388 $cargo_manifest_args //=
389 (defined $oot_dir) && !$cargo_lock_update;
391 if ($cargo_manifest_args) {
392 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
393 qw(--locked --target-dir=target);
396 if (defined $target) {
397 if ($target =~ m{^[A-Z]}) {
398 $target = (cfgs 'arch', $target) // $archmap{$target}
399 // die "$self: --target=$target alias specified; not in cfg or map\n";
401 push @ARGV, "--target=$target";
406 our $build_absdir; # .../Build/<subdir>
408 sub oot_massage_cmdline () {
409 return unless defined $oot_dir;
411 my $use = cfgs qw(oot use);
412 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
413 $build_absdir = "$oot_absdir/$subdir";
417 if (!$cargo_lock_update) {
418 push @xargs, $build_absdir;
419 ($pre, $post) = ('cd "$1"; shift; ', '');
421 push @xargs, $oot_absdir, $subdir, $src_absdir;
424 mkdir -p -- "$1"; cd "$1"; shift;
425 cp -- "$1"/Cargo.toml
427 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
435 mkdir -p src; >src/lib.rs;
438 rm -r src Cargo.toml;
441 my $addpath = (cfg_uc qw(oot path_add)) //
442 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
444 !Types::Serialiser::is_bool $addpath ? $addpath :
445 $addpath ? '$HOME/.cargo/bin' :
447 if (defined $addpath) {
449 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
453 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
454 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
456 my $getuser = sub { cfgsn qw(oot user) };
458 my $xe = $verbose >= 2 ? 'xe' : 'e';
461 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
463 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
465 push @command, @ARGV;
467 my $command_sh = sub {
468 my $quoted = join ' ', map {
473 @command = @_, "set -${xe}; $pre $quoted; $post";
475 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
477 if ($use eq 'really') {
478 my $user = $getuser->();
479 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
480 my $homedir = $pw[7];
481 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
482 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
483 } elsif ($use eq 'ssh') {
484 my $user = $getuser->();
485 $user .= '@localhost' unless $user =~ m/\@/;
486 $command_sh->('ssh',$user);
487 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
488 } elsif ($use eq 'command_args') {
489 my @c = cfgn_list qw(oot command);
491 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
492 } elsif ($use eq 'command_sh') {
493 my @c = cfgn_list qw(oot command);
495 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
496 } elsif ($use eq 'null') {
499 die "$self: oot.use mode $use not recognised\n";
506 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
507 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
508 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
509 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
510 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
516 if ($want_uninstall) {
518 foreach my $mf (keys %manifests) {
519 eval { uninstall1($mf,1); 1; } or warn "$@";
521 eval { unaltcargolock(1); 1; } or warn "$@";
525 our $cleanup_cargo_lock;
527 foreach my $mf (keys %manifests) {
528 link "$mf", "$mf.unnailed" or $!==EEXIST
529 or die "$self: make backup link $mf.unnailed: $!\n";
532 if (defined($alt_cargo_lock)) {
533 if (@alt_cargo_lock_stat) {
534 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
536 if (link $alt_cargo_lock, 'Cargo.lock') {
537 print STDERR " linked\n" if $verbose>=3;
538 } elsif ($! != EEXIST) {
539 print STDERR "\n" if $verbose>=3;
540 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
542 print STDERR "checking quality." if $verbose>=3;
543 my @lock_stat = stat 'Cargo.lock'
544 or die "$self: stat Cargo.lock (for alt check: $!\n";
545 same_file(\@alt_cargo_lock_stat, \@lock_stat)
547 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
549 $cleanup_cargo_lock = 1;
551 $cleanup_cargo_lock = 1;
552 # If Cargo.lock exists and alt doesn't, that means either
553 # that a previous run was interrupted, or that the user has
561 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
566 foreach my $mf (keys %manifests) {
567 my $nailing = "$mf.nailing~";
568 my $nailed = nailed($mf);
571 if (open NN, '<', $nailed) {
572 $diff = compare($nailing, \*NN);
573 die "$self: compare $nailing and $nailed: $!" if $diff<0;
575 $!==ENOENT or die "$self: check previous $nailed: $!\n";
585 rename $use, $mf or die "$self: install nailed $use: $!\n";
586 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
587 print STDERR "$self: nailed $mf\n" if $verbose>=3;
592 my $r = system @ARGV;
596 print STDERR "$self: could not execute $ARGV[0]: $!\n";
598 } elsif ($r & 0xff00) {
599 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
602 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
607 sub cargo_lock_update_after () {
608 if ($cargo_lock_update) {
609 # avoids importing File::Copy and the error handling is about as good
611 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
612 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
613 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
617 sub uninstall1 ($$) {
618 my ($mf, $enoentok) = @_;
619 my $unnailed = "$mf.unnailed";
620 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
621 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
624 sub unaltcargolock ($) {
626 return unless $cleanup_cargo_lock;
627 die 'internal error!' unless defined $alt_cargo_lock;
629 # we ignore $enoentok because we don't know if one was supposed to
632 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
633 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
635 unlink 'Cargo.lock' or $!==ENOENT or die
636 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
637 # ^ this also helps clean up the stupid rename() corner case
641 foreach my $mf (keys %manifests) {
642 my $nailed = nailed($mf);
643 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
649 while (@ARGV && $ARGV[0] =~ m/^-/) {
656 } elsif (s{^-q}{-}) {
658 } elsif (s{^-n}{-}) {
660 } elsif (s{^-D}{-}) {
662 } elsif (s{^-T(.+)}{-}s) {
664 } elsif (s{^-([uU])}{-}) {
665 $cargo_lock_update= $1=~m/[a-z]/;
666 } elsif (s{^-([mM])}{-}) {
667 $cargo_manifest_args= $1=~m/[a-z]/;
669 die "$self: unknown short option(s) $_\n";
672 } elsif (s{^--target=}{}) {
674 } elsif (m{^--(no-)?cargo-lock-update}) {
675 $cargo_lock_update= !!$1;
676 } elsif (m{^--(no-)?cargo-manifest-args}) {
677 $cargo_manifest_args= !!$1;
679 die "$self: unknown long option $_\n";
683 die "$self: need command to run\n" unless @ARGV || $noact;
687 consider_alt_cargo_lock();
692 our @display_cmd = @ARGV;
693 oot_massage_cmdline();
699 print STDERR Dumper(\%manifests) if $dump>=2;
700 print STDERR Dumper(\%packagemap, \@ARGV,
701 { src_absdir => $src_absdir,
702 worksphere => $worksphere,
705 oot_absdir => $oot_absdir,
706 build_absdir => $build_absdir });
716 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
717 (scalar keys %manifests), (scalar keys %packagemap),
718 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
721 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
722 my $estatus = invoke();
724 cargo_lock_update_after();
729 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;