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 if (!ref $nail->{subdirs}) {
363 map { s/^\s+//; s/\s+$//; $_; }
370 our @alt_cargo_lock_stat;
372 sub consider_alt_cargo_lock () {
373 my @ck = qw(alt_cargo_lock);
374 # User should *either* have Cargo.lock in .gitignore,
375 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
377 $alt_cargo_lock = (cfg_uc @ck);
380 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
381 $force = cfg_bool qw(alt_cargo_lock force);
382 my @ck = qw(alt_cargo_lock file);
383 $alt_cargo_lock = cfg_uc @ck;
385 $alt_cargo_lock //= Types::Serialiser::true;
387 if (Types::Serialiser::is_bool $alt_cargo_lock) {
388 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
389 $alt_cargo_lock = 'Cargo.lock.example';
392 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
393 badcfg @ck, "expected boolean, or leafname";
396 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
397 $alt_cargo_lock = undef unless $force;
401 @alt_cargo_lock_stat = stat _;
404 our $oot_dir; # oot.dir or "Build"
406 sub consider_oot () {
407 $oot_dir = cfgs qw(oot dir);
408 my $use = cfgs qw(oot use);
409 unless (defined($oot_dir) || defined($use)) {
410 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
411 if $cargo_lock_update;
412 $cargo_lock_update=0;
415 $oot_dir //= 'Build';
421 sub read_manifest ($) {
423 my $manifest = "../$subdir/Cargo.toml";
424 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
425 if (defined $manifests{$manifest}) {
427 "$self: warning: $subdir: specified more than once!\n";
430 foreach my $try ("$manifest.unnailed", "$manifest") {
431 my $toml = toml_or_enoent($try, "package manifest") // next;
432 my $p = $toml->{package}{name};
435 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
438 $manifests{$manifest} = $toml;
445 foreach my $p (keys %{ $nail->{packages} }) {
446 my $v = $nail->{packages}{$p};
447 my $subdir = ref($v) ? $v->{subdir} : $v;
448 my $gotpackage = read_manifest($subdir) // '<nothing!>';
449 if ($gotpackage ne $p) {
451 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
453 die if defined $packagemap{$p};
454 $packagemap{$p} = $subdir;
456 foreach my $subdir (@{ $nail->{subdirs} }) {
457 my $gotpackage = read_manifest($subdir);
458 if (!defined $gotpackage) {
460 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
463 $packagemap{$gotpackage} //= $subdir;
468 foreach my $p (sort keys %packagemap) {
469 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
471 foreach my $mf (keys %manifests) {
472 my $toml = $manifests{$mf};
473 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
474 my $deps = $toml->{$k};
476 foreach my $p (keys %packagemap) {
477 my $info = $deps->{$p};
478 next unless defined $info;
479 $deps->{$p} = $info = { } unless ref $info;
480 delete $info->{version};
481 $info->{path} = $worksphere.'/'.$packagemap{$p};
484 my $nailing = "$mf.nailing~";
485 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
486 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
487 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
488 close N or die "$self: close new $nailing: $!\n";
494 $ARGV[0] =~ m{\bcargo\b} &&
495 $ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
496 $cargo_lock_update //= 1;
499 $cargo_lock_update //= 0;
501 $cargo_manifest_args //=
502 (defined $oot_dir) && !$cargo_lock_update;
504 if ($cargo_manifest_args) {
505 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
506 qw(--locked --target-dir=target);
509 if (defined $target) {
510 if ($target =~ m{^[A-Z]}) {
511 $target = (cfgs 'arch', $target) // $archmap{$target}
512 // die "$self: --target=$target alias specified; not in cfg or map\n";
514 push @ARGV, "--target=$target";
519 our $build_absdir; # .../Build/<subdir>
521 sub oot_massage_cmdline () {
522 return unless defined $oot_dir;
524 my $use = cfgs qw(oot use);
525 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
526 $build_absdir = "$oot_absdir/$subdir";
530 if (!$cargo_lock_update) {
531 push @xargs, $build_absdir;
532 ($pre, $post) = ('cd "$1"; shift; ', '');
534 push @xargs, $oot_absdir, $subdir, $src_absdir;
537 mkdir -p -- "$1"; cd "$1"; shift;
538 cp -- "$1"/Cargo.toml
540 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
548 mkdir -p src; >src/lib.rs;
551 rm -r src Cargo.toml;
554 my $addpath = (cfg_uc qw(oot path_add)) //
555 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
557 !Types::Serialiser::is_bool $addpath ? $addpath :
558 $addpath ? '$HOME/.cargo/bin' :
560 if (defined $addpath) {
562 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
566 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
567 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
569 my $getuser = sub { cfgsn qw(oot user) };
571 my $xe = $verbose >= 2 ? 'xe' : 'e';
574 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
576 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
578 push @command, @ARGV;
580 my $command_sh = sub {
581 my $quoted = join ' ', map {
586 @command = @_, "set -${xe}; $pre $quoted; $post";
588 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
590 if ($use eq 'really') {
591 my $user = $getuser->();
592 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
593 my $homedir = $pw[7];
594 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
595 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
596 } elsif ($use eq 'ssh') {
597 my $user = $getuser->();
598 $user .= '@localhost' unless $user =~ m/\@/;
599 $command_sh->('ssh',$user);
600 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
601 } elsif ($use eq 'command_args') {
602 my @c = cfgn_list qw(oot command);
604 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
605 } elsif ($use eq 'command_sh') {
606 my @c = cfgn_list qw(oot command);
608 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
609 } elsif ($use eq 'null') {
612 die "$self: oot.use mode $use not recognised\n";
619 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
620 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
621 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
622 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
623 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
629 if ($want_uninstall) {
631 foreach my $mf (keys %manifests) {
632 eval { uninstall1($mf,1); 1; } or warn "$@";
634 eval { unaltcargolock(1); 1; } or warn "$@";
638 our $cleanup_cargo_lock;
640 foreach my $mf (keys %manifests) {
641 link "$mf", "$mf.unnailed" or $!==EEXIST
642 or die "$self: make backup link $mf.unnailed: $!\n";
645 if (defined($alt_cargo_lock)) {
646 if (@alt_cargo_lock_stat) {
647 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
649 if (link $alt_cargo_lock, 'Cargo.lock') {
650 print STDERR " linked\n" if $verbose>=3;
651 } elsif ($! != EEXIST) {
652 print STDERR "\n" if $verbose>=3;
653 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
655 print STDERR "checking quality." if $verbose>=3;
656 my @lock_stat = stat 'Cargo.lock'
657 or die "$self: stat Cargo.lock (for alt check: $!\n";
658 same_file(\@alt_cargo_lock_stat, \@lock_stat)
660 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
662 $cleanup_cargo_lock = 1;
664 $cleanup_cargo_lock = 1;
665 # If Cargo.lock exists and alt doesn't, that means either
666 # that a previous run was interrupted, or that the user has
674 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
679 foreach my $mf (keys %manifests) {
680 my $nailing = "$mf.nailing~";
681 my $nailed = nailed($mf);
684 if (open NN, '<', $nailed) {
685 $diff = compare($nailing, \*NN);
686 die "$self: compare $nailing and $nailed: $!" if $diff<0;
688 $!==ENOENT or die "$self: check previous $nailed: $!\n";
698 rename $use, $mf or die "$self: install nailed $use: $!\n";
699 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
700 print STDERR "$self: nailed $mf\n" if $verbose>=3;
705 my $r = system @ARGV;
709 print STDERR "$self: could not execute $ARGV[0]: $!\n";
711 } elsif ($r & 0xff00) {
712 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
715 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
720 sub cargo_lock_update_after () {
721 if ($cargo_lock_update) {
722 # avoids importing File::Copy and the error handling is about as good
724 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
725 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
726 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
730 sub uninstall1 ($$) {
731 my ($mf, $enoentok) = @_;
732 my $unnailed = "$mf.unnailed";
733 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
734 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
737 sub unaltcargolock ($) {
739 return unless $cleanup_cargo_lock;
740 die 'internal error!' unless defined $alt_cargo_lock;
742 # we ignore $enoentok because we don't know if one was supposed to
745 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
746 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
748 unlink 'Cargo.lock' or $!==ENOENT or die
749 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
750 # ^ this also helps clean up the stupid rename() corner case
754 foreach my $mf (keys %manifests) {
755 my $nailed = nailed($mf);
756 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
762 while (@ARGV && $ARGV[0] =~ m/^-/) {
769 } elsif (s{^-q}{-}) {
771 } elsif (s{^-n}{-}) {
773 } elsif (s{^-D}{-}) {
775 } elsif (s{^-T(.+)}{-}s) {
777 } elsif (s{^-([uU])}{-}) {
778 $cargo_lock_update= $1=~m/[a-z]/;
779 } elsif (s{^-([mM])}{-}) {
780 $cargo_manifest_args= $1=~m/[a-z]/;
782 die "$self: unknown short option(s) $_\n";
785 } elsif (s{^--target=}{}) {
787 } elsif (m{^--(no-)?cargo-lock-update}) {
788 $cargo_lock_update= !!$1;
789 } elsif (m{^--(no-)?cargo-manifest-args}) {
790 $cargo_manifest_args= !!$1;
792 die "$self: unknown long option $_\n";
796 die "$self: need command to run\n" unless @ARGV || $noact;
800 consider_alt_cargo_lock();
805 our @display_cmd = @ARGV;
806 oot_massage_cmdline();
812 print STDERR Dumper(\%manifests) if $dump>=2;
813 print STDERR Dumper(\%packagemap, \@ARGV,
814 { src_absdir => $src_absdir,
815 worksphere => $worksphere,
818 oot_absdir => $oot_absdir,
819 build_absdir => $build_absdir });
829 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
830 (scalar keys %manifests), (scalar keys %packagemap),
831 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
834 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
835 my $estatus = invoke();
837 cargo_lock_update_after();
842 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;