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";e
42 our $subdir = $1; # leafname
44 our $lockfile = "../.nailing-cargo.lock";
52 # build (default) =>qw( ),
53 update =>qw( !target lock-update ),
54 'generate-lockfile'=>qw( !target lock-update ),
55 fetch =>qw( !target online !target-dir ),
56 '' =>qw( !target !manifest-path !locked !offline );
64 sub read_or_enoent ($) {
66 if (!open R, '<', $fn) {
67 return undef if $!==ENOENT;
68 die "$self: open $fn: $!\n";
71 my ($r) = <R> // die "$self: read $fn: $!\n";
75 sub stat_exists ($$) {
77 if (stat $fn) { return 1; }
78 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
82 sub toml_or_enoent ($$) {
84 my $toml = read_or_enoent($f) // return;
85 print STDERR "Read TOML from $f\n" if $dump;
86 my ($v,$e) = from_toml($toml);
89 die "$self: parse TOML: $what: $f: $e\n";
91 die "$e ?" if length $e;
97 my $toml = toml_or_enoent($f, "config file");
98 push @configs, $toml if defined $toml;
102 my $dotfile = ".nailing-cargo.toml";
103 load1config("../Nailing-Cargo.toml");
104 load1config($dotfile);
105 load1config("$ENV{HOME}/$dotfile") if defined $ENV{HOME};
106 load1config("/etc/nailing-cargo/cfg.toml");
109 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
113 "@$x[0..5]" eq "@$y[0..5]";
118 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
119 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
120 my @fstat = stat LOCK or die "$self: fstat: $!\n";
121 my @stat = stat $lockfile;
123 next if $! == ENOENT;
124 die "$self: stat $lockfile: $!\n";
126 last if same_file(\@fstat,\@stat);
130 unlink $lockfile or die "$self: removing lockfile: $!\n";
138 die "$self: config key \`@_': $m\n";
142 foreach my $cfg (@configs) {
145 last unless defined $v;
146 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
149 return $v if defined $v;
157 my $got = ref($v) || 'scalar';
158 return $v if !defined($v) || $got eq $exp;
159 badcfg @_, "found \L$got\E, expected \L$exp\E";
160 # ^ toml doesn't make refs to scalars, so this is unambiguous
165 (cfge $exp, @_) // badcfg @_, "missing";
168 sub cfgs { cfge 'scalar', @_ }
169 sub cfgsn { cfgn 'scalar', @_ }
173 return $v if !defined($v) || Types::Serialiser::is_bool $v;
174 badcfg @_, "expected boolean";
178 my $l = cfge 'ARRAY', @_;
179 foreach my $x (@$l) {
180 !ref $x or badcfg @_, "list contains non-scalar element";
186 my $nailfile = "../Cargo.nail";
187 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
189 my $toml = <N> // die "$self: read $nailfile: $!";
191 if ($toml !~ m{^\s*\[/}m &&
192 $toml !~ m{^[^\n\#]*\=}m &&
193 # old non-toml syntax
194 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
195 $toml =~ s{^}{[packages\]\n};
197 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
200 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
204 ($nail,$e) = from_toml($toml);
205 if (!defined $nail) {
208 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
211 die "$self: parse $nailfile: $e\n";
213 die "$e ?" if length $e;
215 $nail->{subdirs} //= [ ];
217 if (!ref $nail->{subdirs}) {
220 map { s/^\s+//; s/\s+$//; $_; }
226 unshift @configs, $nail;
229 our @alt_cargo_lock_stat;
231 sub consider_alt_cargo_lock () {
232 my @ck = qw(alt_cargo_lock);
233 # User should *either* have Cargo.lock in .gitignore,
234 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
236 $alt_cargo_lock = (cfg_uc @ck);
239 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
240 $force = cfg_bool qw(alt_cargo_lock force);
241 my @ck = qw(alt_cargo_lock file);
242 $alt_cargo_lock = cfg_uc @ck;
244 $alt_cargo_lock //= Types::Serialiser::true;
246 if (Types::Serialiser::is_bool $alt_cargo_lock) {
247 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
248 $alt_cargo_lock = 'Cargo.lock.example';
251 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
252 badcfg @ck, "expected boolean, or leafname";
255 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
256 $alt_cargo_lock = undef unless $force;
260 @alt_cargo_lock_stat = stat _;
263 our $oot_dir; # oot.dir or "Build"
265 sub consider_oot () {
266 $oot_dir = cfgs qw(oot dir);
267 my $use = cfgs qw(oot use);
268 unless (defined($oot_dir) || defined($use)) {
269 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
270 if $cargo_lock_update;
271 $cargo_lock_update=0;
274 if ($use eq 'disable') {
278 $oot_dir //= 'Build';
284 sub read_manifest ($) {
286 my $manifest = "../$subdir/Cargo.toml";
287 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
288 if (defined $manifests{$manifest}) {
290 "$self: warning: $subdir: specified more than once!\n";
293 foreach my $try ("$manifest.unnailed", "$manifest") {
294 my $toml = toml_or_enoent($try, "package manifest") // next;
295 my $p = $toml->{package}{name};
298 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
301 $manifests{$manifest} = $toml;
308 foreach my $p (keys %{ $nail->{packages} }) {
309 my $v = $nail->{packages}{$p};
310 my $subdir = ref($v) ? $v->{subdir} : $v;
311 my $gotpackage = read_manifest($subdir) // '<nothing!>';
312 if ($gotpackage ne $p) {
314 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
316 die if defined $packagemap{$p};
317 $packagemap{$p} = $subdir;
319 foreach my $subdir (@{ $nail->{subdirs} }) {
320 my $gotpackage = read_manifest($subdir);
321 if (!defined $gotpackage) {
323 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
326 $packagemap{$gotpackage} //= $subdir;
331 foreach my $p (sort keys %packagemap) {
332 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
334 foreach my $mf (keys %manifests) {
335 my $toml = $manifests{$mf};
336 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
337 my $deps = $toml->{$k};
339 foreach my $p (keys %packagemap) {
340 my $info = $deps->{$p};
341 next unless defined $info;
342 $deps->{$p} = $info = { } unless ref $info;
343 delete $info->{version};
344 $info->{path} = $worksphere.'/'.$packagemap{$p};
347 my $nailing = "$mf.nailing~";
348 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
349 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
350 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
351 close N or die "$self: close new $nailing: $!\n";
356 $online = 1 if subcmd_p('online');
357 $online //= cfg_bool qw(misc online);
360 $cargo_lock_update //= subcmd_p('lock-update');
362 if (!$cargo_lock_update) {
363 push @ARGV, qw(--locked) unless subcmd_p('!locked');
364 if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
365 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml";
366 push @ARGV, qw(--target-dir=target) unless subcmd_p('!target');
370 if (defined($target) && !subcmd_p('!target')) {
371 if ($target =~ m{^[A-Z]}) {
372 $target = (cfgs 'arch', $target) // $archmap{$target}
373 // die "$self: --target=$target alias specified; not in cfg or map\n";
375 push @ARGV, "--target=$target";
378 push @ARGV, "--offline" unless $online || subcmd_p('!offline');
382 our $build_absdir; # .../Build/<subdir>
384 sub oot_massage_cmdline () {
385 return unless defined $oot_dir;
387 my $use = cfgs qw(oot use);
388 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
389 $build_absdir = "$oot_absdir/$subdir";
393 if (!$cargo_lock_update) {
394 push @xargs, $build_absdir;
395 ($pre, $post) = ('cd "$1"; shift; ', '');
397 push @xargs, $oot_absdir, $subdir, $src_absdir;
400 mkdir -p -- "$1"; cd "$1"; shift;
401 cp -- "$1"/Cargo.toml
403 $pre .= <<'ENDLK' if stat_exists 'Cargo.lock', 'working cargo lockfile';
411 mkdir -p src; >src/lib.rs; >build.rs
414 rm -r src Cargo.toml build.rs;
417 my $addpath = (cfg_uc qw(oot path_add)) //
418 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
420 !Types::Serialiser::is_bool $addpath ? $addpath :
421 $addpath ? '$HOME/.cargo/bin' :
423 if (defined $addpath) {
425 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
429 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
430 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
432 my $getuser = sub { cfgsn qw(oot user) };
434 my $xe = $verbose >= 2 ? 'xe' : 'e';
437 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
439 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
441 push @command, @ARGV;
443 my $command_sh = sub {
444 my $quoted = join ' ', map {
449 @command = @_, "set -${xe}; $pre $quoted; $post";
451 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
453 if ($use eq 'really') {
454 my $user = $getuser->();
455 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
456 my $homedir = $pw[7];
457 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
458 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
459 } elsif ($use eq 'ssh') {
460 my $user = $getuser->();
461 $user .= '@localhost' unless $user =~ m/\@/;
462 $command_sh->('ssh',$user);
463 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
464 } elsif ($use eq 'command_args') {
465 my @c = cfgn_list qw(oot command);
467 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
468 } elsif ($use eq 'command_sh') {
469 my @c = cfgn_list qw(oot command);
471 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
472 } elsif ($use eq 'null') {
475 die "$self: oot.use mode $use not recognised\n";
482 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
483 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
484 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
485 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
486 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
492 if ($want_uninstall) {
494 foreach my $mf (keys %manifests) {
495 eval { uninstall1($mf,1); 1; } or warn "$@";
497 eval { unaltcargolock(1); 1; } or warn "$@";
501 our $cleanup_cargo_lock;
503 foreach my $mf (keys %manifests) {
504 link "$mf", "$mf.unnailed" or $!==EEXIST
505 or die "$self: make backup link $mf.unnailed: $!\n";
508 if (defined($alt_cargo_lock)) {
509 if (@alt_cargo_lock_stat) {
510 print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
512 if (link $alt_cargo_lock, 'Cargo.lock') {
513 print STDERR " linked\n" if $verbose>=3;
514 } elsif ($! != EEXIST) {
515 print STDERR "\n" if $verbose>=3;
516 die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
518 print STDERR "checking quality." if $verbose>=3;
519 my @lock_stat = stat 'Cargo.lock'
520 or die "$self: stat Cargo.lock (for alt check: $!\n";
521 same_file(\@alt_cargo_lock_stat, \@lock_stat)
523 "$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
525 $cleanup_cargo_lock = 1;
527 $cleanup_cargo_lock = 1;
528 # If Cargo.lock exists and alt doesn't, that means either
529 # that a previous run was interrupted, or that the user has
537 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
542 my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
544 foreach my $mf (keys %manifests) {
545 if (@our_unfound_stab) {
546 if (stat_exists $mf, "manifest in to-be-nailed directory") {
547 my @mf_stab = stat _ ;
548 if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
549 @our_unfound_stab = ();
554 my $nailing = "$mf.nailing~";
555 my $nailed = nailed($mf);
558 if (open NN, '<', $nailed) {
559 $diff = compare($nailing, \*NN);
560 die "$self: compare $nailing and $nailed: $!" if $diff<0;
562 $!==ENOENT or die "$self: check previous $nailed: $!\n";
572 rename $use, $mf or die "$self: install nailed $use: $!\n";
573 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
574 print STDERR "$self: nailed $mf\n" if $verbose>=3;
577 if (@our_unfound_stab) {
579 "$self: *WARNING* cwd is not in Cargo.nail thbough it has Cargo.toml!\n";
584 my $r = system @ARGV;
588 print STDERR "$self: could not execute $ARGV[0]: $!\n";
590 } elsif ($r & 0xff00) {
591 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
594 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
599 sub cargo_lock_update_after () {
600 if ($cargo_lock_update) {
601 # avoids importing File::Copy and the error handling is about as good
603 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
604 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
605 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
609 sub uninstall1 ($$) {
610 my ($mf, $enoentok) = @_;
611 my $unnailed = "$mf.unnailed";
612 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
613 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
616 sub unaltcargolock ($) {
618 return unless $cleanup_cargo_lock;
619 die 'internal error!' unless defined $alt_cargo_lock;
621 # we ignore $enoentok because we don't know if one was supposed to
624 rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
625 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";
627 unlink 'Cargo.lock' or $!==ENOENT or die
628 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
629 # ^ this also helps clean up the stupid rename() corner case
633 foreach my $mf (keys %manifests) {
634 my $nailed = nailed($mf);
635 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
644 # Loop exit condition:
647 # $is_cargo==1 <cargo-command> <cargo-opts> [--] <subcmd>...
648 # $is_cargo==0 <build-command>...
651 @ARGV or die "$self: need cargo subcommand\n";
656 my $not_a_nailing_opt = sub { # usage 1
657 unshift @ARGV, $orgopt;
658 unshift @ARGV, 'cargo';
660 no warnings qw(exiting);
663 $not_a_nailing_opt->() unless m{^-};
664 $not_a_nailing_opt->() if $_ eq '--';
666 if ($_ eq '---') { # usage 2 or 3
667 die "$self: --- must be followed by build command\n" unless @ARGV;
668 if ($ARGV[0] eq '--') { # usage 3
671 } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
673 } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
684 } elsif (s{^-q}{-}) {
686 } elsif (s{^-n}{-}) {
688 } elsif (s{^-c(.+)}{-}s) {
690 } elsif (s{^-C}{-}) {
692 } elsif (s{^-D}{-}) {
694 } elsif (s{^-T(.+)}{-}s) {
696 } elsif (s{^-([oO])}{-}) {
697 $online= $1=~m/[a-z]/;
699 die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
700 $not_a_nailing_opt->();
703 } elsif (s{^--target=}{}) {
705 } elsif (m{^--(on|off)line$}) {
706 $online = $1 eq 'on';
707 } elsif (s{^--subcommand-props=}{}) {
708 my @props = split /\,/, $_;
710 if (!%subcmd_prop_ok) {
711 for $v in (%subcmd_props) { $subcmd_prop_ok{$_}=1 foreach @$v; };
714 or die "$self: unknown subcommand property \`$_'\n"
716 $cargo_subcmd = \@props;
717 } elsif (m{^--(no-)?cargo-lock-update}) {
718 $cargo_lock_update= !!$1;
720 $not_a_nailing_opt->();
728 my @cargo_and_opts = shift @ARGV;
729 while (defined($_ = shift @ARGV)) {
730 if (!m{^-}) { unshift @ARGV, $_; last; }
731 if ($_ eq '--') { last; }
732 push @cargo_and_opts, $_;
734 @ARGV || die "$self: need cargo subcommand\n";
735 $cargo_subcmd //= $ARGV[0];
736 unshift @ARGV, @cargo_and_opts;
738 $cargo_subcmd //= '';
741 if (!ref($cargo_subcmd)) {
742 $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
750 consider_alt_cargo_lock();
755 our @display_cmd = @ARGV;
756 oot_massage_cmdline();
762 print STDERR Dumper(\%manifests) if $dump>=2;
763 print STDERR Dumper(\%packagemap, \@ARGV,
764 { src_absdir => $src_absdir,
765 worksphere => $worksphere,
768 oot_absdir => $oot_absdir,
769 build_absdir => $build_absdir });
779 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
780 (scalar keys %manifests), (scalar keys %packagemap),
781 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
784 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
785 my $estatus = invoke();
787 cargo_lock_update_after();
792 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;