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-cargo make
22 # ../nailing-cargo/nailing-cargo cargo build
24 # Why do we need this ?
26 # https://github.com/rust-lang/cargo/issues/6713
27 # https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate
28 # https://github.com/rust-lang/cargo/issues/1481
31 # -v Increase verbosity. Default is 1.
32 # -q Set verbosity ot 0.
33 # -D Increase amount of debugging dump.
35 # -n "No action": stop after writing Cargo.toml.nailing~
36 # everywhere, and do not run any build command.
38 # -T<arch> --target=<arch>
39 # Specify target architecture. If <arch> starts with a
40 # capital ascii letter, is an alias for some other arch
41 # looked up in Cargo.nail and then in the builtin list:
42 # RPI arm-unknown-linux-gnueabihf
43 # Translates to a --target= option to the ultimate command,
44 # unless that is a cargo subcommand which would reject it.
46 # -u | --cargo-lock-update
47 # -U | --no-cargo-lock-update
48 # Arranges to do a dance to allow Cargo.lock (or
49 # alternative) to be updated in the source directory.
51 # The Cargo.lock and Cargo.toml are copied to the build
52 # directory along with a skeleton just big enough to fool
53 # cargo. After cargo has run, the resulting Cargo.lock is
54 # copied back to the source tree.
56 # Makes no sense with in-tree builds.
58 # Default is no update unless the ultimate command is a
59 # cargo subcommand which we know needs it.
61 # -m | --cargo-manifest-args
62 # -M | --no-cargo-manifest-args
63 # Controls whether we add cargo command line options
64 # relating to finding Cargo.toml, to the command to
67 # Default is true if we are doing an out-of- tree build,
68 # unless we are updating the Cargo.lock (in which case the
69 # only relevant files are to be found in the build directory).
72 # --manifest-path=<path/to/Cargo.toml>
76 # -T | --no-cargo-target-arg
77 # -t | --cargo-target-arg
78 # Suppress --target (or un-suppress it).
79 # Only useful with -m.
83 # # Adds each <subdir> to the list of directories whose
84 # # Cargo.toml is to be nailed, and also arranges to use
85 # # the package found there for other directories if
86 # # no other source of that package is evident in Cargo.nail.
97 # # Adds <subdir> to the list of directories whose Cargo.toml
98 # # is to be nailed, and overrides any other nailing for <package>
100 # <package> = <subdir>
101 # <package> = { <subdir> = ... }
103 # To control use of alternative Cargo.lock filename:
106 # file = true # equivalent to "Cargo.lock.example"
107 # file = false # disables this feature
108 # file = "<some leafname>"
110 # force = false # default, uses alt file only if it already exists
111 # force = true # always uses alt file; creation would make Cargo.lock
113 # (you can also specify just alt_cargo_lock instead of alt_cargo_lock.file)
115 # To enable out of tree builds:
117 # dir = "<build-directory>" # default is Build, if use is specified
120 # user = "<someuser>"
123 # user = "<user>@host" # NB must still share a filesystem!
125 # use = "command_args"
126 # command = ["<command>", "<which works like>", "nice"]
129 # command = ["<command>", "<which work like>", "sh -c"]
135 # Always dirties everyone's Cargo.toml, but tries to put them
136 # back (if not, running it again should fix it). Cannnot be
137 # fixed without changes to cargo.
139 # Out of tree builds require a unified filesystem view: eg,
140 # different users on the same host, NFS, or something. This
143 # Alternative Cargo.lock file must currently be a leafname.
144 # I think this just involves review to check other values work.
146 # Alternative Cargo.lock file must be on smae filesystem.
147 # This is not so easy; we would want the existing algorithm but
148 # a fallback for this case.
150 # Cargo.nail unconditionally looked for in ..
151 # Ideally should be configurable, and also perhaps be able
152 # to combine multiple Cargo.nail files ?
154 # Env vars we pass to the command:
155 # NAILINGCARGO_WORKSPHERE absolute path of invocation ..
156 # NAILINGCARGO_MANIFEST_DIR absolute path of invocation .
157 # NAILINGCARGO_BUILDSPHERE only if out of tree: abs parent of build dir
158 # NAILINGCARGO_BUILD_DIR absolute path of build dir (even if = src)
165 use Types::Serialiser;
168 RPI => 'arm-unknown-linux-gnueabihf',
172 $self = $0; $self =~ s{^.*/(?=.)}{};
174 while ($deref =~ m{^/}) {
175 my $link = readlink $deref;
176 if (!defined $link) {
178 or die "$self: checking our script location $deref: $!\n";
179 $deref =~ s{/[^/]+$}{}
180 or die "$self: unexpected script path: $deref\n";
181 unshift @INC, $deref."/TOML-Tiny/lib";
184 last if $link !~ m{^/};
189 use Fcntl qw(LOCK_EX);
191 use TOML::Tiny::Faithful;
193 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
195 our $worksphere = $src_absdir;
196 $worksphere =~ s{/([^/]+)$}{}
197 or die "$self: cwd \`$worksphere' unsupported!\n";
198 our $subdir = $1; # leafname
200 our $lockfile = "../.nailing-cargo.lock";
202 our $cargo_lock_update;
203 our $cargo_manifest_args;
204 our $cargo_target_arg=1;
212 sub read_or_enoent ($) {
214 if (!open R, '<', $fn) {
215 return undef if $!==ENOENT;
216 die "$self: open $fn: $!\n";
219 my ($r) = <R> // die "$self: read $fn: $!\n";
223 sub stat_exists ($$) {
224 my ($fn, $what) = @_;
225 if (stat $fn) { return 1; }
226 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
230 sub toml_or_enoent ($$) {
232 my $toml = read_or_enoent($f) // return;
233 my ($v,$e) = from_toml($toml);
236 die "$self: parse TOML: $what: $f: $e\n";
238 die "$e ?" if length $e;
242 sub load1config ($) {
244 my $toml = toml_or_enoent($f, "config file");
245 push @configs, $toml if defined $toml;
249 my $cfgleaf = ".nailing-cargo-cfg.toml";
250 load1config("/etc/nailing-cargo/cfg.toml");
251 load1config("$worksphere/$cfgleaf");
252 load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
257 foreach my $cfg (@configs) {
259 return $v if defined $v;
264 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
268 "@$x[0..5]" eq "@$y[0..5]";
273 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
274 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
275 my @fstat = stat LOCK or die "$self: fstat: $!\n";
276 my @stat = stat $lockfile;
278 next if $! == ENOENT;
279 die "$self: stat $lockfile: $!\n";
281 last if same_file(\@fstat,\@stat);
285 unlink $lockfile or die "$self: removing lockfile: $!\n";
293 die "$self: config key \`@_': $m\n";
299 last unless defined $v;
300 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
309 my $got = ref($v) || 'scalar';
310 return $v if !defined($v) || $got eq $exp;
311 badcfg @_, "found \L$got\E, expected \L$exp\E";
312 # ^ toml doesn't make refs to scalars, so this is unambiguous
317 (cfge $exp, @_) // badcfg @_, "missing";
320 sub cfgs { cfge 'scalar', @_ }
321 sub cfgsn { cfgn 'scalar', @_ }
325 return $v if !defined($v) || Types::Serialiser::is_bool $v;
326 badcfg @_, "expected boolean";
330 my $l = cfge 'ARRAY', @_;
331 foreach my $x (@$l) {
332 !ref $x or badcfg @_, "list contains non-scalar element";
338 my $nailfile = "../Cargo.nail";
339 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
341 my $toml = <N> // die "$self: read $nailfile: $!";
343 if ($toml !~ m{^\s*\[/}m &&
344 $toml !~ m{^[^\n\#]*\=}m &&
345 # old non-toml syntax
346 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
347 $toml =~ s{^}{[packages\]\n};
349 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
352 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
356 ($nail,$e) = from_toml($toml);
357 if (!defined $nail) {
360 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
363 die "$self: parse $nailfile: $e\n";
365 die "$e ?" if length $e;
367 $nail->{subdirs} //= [ ];
369 if (!ref $nail->{subdirs}) {
372 map { s/^\s+//; s/\s+$//; $_; }
379 our @alt_cargo_lock_stat;
381 sub consider_alt_cargo_lock () {
382 my @ck = qw(alt_cargo_lock);
383 # User should *either* have Cargo.lock in .gitignore,
384 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
386 $alt_cargo_lock = (cfg_uc @ck);
389 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
390 $force = cfg_bool qw(alt_cargo_lock force);
391 my @ck = qw(alt_cargo_lock file);
392 $alt_cargo_lock = cfg_uc @ck;
394 $alt_cargo_lock //= Types::Serialiser::true;
396 if (Types::Serialiser::is_bool $alt_cargo_lock) {
397 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
398 $alt_cargo_lock = 'Cargo.lock.example';
401 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
402 badcfg @ck, "expected boolean, or leafname";
405 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
406 $alt_cargo_lock = undef unless $force;
410 @alt_cargo_lock_stat = stat _;
413 our $oot_dir; # oot.dir or "Build"
415 sub consider_oot () {
416 $oot_dir = cfgs qw(oot dir);
417 my $use = cfgs qw(oot use);
418 unless (defined($oot_dir) || defined($use)) {
419 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
420 if $cargo_lock_update;
421 $cargo_lock_update=0;
424 $oot_dir //= 'Build';
430 sub read_manifest ($) {
432 my $manifest = "../$subdir/Cargo.toml";
433 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
434 if (defined $manifests{$manifest}) {
436 "$self: warning: $subdir: specified more than once!\n";
439 foreach my $try ("$manifest.unnailed", "$manifest") {
440 my $toml = toml_or_enoent($try, "package manifest") // next;
441 my $p = $toml->{package}{name};
444 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
447 $manifests{$manifest} = $toml;
454 foreach my $p (keys %{ $nail->{packages} }) {
455 my $v = $nail->{packages}{$p};
456 my $subdir = ref($v) ? $v->{subdir} : $v;
457 my $gotpackage = read_manifest($subdir) // '<nothing!>';
458 if ($gotpackage ne $p) {
460 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
462 die if defined $packagemap{$p};
463 $packagemap{$p} = $subdir;
465 foreach my $subdir (@{ $nail->{subdirs} }) {
466 my $gotpackage = read_manifest($subdir);
467 if (!defined $gotpackage) {
469 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
472 $packagemap{$gotpackage} //= $subdir;
477 foreach my $p (sort keys %packagemap) {
478 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
480 foreach my $mf (keys %manifests) {
481 my $toml = $manifests{$mf};
482 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
483 my $deps = $toml->{$k};
485 foreach my $p (keys %packagemap) {
486 my $info = $deps->{$p};
487 next unless defined $info;
488 $deps->{$p} = $info = { } unless ref $info;
489 delete $info->{version};
490 $info->{path} = $worksphere.'/'.$packagemap{$p};
493 my $nailing = "$mf.nailing~";
494 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
495 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
496 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
497 close N or die "$self: close new $nailing: $!\n";
503 $ARGV[0] =~ m{\bcargo\b} &&
504 $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
505 $cargo_lock_update //= 1;
508 $cargo_lock_update //= 0;
510 $cargo_manifest_args //=
511 (defined $oot_dir) && !$cargo_lock_update;
513 if ($cargo_manifest_args) {
514 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
516 push @ARGV, qw(--target-dir=target) if $cargo_target_arg;
519 if (defined $target) {
520 if ($target =~ m{^[A-Z]}) {
521 $target = (cfgs 'arch', $target) // $archmap{$target}
522 // die "$self: --target=$target alias specified; not in cfg or map\n";
524 push @ARGV, "--target=$target";
529 our $build_absdir; # .../Build/<subdir>
531 sub oot_massage_cmdline () {
532 return unless defined $oot_dir;
534 my $use = cfgs qw(oot use);
535 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
536 $build_absdir = "$oot_absdir/$subdir";
540 if (!$cargo_lock_update) {
541 push @xargs, $build_absdir;
542 ($pre, $post) = ('cd "$1"; shift; ', '');
544 push @xargs, $oot_absdir, $subdir, $src_absdir;
547 mkdir -p -- "$1"; cd "$1"; shift;
548 cp -- "$1"/Cargo.toml
550 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
558 mkdir -p src; >src/lib.rs; >build.rs
561 rm -r src Cargo.toml build.rs;
564 my $addpath = (cfg_uc qw(oot path_add)) //
565 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
567 !Types::Serialiser::is_bool $addpath ? $addpath :
568 $addpath ? '$HOME/.cargo/bin' :
570 if (defined $addpath) {
572 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
576 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
577 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
579 my $getuser = sub { cfgsn qw(oot user) };
581 my $xe = $verbose >= 2 ? 'xe' : 'e';
584 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
586 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
588 push @command, @ARGV;
590 my $command_sh = sub {
591 my $quoted = join ' ', map {
596 @command = @_, "set -${xe}; $pre $quoted; $post";
598 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
600 if ($use eq 'really') {
601 my $user = $getuser->();
602 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
603 my $homedir = $pw[7];
604 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
605 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
606 } elsif ($use eq 'ssh') {
607 my $user = $getuser->();
608 $user .= '@localhost' unless $user =~ m/\@/;
609 $command_sh->('ssh',$user);
610 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
611 } elsif ($use eq 'command_args') {
612 my @c = cfgn_list qw(oot command);
614 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
615 } elsif ($use eq 'command_sh') {
616 my @c = cfgn_list qw(oot command);
618 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
619 } elsif ($use eq 'null') {
622 die "$self: oot.use mode $use not recognised\n";
629 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
630 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
631 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
632 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
633 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
639 if ($want_uninstall) {
641 foreach my $mf (keys %manifests) {
642 eval { uninstall1($mf,1); 1; } or warn "$@";
644 eval { unaltcargolock(1); 1; } or warn "$@";
648 our $cleanup_cargo_lock;
650 foreach my $mf (keys %manifests) {
651 link "$mf", "$mf.unnailed" or $!==EEXIST
652 or die "$self: make backup link $mf.unnailed: $!\n";
655 if (defined($alt_cargo_lock)) {
656 if (@alt_cargo_lock_stat) {
657 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
659 if (link $alt_cargo_lock, 'Cargo.lock') {
660 print STDERR " linked\n" if $verbose>=3;
661 } elsif ($! != EEXIST) {
662 print STDERR "\n" if $verbose>=3;
663 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
665 print STDERR "checking quality." if $verbose>=3;
666 my @lock_stat = stat 'Cargo.lock'
667 or die "$self: stat Cargo.lock (for alt check: $!\n";
668 same_file(\@alt_cargo_lock_stat, \@lock_stat)
670 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
672 $cleanup_cargo_lock = 1;
674 $cleanup_cargo_lock = 1;
675 # If Cargo.lock exists and alt doesn't, that means either
676 # that a previous run was interrupted, or that the user has
684 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
689 foreach my $mf (keys %manifests) {
690 my $nailing = "$mf.nailing~";
691 my $nailed = nailed($mf);
694 if (open NN, '<', $nailed) {
695 $diff = compare($nailing, \*NN);
696 die "$self: compare $nailing and $nailed: $!" if $diff<0;
698 $!==ENOENT or die "$self: check previous $nailed: $!\n";
708 rename $use, $mf or die "$self: install nailed $use: $!\n";
709 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
710 print STDERR "$self: nailed $mf\n" if $verbose>=3;
715 my $r = system @ARGV;
719 print STDERR "$self: could not execute $ARGV[0]: $!\n";
721 } elsif ($r & 0xff00) {
722 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
725 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
730 sub cargo_lock_update_after () {
731 if ($cargo_lock_update) {
732 # avoids importing File::Copy and the error handling is about as good
734 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
735 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
736 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
740 sub uninstall1 ($$) {
741 my ($mf, $enoentok) = @_;
742 my $unnailed = "$mf.unnailed";
743 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
744 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
747 sub unaltcargolock ($) {
749 return unless $cleanup_cargo_lock;
750 die 'internal error!' unless defined $alt_cargo_lock;
752 # we ignore $enoentok because we don't know if one was supposed to
755 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
756 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
758 unlink 'Cargo.lock' or $!==ENOENT or die
759 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
760 # ^ this also helps clean up the stupid rename() corner case
764 foreach my $mf (keys %manifests) {
765 my $nailed = nailed($mf);
766 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
772 while (@ARGV && $ARGV[0] =~ m/^-/) {
779 } elsif (s{^-q}{-}) {
781 } elsif (s{^-n}{-}) {
783 } elsif (s{^-D}{-}) {
785 } elsif (s{^-T(.+)}{-}s) {
787 } elsif (s{^-([uU])}{-}) {
788 $cargo_lock_update= $1=~m/[a-z]/;
789 } elsif (s{^-([mM])}{-}) {
790 $cargo_manifest_args= $1=~m/[a-z]/;
791 } elsif (s{^-([tT])}{-}) {
792 $cargo_target_arg= $1=~m/[a-z]/;
794 die "$self: unknown short option(s) $_\n";
797 } elsif (s{^--target=}{}) {
799 } elsif (m{^--(no-)?cargo-lock-update}) {
800 $cargo_lock_update= !!$1;
801 } elsif (m{^--(no-)?cargo-manifest-args}) {
802 $cargo_manifest_args= !!$1;
803 } elsif (m{^--(no-)?cargo-target-arg}) {
804 $cargo_target_arg= !!$1;
806 die "$self: unknown long option $_\n";
810 die "$self: need command to run\n" unless @ARGV || $noact;
814 consider_alt_cargo_lock();
819 our @display_cmd = @ARGV;
820 oot_massage_cmdline();
826 print STDERR Dumper(\%manifests) if $dump>=2;
827 print STDERR Dumper(\%packagemap, \@ARGV,
828 { src_absdir => $src_absdir,
829 worksphere => $worksphere,
832 oot_absdir => $oot_absdir,
833 build_absdir => $build_absdir });
843 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
844 (scalar keys %manifests), (scalar keys %packagemap),
845 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
848 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
849 my $estatus = invoke();
851 cargo_lock_update_after();
856 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;