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>
73 # --locked --target-dir=target
77 # # Adds each <subdir> to the list of directories whose
78 # # Cargo.toml is to be nailed, and also arranges to use
79 # # the package found there for other directories if
80 # # no other source of that package is evident in Cargo.nail.
91 # # Adds <subdir> to the list of directories whose Cargo.toml
92 # # is to be nailed, and overrides any other nailing for <package>
94 # <package> = <subdir>
95 # <package> = { <subdir> = ... }
97 # To control use of alternative Cargo.lock filename:
100 # file = true # equivalent to "Cargo.lock.example"
101 # file = false # disables this feature
102 # file = "<some leafname>"
104 # force = false # default, uses alt file only if it already exists
105 # force = true # always uses alt file; creation would make Cargo.lock
107 # (you can also specify just alt_cargo_lock instead of alt_cargo_lock.file)
109 # To enable out of tree builds:
111 # dir = "<build-directory>" # default is Build, if use is specified
114 # user = "<someuser>"
117 # user = "<user>@host" # NB must still share a filesystem!
119 # use = "command_args"
120 # command = ["<command>", "<which works like>", "nice"]
123 # command = ["<command>", "<which work like>", "sh -c"]
129 # Always dirties everyone's Cargo.toml, but tries to put them
130 # back (if not, running it again should fix it). Cannnot be
131 # fixed without changes to cargo.
133 # Out of tree builds require a unified filesystem view: eg,
134 # different users on the same host, NFS, or something. This
137 # Alternative Cargo.lock file must currently be a leafname.
138 # I think this just involves review to check other values work.
140 # Alternative Cargo.lock file must be on smae filesystem.
141 # This is not so easy; we would want the existing algorithm but
142 # a fallback for this case.
144 # Cargo.nail unconditionally looked for in ..
145 # Ideally should be configurable, and also perhaps be able
146 # to combine multiple Cargo.nail files ?
148 # Env vars we pass to the command:
149 # NAILINGCARGO_WORKSPHERE absolute path of invocation ..
150 # NAILINGCARGO_MANIFEST_DIR absolute path of invocation .
151 # NAILINGCARGO_BUILDSPHERE only if out of tree: abs parent of build dir
152 # NAILINGCARGO_BUILD_DIR absolute path of build dir (even if = src)
159 use Types::Serialiser;
162 RPI => 'arm-unknown-linux-gnueabihf',
166 $self = $0; $self =~ s{^.*/(?=.)}{};
168 while ($deref =~ m{^/}) {
169 my $link = readlink $deref;
170 if (!defined $link) {
172 or die "$self: checking our script location $deref: $!\n";
173 $deref =~ s{/[^/]+$}{}
174 or die "$self: unexpected script path: $deref\n";
175 unshift @INC, $deref."/TOML-Tiny/lib";
178 last if $link !~ m{^/};
183 use Fcntl qw(LOCK_EX);
185 use TOML::Tiny::Faithful;
187 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
189 our $worksphere = $src_absdir;
190 $worksphere =~ s{/([^/]+)$}{}
191 or die "$self: cwd \`$worksphere' unsupported!\n";
192 our $subdir = $1; # leafname
194 our $lockfile = "../.nailing-cargo.lock";
196 our $cargo_lock_update;
197 our $cargo_manifest_args;
205 sub read_or_enoent ($) {
207 if (!open R, '<', $fn) {
208 return undef if $!==ENOENT;
209 die "$self: open $fn: $!\n";
212 my ($r) = <R> // die "$self: read $fn: $!\n";
216 sub stat_exists ($$) {
217 my ($fn, $what) = @_;
218 if (stat $fn) { return 1; }
219 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
223 sub toml_or_enoent ($$) {
225 my $toml = read_or_enoent($f) // return;
226 my ($v,$e) = from_toml($toml);
229 die "$self: parse TOML: $what: $f: $e\n";
231 die "$e ?" if length $e;
235 sub load1config ($) {
237 my $toml = toml_or_enoent($f, "config file");
238 push @configs, $toml if defined $toml;
242 my $cfgleaf = ".nailing-cargo-cfg.toml";
243 load1config("/etc/nailing-cargo/cfg.toml");
244 load1config("$worksphere/$cfgleaf");
245 load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
250 foreach my $cfg (@configs) {
252 return $v if defined $v;
257 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
261 "@$x[0..5]" eq "@$y[0..5]";
266 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
267 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
268 my @fstat = stat LOCK or die "$self: fstat: $!\n";
269 my @stat = stat $lockfile;
271 next if $! == ENOENT;
272 die "$self: stat $lockfile: $!\n";
274 last if same_file(\@fstat,\@stat);
278 unlink $lockfile or die "$self: removing lockfile: $!\n";
286 die "$self: config key \`@_': $m\n";
292 last unless defined $v;
293 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
302 my $got = ref($v) || 'scalar';
303 return $v if !defined($v) || $got eq $exp;
304 badcfg @_, "found \L$got\E, expected \L$exp\E";
305 # ^ toml doesn't make refs to scalars, so this is unambiguous
310 (cfge $exp, @_) // badcfg @_, "missing";
313 sub cfgs { cfge 'scalar', @_ }
314 sub cfgsn { cfgn 'scalar', @_ }
318 return $v if !defined($v) || Types::Serialiser::is_bool $v;
319 badcfg @_, "expected boolean";
323 my $l = cfge 'ARRAY', @_;
324 foreach my $x (@$l) {
325 !ref $x or badcfg @_, "list contains non-scalar element";
331 my $nailfile = "../Cargo.nail";
332 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
334 my $toml = <N> // die "$self: read $nailfile: $!";
336 if ($toml !~ m{^\s*\[/}m &&
337 $toml !~ m{^[^\n\#]*\=}m &&
338 # old non-toml syntax
339 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
340 $toml =~ s{^}{[packages\]\n};
342 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
345 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
349 ($nail,$e) = from_toml($toml);
350 if (!defined $nail) {
353 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
356 die "$self: parse $nailfile: $e\n";
358 die "$e ?" if length $e;
360 $nail->{subdirs} //= [ ];
362 if (!ref $nail->{subdirs}) {
365 map { s/^\s+//; s/\s+$//; $_; }
372 our @alt_cargo_lock_stat;
374 sub consider_alt_cargo_lock () {
375 my @ck = qw(alt_cargo_lock);
376 # User should *either* have Cargo.lock in .gitignore,
377 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
379 $alt_cargo_lock = (cfg_uc @ck);
382 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
383 $force = cfg_bool qw(alt_cargo_lock force);
384 my @ck = qw(alt_cargo_lock file);
385 $alt_cargo_lock = cfg_uc @ck;
387 $alt_cargo_lock //= Types::Serialiser::true;
389 if (Types::Serialiser::is_bool $alt_cargo_lock) {
390 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
391 $alt_cargo_lock = 'Cargo.lock.example';
394 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
395 badcfg @ck, "expected boolean, or leafname";
398 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
399 $alt_cargo_lock = undef unless $force;
403 @alt_cargo_lock_stat = stat _;
406 our $oot_dir; # oot.dir or "Build"
408 sub consider_oot () {
409 $oot_dir = cfgs qw(oot dir);
410 my $use = cfgs qw(oot use);
411 unless (defined($oot_dir) || defined($use)) {
412 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
413 if $cargo_lock_update;
414 $cargo_lock_update=0;
417 $oot_dir //= 'Build';
423 sub read_manifest ($) {
425 my $manifest = "../$subdir/Cargo.toml";
426 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
427 if (defined $manifests{$manifest}) {
429 "$self: warning: $subdir: specified more than once!\n";
432 foreach my $try ("$manifest.unnailed", "$manifest") {
433 my $toml = toml_or_enoent($try, "package manifest") // next;
434 my $p = $toml->{package}{name};
437 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
440 $manifests{$manifest} = $toml;
447 foreach my $p (keys %{ $nail->{packages} }) {
448 my $v = $nail->{packages}{$p};
449 my $subdir = ref($v) ? $v->{subdir} : $v;
450 my $gotpackage = read_manifest($subdir) // '<nothing!>';
451 if ($gotpackage ne $p) {
453 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
455 die if defined $packagemap{$p};
456 $packagemap{$p} = $subdir;
458 foreach my $subdir (@{ $nail->{subdirs} }) {
459 my $gotpackage = read_manifest($subdir);
460 if (!defined $gotpackage) {
462 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
465 $packagemap{$gotpackage} //= $subdir;
470 foreach my $p (sort keys %packagemap) {
471 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
473 foreach my $mf (keys %manifests) {
474 my $toml = $manifests{$mf};
475 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
476 my $deps = $toml->{$k};
478 foreach my $p (keys %packagemap) {
479 my $info = $deps->{$p};
480 next unless defined $info;
481 $deps->{$p} = $info = { } unless ref $info;
482 delete $info->{version};
483 $info->{path} = $worksphere.'/'.$packagemap{$p};
486 my $nailing = "$mf.nailing~";
487 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
488 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
489 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
490 close N or die "$self: close new $nailing: $!\n";
496 $ARGV[0] =~ m{\bcargo\b} &&
497 $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
498 $cargo_lock_update //= 1;
501 $cargo_lock_update //= 0;
503 $cargo_manifest_args //=
504 (defined $oot_dir) && !$cargo_lock_update;
506 if ($cargo_manifest_args) {
507 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
508 qw(--locked --target-dir=target);
511 if (defined $target) {
512 if ($target =~ m{^[A-Z]}) {
513 $target = (cfgs 'arch', $target) // $archmap{$target}
514 // die "$self: --target=$target alias specified; not in cfg or map\n";
516 push @ARGV, "--target=$target";
521 our $build_absdir; # .../Build/<subdir>
523 sub oot_massage_cmdline () {
524 return unless defined $oot_dir;
526 my $use = cfgs qw(oot use);
527 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
528 $build_absdir = "$oot_absdir/$subdir";
532 if (!$cargo_lock_update) {
533 push @xargs, $build_absdir;
534 ($pre, $post) = ('cd "$1"; shift; ', '');
536 push @xargs, $oot_absdir, $subdir, $src_absdir;
539 mkdir -p -- "$1"; cd "$1"; shift;
540 cp -- "$1"/Cargo.toml
542 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
550 mkdir -p src; >src/lib.rs;
553 rm -r src Cargo.toml;
556 my $addpath = (cfg_uc qw(oot path_add)) //
557 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
559 !Types::Serialiser::is_bool $addpath ? $addpath :
560 $addpath ? '$HOME/.cargo/bin' :
562 if (defined $addpath) {
564 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
568 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
569 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
571 my $getuser = sub { cfgsn qw(oot user) };
573 my $xe = $verbose >= 2 ? 'xe' : 'e';
576 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
578 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
580 push @command, @ARGV;
582 my $command_sh = sub {
583 my $quoted = join ' ', map {
588 @command = @_, "set -${xe}; $pre $quoted; $post";
590 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
592 if ($use eq 'really') {
593 my $user = $getuser->();
594 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
595 my $homedir = $pw[7];
596 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
597 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
598 } elsif ($use eq 'ssh') {
599 my $user = $getuser->();
600 $user .= '@localhost' unless $user =~ m/\@/;
601 $command_sh->('ssh',$user);
602 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
603 } elsif ($use eq 'command_args') {
604 my @c = cfgn_list qw(oot command);
606 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
607 } elsif ($use eq 'command_sh') {
608 my @c = cfgn_list qw(oot command);
610 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
611 } elsif ($use eq 'null') {
614 die "$self: oot.use mode $use not recognised\n";
621 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
622 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
623 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
624 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
625 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
631 if ($want_uninstall) {
633 foreach my $mf (keys %manifests) {
634 eval { uninstall1($mf,1); 1; } or warn "$@";
636 eval { unaltcargolock(1); 1; } or warn "$@";
640 our $cleanup_cargo_lock;
642 foreach my $mf (keys %manifests) {
643 link "$mf", "$mf.unnailed" or $!==EEXIST
644 or die "$self: make backup link $mf.unnailed: $!\n";
647 if (defined($alt_cargo_lock)) {
648 if (@alt_cargo_lock_stat) {
649 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
651 if (link $alt_cargo_lock, 'Cargo.lock') {
652 print STDERR " linked\n" if $verbose>=3;
653 } elsif ($! != EEXIST) {
654 print STDERR "\n" if $verbose>=3;
655 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
657 print STDERR "checking quality." if $verbose>=3;
658 my @lock_stat = stat 'Cargo.lock'
659 or die "$self: stat Cargo.lock (for alt check: $!\n";
660 same_file(\@alt_cargo_lock_stat, \@lock_stat)
662 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
664 $cleanup_cargo_lock = 1;
666 $cleanup_cargo_lock = 1;
667 # If Cargo.lock exists and alt doesn't, that means either
668 # that a previous run was interrupted, or that the user has
676 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
681 foreach my $mf (keys %manifests) {
682 my $nailing = "$mf.nailing~";
683 my $nailed = nailed($mf);
686 if (open NN, '<', $nailed) {
687 $diff = compare($nailing, \*NN);
688 die "$self: compare $nailing and $nailed: $!" if $diff<0;
690 $!==ENOENT or die "$self: check previous $nailed: $!\n";
700 rename $use, $mf or die "$self: install nailed $use: $!\n";
701 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
702 print STDERR "$self: nailed $mf\n" if $verbose>=3;
707 my $r = system @ARGV;
711 print STDERR "$self: could not execute $ARGV[0]: $!\n";
713 } elsif ($r & 0xff00) {
714 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
717 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
722 sub cargo_lock_update_after () {
723 if ($cargo_lock_update) {
724 # avoids importing File::Copy and the error handling is about as good
726 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
727 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
728 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
732 sub uninstall1 ($$) {
733 my ($mf, $enoentok) = @_;
734 my $unnailed = "$mf.unnailed";
735 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
736 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
739 sub unaltcargolock ($) {
741 return unless $cleanup_cargo_lock;
742 die 'internal error!' unless defined $alt_cargo_lock;
744 # we ignore $enoentok because we don't know if one was supposed to
747 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
748 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
750 unlink 'Cargo.lock' or $!==ENOENT or die
751 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
752 # ^ this also helps clean up the stupid rename() corner case
756 foreach my $mf (keys %manifests) {
757 my $nailed = nailed($mf);
758 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
764 while (@ARGV && $ARGV[0] =~ m/^-/) {
771 } elsif (s{^-q}{-}) {
773 } elsif (s{^-n}{-}) {
775 } elsif (s{^-D}{-}) {
777 } elsif (s{^-T(.+)}{-}s) {
779 } elsif (s{^-([uU])}{-}) {
780 $cargo_lock_update= $1=~m/[a-z]/;
781 } elsif (s{^-([mM])}{-}) {
782 $cargo_manifest_args= $1=~m/[a-z]/;
784 die "$self: unknown short option(s) $_\n";
787 } elsif (s{^--target=}{}) {
789 } elsif (m{^--(no-)?cargo-lock-update}) {
790 $cargo_lock_update= !!$1;
791 } elsif (m{^--(no-)?cargo-manifest-args}) {
792 $cargo_manifest_args= !!$1;
794 die "$self: unknown long option $_\n";
798 die "$self: need command to run\n" unless @ARGV || $noact;
802 consider_alt_cargo_lock();
807 our @display_cmd = @ARGV;
808 oot_massage_cmdline();
814 print STDERR Dumper(\%manifests) if $dump>=2;
815 print STDERR Dumper(\%packagemap, \@ARGV,
816 { src_absdir => $src_absdir,
817 worksphere => $worksphere,
820 oot_absdir => $oot_absdir,
821 build_absdir => $build_absdir });
831 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
832 (scalar keys %manifests), (scalar keys %packagemap),
833 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
836 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
837 my $estatus = invoke();
839 cargo_lock_update_after();
844 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;