2 # nailing-cargo: wrapper to use unpublished local crates
3 # SPDX-License-Identifier: AGPL-3.0-or-later
12 RPI => 'arm-unknown-linux-gnueabihf',
16 $self = $0; $self =~ s{^.*/(?=.)}{};
18 while ($deref =~ m{^/}) {
19 my $link = readlink $deref;
22 or die "$self: checking our script location $deref: $!\n";
23 $deref =~ s{/[^/]+$}{}
24 or die "$self: unexpected script path: $deref\n";
25 unshift @INC, $deref."/TOML-Tiny/lib";
28 last if $link !~ m{^/};
33 use Fcntl qw(LOCK_EX);
35 use TOML::Tiny::Faithful;
37 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
39 our $worksphere = $src_absdir;
40 $worksphere =~ s{/([^/]+)$}{}
41 or die "$self: cwd \`$worksphere' unsupported!\n";
42 our $subdir = $1; # leafname
44 our $lockfile = "../.nailing-cargo.lock";
48 our $command_is_cargo;
50 our $cargo_lock_update;
56 # build (default) =>[qw( )],
57 'generate-lockfile'=>[qw( lock-update !target !target-dir )],
58 update =>[qw( lock-update !target online )],
59 fetch =>[qw( online !target-dir )],
62 our @subcmd_xprops = qw(!manifest-path !offline !locked);
69 sub read_or_enoent ($) {
71 if (!open R, '<', $fn) {
72 return undef if $!==ENOENT;
73 die "$self: open $fn: $!\n";
76 my ($r) = <R> // die "$self: read $fn: $!\n";
80 sub stat_exists ($$) {
82 if (stat $fn) { return 1; }
83 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
88 print STDERR " subcmd_p ".(join ' ', keys %$cargo_subcmd)." | @_\n"
90 $cargo_subcmd->{$_[0]}
93 sub toml_or_enoent ($$) {
95 my $toml = read_or_enoent($f) // return;
96 print STDERR "Read TOML from $f\n" if $dump;
97 my ($v,$e) = from_toml($toml);
100 die "$self: parse TOML: $what: $f: $e\n";
102 die "$e ?" if length $e;
106 sub load1config ($) {
108 my $toml = toml_or_enoent($f, "config file");
109 push @configs, $toml if defined $toml;
113 my $dotfile = ".nailing-cargo.toml";
114 load1config("../Nailing-Cargo.toml");
115 load1config($dotfile);
116 load1config("$ENV{HOME}/$dotfile") if defined $ENV{HOME};
117 load1config("/etc/nailing-cargo/cfg.toml");
120 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
124 "@$x[0..5]" eq "@$y[0..5]";
129 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
130 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
131 my @fstat = stat LOCK or die "$self: fstat: $!\n";
132 my @stat = stat $lockfile;
134 next if $! == ENOENT;
135 die "$self: stat $lockfile: $!\n";
137 last if same_file(\@fstat,\@stat);
141 unlink $lockfile or die "$self: removing lockfile: $!\n";
149 die "$self: config key \`@_': $m\n";
153 foreach my $cfg (@configs) {
156 last unless defined $v;
157 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
160 return $v if defined $v;
168 my $got = ref($v) || 'scalar';
169 return $v if !defined($v) || $got eq $exp;
170 badcfg @_, "found \L$got\E, expected \L$exp\E";
171 # ^ toml doesn't make refs to scalars, so this is unambiguous
176 (cfge $exp, @_) // badcfg @_, "missing";
179 sub cfgs { cfge 'scalar', @_ }
180 sub cfgsn { cfgn 'scalar', @_ }
184 return $v if !defined($v) || Types::Serialiser::is_bool $v;
185 badcfg @_, "expected boolean";
189 my $l = cfge 'ARRAY', @_;
190 foreach my $x (@$l) {
191 !ref $x or badcfg @_, "list contains non-scalar element";
197 my $nailfile = "../Cargo.nail";
198 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
200 my $toml = <N> // die "$self: read $nailfile: $!";
202 if ($toml !~ m{^\s*\[/}m &&
203 $toml !~ m{^[^\n\#]*\=}m &&
204 # old non-toml syntax
205 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
206 $toml =~ s{^}{[packages\]\n};
208 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
211 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
215 ($nail,$e) = from_toml($toml);
216 if (!defined $nail) {
219 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
222 die "$self: parse $nailfile: $e\n";
224 die "$e ?" if length $e;
226 $nail->{subdirs} //= [ ];
228 if (!ref $nail->{subdirs}) {
231 map { s/^\s+//; s/\s+$//; $_; }
237 unshift @configs, $nail;
240 our @alt_cargo_lock_stat;
242 sub consider_alt_cargo_lock () {
243 my @ck = qw(alt_cargo_lock);
244 # User should *either* have Cargo.lock in .gitignore,
245 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
247 $alt_cargo_lock = (cfg_uc @ck);
250 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
251 $force = cfg_bool qw(alt_cargo_lock force);
252 my @ck = qw(alt_cargo_lock file);
253 $alt_cargo_lock = cfg_uc @ck;
255 $alt_cargo_lock //= Types::Serialiser::true;
257 if (Types::Serialiser::is_bool $alt_cargo_lock) {
258 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
259 $alt_cargo_lock = 'Cargo.lock.example';
262 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
263 badcfg @ck, "expected boolean, or leafname";
266 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
267 $alt_cargo_lock = undef unless $force;
271 @alt_cargo_lock_stat = stat _;
274 our $oot_dir; # oot.dir or "Build"
276 sub consider_oot () {
277 $oot_dir = cfgs qw(oot dir);
278 my $use = cfgs qw(oot use);
279 unless (defined($oot_dir) || defined($use) ||
280 defined(cfg_uc qw(oot user))) {
283 if (($use//'') eq 'disable') {
287 $oot_dir //= 'Build';
293 sub read_manifest ($$) {
294 my ($subdir, $why) = @_;
295 my $manifest = "../$subdir/Cargo.toml";
296 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
297 if (defined $manifests{$manifest}) {
299 "$self: warning: $subdir: specified more than once!\n";
302 foreach my $try ("$manifest.unnailed", "$manifest") {
303 my $toml = toml_or_enoent($try, "package manifest") // next;
304 my $p = $toml->{package}{name};
307 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
310 $manifests{$manifest} = $toml;
317 foreach my $p (keys %{ $nail->{packages} }) {
318 my $v = $nail->{packages}{$p};
319 my $subdir = ref($v) ? $v->{subdir} : $v;
320 my $gotpackage = read_manifest($subdir, "from [packages]") // '<nothing!>';
321 if ($gotpackage ne $p) {
323 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
325 die if defined $packagemap{$p};
326 $packagemap{$p} = $subdir;
328 foreach my $subdir (@{ $nail->{subdirs} }) {
329 my $gotpackage = read_manifest($subdir, "from [subdirs]");
330 if (!defined $gotpackage) {
332 "$self: warning: ignoring subdir $subdir which has no (suitable) Cargo.toml\n";
335 $packagemap{$gotpackage} //= $subdir;
340 foreach my $p (sort keys %packagemap) {
341 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
343 foreach my $mf (keys %manifests) {
344 my $toml = $manifests{$mf};
345 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
346 my $deps = $toml->{$k};
348 foreach my $p (keys %packagemap) {
349 my $info = $deps->{$p};
350 next unless defined $info;
351 $deps->{$p} = $info = { } unless ref $info;
352 delete $info->{version};
353 $info->{path} = $worksphere.'/'.$packagemap{$p};
356 my $nailing = "$mf.nailing~";
357 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
358 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
359 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
360 close N or die "$self: close new $nailing: $!\n";
365 if (!defined $online) {
366 $_ = cfg_uc qw(misc online);
368 } elsif (Types::Serialiser::is_bool $_) {
373 } elsif (m/^[1ty]/) { # allow booleanish strings
374 $online = 1; # for less user frustration
375 } elsif (m/^[0fn]/) {
378 badcfg qw(misc online), "expected boolean or 'auto', found '$_'";
381 $online //= 1 if subcmd_p('online');
384 $cargo_lock_update //= subcmd_p('lock-update');
388 if (!$cargo_lock_update) {
389 push @add, qw(--locked) unless subcmd_p('!locked');
390 if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
391 my $cargotoml = "${src_absdir}/Cargo.toml";
392 push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
393 push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
397 if (defined($target) && !subcmd_p('!target')) {
398 if ($target =~ m{^[A-Z]}) {
399 $target = (cfgs 'arch', $target) // $archmap{$target}
400 // die "$self: --target=$target alias specified; not in cfg or map\n";
402 push @add, "--target=$target";
405 push @add, "--offline" unless $online || subcmd_p('!offline');
407 push @args_preface, @add if $pass_options;
408 die if grep { m/ / } @add;
409 $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";
411 unshift @ARGV, @args_preface;
415 our $build_absdir; # .../Build/<subdir>
417 sub oot_massage_cmdline () {
418 return unless defined $oot_dir;
420 my $use = cfgs qw(oot use);
421 $use // die "$self: out-of-tree build, but \`oot.use' not configured\n";
422 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
423 $build_absdir = "$oot_absdir/$subdir";
427 if (!$cargo_lock_update) {
428 push @xargs, $build_absdir;
429 ($pre, $post) = ('cd "$1"; shift; ', '');
431 push @xargs, $oot_absdir, $subdir, $src_absdir;
434 mkdir -p -- "$1"; cd "$1"; shift;
435 cp -- "$1"/Cargo.toml
437 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
445 mkdir -p src; >src/lib.rs; >build.rs
448 rm -r src Cargo.toml build.rs;
451 my $addpath = (cfg_uc qw(oot path_add)) //
452 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
454 !Types::Serialiser::is_bool $addpath ? $addpath :
455 $addpath ? '$HOME/.cargo/bin' :
457 if (defined $addpath) {
459 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
463 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
464 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
466 my $getuser = sub { cfgsn qw(oot user) };
468 my $xe = $verbose >= 2 ? 'xe' : 'e';
471 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
473 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
475 push @command, @ARGV;
477 my $command_sh = sub {
478 my $quoted = join ' ', map {
483 @command = @_, "set -${xe}; $pre $quoted; $post";
485 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
487 if ($use eq 'really') {
488 my $user = $getuser->();
489 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
490 my $homedir = $pw[7];
491 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
492 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
493 } elsif ($use eq 'ssh') {
494 my $user = $getuser->();
495 $user .= '@localhost' unless $user =~ m/\@/;
496 $command_sh->('ssh',$user);
497 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
498 } elsif ($use eq 'command_args') {
499 my @c = cfgn_list qw(oot command);
501 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
502 } elsif ($use eq 'command_sh') {
503 my @c = cfgn_list qw(oot command);
505 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
506 } elsif ($use eq 'null') {
509 die "$self: oot.use mode $use not recognised\n";
516 $ENV{CARGO_MANIFEST_DIR} = $src_absdir;
517 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
518 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
519 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
520 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
521 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
527 if ($want_uninstall) {
529 foreach my $mf (keys %manifests) {
530 eval { uninstall1($mf,1); 1; } or warn "$@";
532 eval { unaltcargolock(1); 1; } or warn "$@";
536 sub consider_directories () {
537 return unless defined $oot_dir;
538 my $bsubdir = "../$oot_dir/$subdir";
539 return if stat $bsubdir;
540 die "$0: build directory $bsubdir inaccessible\n"
542 return if $cargo_lock_update; # will make it
543 die "$0: build directory $bsubdir does not exist, and not in Cargo.lock update mode!\n";
546 our $cleanup_cargo_lock;
548 foreach my $mf (keys %manifests) {
549 link "$mf", "$mf.unnailed" or $!==EEXIST
550 or die "$self: make backup link $mf.unnailed: $!\n";
553 if (defined($alt_cargo_lock)) {
554 if (@alt_cargo_lock_stat) {
555 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
557 if (link $alt_cargo_lock, 'Cargo.lock') {
558 print STDERR " linked\n" if $verbose>=3;
559 } elsif ($! != EEXIST) {
560 print STDERR "\n" if $verbose>=3;
561 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
563 print STDERR "checking quality." if $verbose>=3;
564 my @lock_stat = stat 'Cargo.lock'
565 or die "$self: stat Cargo.lock (for alt check: $!\n";
566 same_file(\@alt_cargo_lock_stat, \@lock_stat)
568 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
570 $cleanup_cargo_lock = 1;
572 $cleanup_cargo_lock = 1;
573 # If Cargo.lock exists and alt doesn't, that means either
574 # that a previous run was interrupted, or that the user has
582 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
587 my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
589 foreach my $mf (keys %manifests) {
590 if (@our_unfound_stab) {
591 if (stat_exists $mf, "manifest in to-be-nailed directory") {
592 my @mf_stab = stat _ ;
593 if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
594 @our_unfound_stab = ();
599 my $nailing = "$mf.nailing~";
600 my $nailed = nailed($mf);
603 if (open NN, '<', $nailed) {
604 $diff = compare($nailing, \*NN);
605 die "$self: compare $nailing and $nailed: $!" if $diff<0;
607 $!==ENOENT or die "$self: check previous $nailed: $!\n";
617 rename $use, $mf or die "$self: install nailed $use: $!\n";
618 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
619 print STDERR "$self: nailed $mf\n" if $verbose>=3;
622 if (@our_unfound_stab) {
624 "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
629 my $r = system @ARGV;
633 print STDERR "$self: could not execute $ARGV[0]: $!\n";
635 } elsif ($r & 0xff00) {
636 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
639 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
644 sub cargo_lock_update_after () {
645 if ($cargo_lock_update) {
646 # avoids importing File::Copy and the error handling is about as good
648 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
649 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
650 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
654 sub uninstall1 ($$) {
655 my ($mf, $enoentok) = @_;
656 my $unnailed = "$mf.unnailed";
657 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
658 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
661 sub unaltcargolock ($) {
663 return unless $cleanup_cargo_lock;
664 die 'internal error!' unless defined $alt_cargo_lock;
666 # we ignore $enoentok because we don't know if one was supposed to
669 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
670 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
672 unlink 'Cargo.lock' or $!==ENOENT or die
673 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
674 # ^ this also helps clean up the stupid rename() corner case
678 foreach my $mf (keys %manifests) {
679 my $nailed = nailed($mf);
680 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
689 # Loop exit condition:
692 # $is_cargo==1 <cargo-command> <cargo-opts> [--] <subcmd>...
693 # $is_cargo==0 <build-command>...
696 @ARGV or die "$self: need cargo subcommand\n";
701 my $not_a_nailing_opt = sub { # usage 1
702 unshift @ARGV, $orgopt;
703 unshift @ARGV, 'cargo';
705 no warnings qw(exiting);
708 $not_a_nailing_opt->() unless m{^-};
709 $not_a_nailing_opt->() if $_ eq '--';
711 if ($_ eq '---') { # usage 2 or 3
712 die "$self: --- must be followed by build command\n" unless @ARGV;
713 if ($ARGV[0] eq '--') { # usage 3
716 } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
718 } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
729 } elsif (s{^-q}{-}) {
731 } elsif (s{^-n}{-}) {
733 } elsif (s{^-s(.+)}{-}s) {
735 } elsif (s{^-([uU])}{-}) {
736 $cargo_lock_update = $1=~m/[a-z]/;
737 } elsif (s{^-([cC])}{-}) {
738 $pass_options = $1=~m/[a-z]/;
739 } elsif (s{^-D}{-}) {
741 } elsif (s{^-T(.+)}{-}s) {
743 } elsif (s{^-([oO])}{-}) {
744 $online = $1=~m/[a-z]/;
746 die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
747 $not_a_nailing_opt->();
750 } elsif (s{^--target=}{}) {
752 } elsif (m{^--(on|off)line$}) {
753 $online = $1 eq 'on';
754 } elsif (s{^--subcommand-props=}{}) {
755 my @props = split /\,/, $_;
757 if (!%subcmd_prop_ok) {
758 foreach my $v (\@subcmd_xprops, values %subcmd_props) {
759 $subcmd_prop_ok{$_}=1 foreach @$v;
763 or die "$self: unknown subcommand property \`$_'\n"
765 $cargo_subcmd = \@props;
766 } elsif (m{^--(no-)?cargo-lock-update}) {
767 $cargo_lock_update= !!$1;
769 $not_a_nailing_opt->();
777 @args_preface = shift @ARGV;
778 while (defined($_ = shift @ARGV)) {
779 if (!m{^-}) { unshift @ARGV, $_; last; }
780 if ($_ eq '--') { last; }
781 push @args_preface, $_;
783 @ARGV || die "$self: need cargo subcommand\n";
784 $cargo_subcmd //= $ARGV[0];
787 $cargo_subcmd //= '';
790 push @args_preface, shift @ARGV;
792 if (!ref($cargo_subcmd)) {
793 print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
794 $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
797 print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
799 $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
800 $cargo_subcmd = \%cargo_subcmd;
807 consider_alt_cargo_lock();
812 consider_directories();
813 our @display_cmd = @ARGV;
814 oot_massage_cmdline();
820 print STDERR Dumper(\%manifests) if $dump>=2;
821 print STDERR Dumper(\%packagemap, \@ARGV,
822 { src_absdir => $src_absdir,
823 worksphere => $worksphere,
826 oot_absdir => $oot_absdir,
827 build_absdir => $build_absdir });
837 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
838 (scalar keys %manifests), (scalar keys %packagemap),
839 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
842 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
843 my $estatus = invoke();
845 cargo_lock_update_after();
850 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;