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";
46 our $cargo_lock_update;
47 our $cargo_manifest_args;
48 our $cargo_target_arg=1;
57 sub read_or_enoent ($) {
59 if (!open R, '<', $fn) {
60 return undef if $!==ENOENT;
61 die "$self: open $fn: $!\n";
64 my ($r) = <R> // die "$self: read $fn: $!\n";
68 sub stat_exists ($$) {
70 if (stat $fn) { return 1; }
71 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
75 sub toml_or_enoent ($$) {
77 my $toml = read_or_enoent($f) // return;
78 print STDERR "Read TOML from $f\n" if $dump;
79 my ($v,$e) = from_toml($toml);
82 die "$self: parse TOML: $what: $f: $e\n";
84 die "$e ?" if length $e;
90 my $toml = toml_or_enoent($f, "config file");
91 push @configs, $toml if defined $toml;
95 my $dotfile = ".nailing-cargo.toml";
96 load1config("../Nailing-Cargo.toml");
97 load1config($dotfile);
98 load1config("$ENV{HOME}/$dotfile") if defined $ENV{HOME};
99 load1config("/etc/nailing-cargo/cfg.toml");
102 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
106 "@$x[0..5]" eq "@$y[0..5]";
111 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
112 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
113 my @fstat = stat LOCK or die "$self: fstat: $!\n";
114 my @stat = stat $lockfile;
116 next if $! == ENOENT;
117 die "$self: stat $lockfile: $!\n";
119 last if same_file(\@fstat,\@stat);
123 unlink $lockfile or die "$self: removing lockfile: $!\n";
131 die "$self: config key \`@_': $m\n";
135 foreach my $cfg (@configs) {
138 last unless defined $v;
139 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
142 return $v if defined $v;
150 my $got = ref($v) || 'scalar';
151 return $v if !defined($v) || $got eq $exp;
152 badcfg @_, "found \L$got\E, expected \L$exp\E";
153 # ^ toml doesn't make refs to scalars, so this is unambiguous
158 (cfge $exp, @_) // badcfg @_, "missing";
161 sub cfgs { cfge 'scalar', @_ }
162 sub cfgsn { cfgn 'scalar', @_ }
166 return $v if !defined($v) || Types::Serialiser::is_bool $v;
167 badcfg @_, "expected boolean";
171 my $l = cfge 'ARRAY', @_;
172 foreach my $x (@$l) {
173 !ref $x or badcfg @_, "list contains non-scalar element";
179 my $nailfile = "../Cargo.nail";
180 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
182 my $toml = <N> // die "$self: read $nailfile: $!";
184 if ($toml !~ m{^\s*\[/}m &&
185 $toml !~ m{^[^\n\#]*\=}m &&
186 # old non-toml syntax
187 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
188 $toml =~ s{^}{[packages\]\n};
190 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
193 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
197 ($nail,$e) = from_toml($toml);
198 if (!defined $nail) {
201 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
204 die "$self: parse $nailfile: $e\n";
206 die "$e ?" if length $e;
208 $nail->{subdirs} //= [ ];
210 if (!ref $nail->{subdirs}) {
213 map { s/^\s+//; s/\s+$//; $_; }
219 unshift @configs, $nail;
222 our @alt_cargo_lock_stat;
224 sub consider_alt_cargo_lock () {
225 my @ck = qw(alt_cargo_lock);
226 # User should *either* have Cargo.lock in .gitignore,
227 # or expect to commit Cargo.lock.example ($alt_cargo_lock)
229 $alt_cargo_lock = (cfg_uc @ck);
232 if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
233 $force = cfg_bool qw(alt_cargo_lock force);
234 my @ck = qw(alt_cargo_lock file);
235 $alt_cargo_lock = cfg_uc @ck;
237 $alt_cargo_lock //= Types::Serialiser::true;
239 if (Types::Serialiser::is_bool $alt_cargo_lock) {
240 if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
241 $alt_cargo_lock = 'Cargo.lock.example';
244 if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
245 badcfg @ck, "expected boolean, or leafname";
248 if (!stat_exists $alt_cargo_lock, "alt_cargo_lock") {
249 $alt_cargo_lock = undef unless $force;
253 @alt_cargo_lock_stat = stat _;
256 our $oot_dir; # oot.dir or "Build"
258 sub consider_oot () {
259 $oot_dir = cfgs qw(oot dir);
260 my $use = cfgs qw(oot use);
261 unless (defined($oot_dir) || defined($use)) {
262 die "$self: specified --cargo-lock-update but not out-of-tree build!\n"
263 if $cargo_lock_update;
264 $cargo_lock_update=0;
267 $oot_dir //= 'Build';
273 sub read_manifest ($) {
275 my $manifest = "../$subdir/Cargo.toml";
276 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
277 if (defined $manifests{$manifest}) {
279 "$self: warning: $subdir: specified more than once!\n";
282 foreach my $try ("$manifest.unnailed", "$manifest") {
283 my $toml = toml_or_enoent($try, "package manifest") // next;
284 my $p = $toml->{package}{name};
287 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
290 $manifests{$manifest} = $toml;
297 foreach my $p (keys %{ $nail->{packages} }) {
298 my $v = $nail->{packages}{$p};
299 my $subdir = ref($v) ? $v->{subdir} : $v;
300 my $gotpackage = read_manifest($subdir) // '<nothing!>';
301 if ($gotpackage ne $p) {
303 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
305 die if defined $packagemap{$p};
306 $packagemap{$p} = $subdir;
308 foreach my $subdir (@{ $nail->{subdirs} }) {
309 my $gotpackage = read_manifest($subdir);
310 if (!defined $gotpackage) {
312 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
315 $packagemap{$gotpackage} //= $subdir;
320 foreach my $p (sort keys %packagemap) {
321 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
323 foreach my $mf (keys %manifests) {
324 my $toml = $manifests{$mf};
325 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
326 my $deps = $toml->{$k};
328 foreach my $p (keys %packagemap) {
329 my $info = $deps->{$p};
330 next unless defined $info;
331 $deps->{$p} = $info = { } unless ref $info;
332 delete $info->{version};
333 $info->{path} = $worksphere.'/'.$packagemap{$p};
336 my $nailing = "$mf.nailing~";
337 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
338 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
339 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
340 close N or die "$self: close new $nailing: $!\n";
345 $online //= cfg_bool qw(misc online);
348 $ARGV[0] =~ m{\bcargo\b}) {
349 if ($ARGV[1] =~ m/^(?:generate-lockfile|update)$/) {
350 $cargo_lock_update //= 1;
353 if ($ARGV[1] =~ m/^(?:fetch)$/) {
358 $cargo_lock_update //= 0;
359 $cargo_manifest_args //=
360 (defined $oot_dir) && !$cargo_lock_update;
364 if ($cargo_manifest_args) {
365 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
367 push @ARGV, qw(--target-dir=target) if $cargo_target_arg;
370 if (defined $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;
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";
641 while (@ARGV && $ARGV[0] =~ m/^-/) {
648 } elsif (s{^-q}{-}) {
650 } elsif (s{^-n}{-}) {
652 } elsif (s{^-D}{-}) {
654 } elsif (s{^-A(.+)}{-}s) {
656 } elsif (s{^-([uU])}{-}) {
657 $cargo_lock_update= $1=~m/[a-z]/;
658 } elsif (s{^-([mM])}{-}) {
659 $cargo_manifest_args= $1=~m/[a-z]/;
660 } elsif (s{^-([tT])}{-}) {
661 $cargo_target_arg= $1=~m/[a-z]/;
662 } elsif (s{^-([oO])}{-}) {
663 $online= $1=~m/[a-z]/;
665 die "$self: unknown short option(s) $_\n";
668 } elsif (s{^--(?:target|arch)=}{}) {
670 } elsif (m{^--(no-)?cargo-lock-update}) {
671 $cargo_lock_update= !!$1;
672 } elsif (m{^--(no-)?cargo-manifest-args}) {
673 $cargo_manifest_args= !!$1;
674 } elsif (m{^--(no-)?cargo-target-arg}) {
675 $cargo_target_arg= !!$1;
676 } elsif (m{^--(on|off)line$}) {
677 $online = $1 eq 'on';
679 die "$self: unknown long option $_\n";
683 die "$self: need command to run\n" unless @ARGV || $noact;
688 consider_alt_cargo_lock();
693 our @display_cmd = @ARGV;
694 oot_massage_cmdline();
700 print STDERR Dumper(\%manifests) if $dump>=2;
701 print STDERR Dumper(\%packagemap, \@ARGV,
702 { src_absdir => $src_absdir,
703 worksphere => $worksphere,
706 oot_absdir => $oot_absdir,
707 build_absdir => $build_absdir });
717 printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
718 (scalar keys %manifests), (scalar keys %packagemap),
719 (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
722 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
723 my $estatus = invoke();
725 cargo_lock_update_after();
730 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;