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-caretwgo make
22 # ../nailing-cargo/nailing-cargo cargo build
23 # CARGO='../nailing-cargo/nailing-cargo cargo' make
25 # Why do we need this ?
27 # https://github.com/rust-lang/cargo/issues/6713
28 # https://stackoverflow.com/questions/33025887/how-to-use-a-local-unpublished-crate
29 # https://github.com/rust-lang/cargo/issues/1481
37 # package = { subdir = ... }
46 use Types::Serialiser;
49 RPI => 'arm-unknown-linux-gnueabihf',
53 $self = $0; $self =~ s{^.*/(?=.)}{};
55 while ($deref =~ m{^/}) {
56 my $link = readlink $deref;
59 or die "$self: checking our script location $deref: $!\n";
60 $deref =~ s{/[^/]+$}{}
61 or die "$self: unexpected script path: $deref\n";
62 unshift @INC, $deref."/TOML-Tiny/lib";
65 last if $link !~ m{^/};
70 use Fcntl qw(LOCK_EX);
72 use TOML::Tiny::Faithful;
74 our $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
76 our $worksphere = $src_absdir;
77 $worksphere =~ s{/([^/]+)$}{}
78 or die "$self: cwd \`$worksphere' unsupported!\n";
79 our $subdir = $1; # leafname
81 our $lockfile = "../.nailing-cargo.lock";
83 our $cargo_lock_update;
84 our $cargo_manifest_args;
91 sub read_or_enoent ($) {
93 if (!open R, '<', $fn) {
94 return undef if $!==ENOENT;
95 die "$self: open $fn: $!\n";
98 my ($r) = <R> // die "$self: read $fn: $!\n";
102 sub stat_exists ($$) {
103 my ($fn, $what) = @_;
104 if (stat $fn) { return 1; }
105 $!==ENOENT or die "$self: stat $what: $fn: $!\n";
109 sub toml_or_enoent ($$) {
111 my $toml = read_or_enoent($f) // return;
112 my ($v,$e) = from_toml($toml);
115 die "$self: parse TOML: $what: $f: $e\n";
117 die "$e ?" if length $e;
121 sub load1config ($) {
123 my $toml = toml_or_enoent($f, "config file");
124 push @configs, $toml if defined $toml;
128 my $cfgleaf = ".nailing-cargo-cfg.toml";
129 load1config("/etc/nailing-cargo/cfg.toml");
130 load1config("$worksphere/$cfgleaf");
131 load1config("$ENV{HOME}/$cfgleaf") if defined $ENV{HOME};
136 foreach my $cfg (@configs) {
138 return $v if defined $v;
143 sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }
147 "@$x[0..5]" eq "@$y[0..5]";
152 open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
153 flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
154 my @fstat = stat LOCK or die "$self: fstat: $!\n";
155 my @stat = stat $lockfile;
157 next if $! == ENOENT;
158 die "$self: stat $lockfile: $!\n";
160 last if same_file(\@fstat,\@stat);
164 unlink $lockfile or die "$self: removing lockfile: $!\n";
172 die "$self: config key \`@_': $m\n";
178 last unless defined $v;
179 ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
188 my $got = ref($v) || 'scalar';
189 return $v if !defined($v) || $got eq $exp;
190 badcfg @_, "found \L$got\E, expected \L$exp\E";
191 # ^ toml doesn't make refs to scalars, so this is unambiguous
196 (cfge $exp, @_) // badcfg @_, "missing";
199 sub cfgs { cfge 'scalar', @_ }
200 sub cfgsn { cfgn 'scalar', @_ }
203 my $l = cfge 'ARRAY', @_;
204 foreach my $x (@$l) {
205 !ref $x or badcfg @_, "list contains non-scalar element";
211 my $nailfile = "../Cargo.nail";
212 open N, '<', $nailfile or die "$self: open $nailfile: $!\n";
214 my $toml = <N> // die "$self: read $nailfile: $!";
216 if ($toml !~ m{^\s*\[/}m &&
217 $toml !~ m{^[^\n\#]*\=}m &&
218 # old non-toml syntax
219 $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
220 $toml =~ s{^}{[packages\]\n};
222 $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
225 $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
229 ($nail,$e) = from_toml($toml);
230 if (!defined $nail) {
233 print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
236 die "$self: parse $nailfile: $e\n";
238 die "$e ?" if length $e;
240 if (!ref $nail->{subdirs}) {
243 map { s/^\s+//; s/\s+$//; $_; }
250 our $oot_dir; # oot.dir or "Build"
252 sub consider_oot () {
253 $oot_dir = cfgs qw(oot dir);
254 my $use = cfgs qw(oot use);
255 unless (defined($oot_dir) || defined($use)) {
256 $cargo_lock_update//=0;
259 $oot_dir //= 'Build';
265 sub read_manifest ($) {
267 my $manifest = "../$subdir/Cargo.toml";
268 print STDERR "$self: reading $manifest...\n" if $verbose>=4;
269 if (defined $manifests{$manifest}) {
271 "$self: warning: $subdir: specified more than once!\n";
274 foreach my $try ("$manifest.unnailed", "$manifest") {
275 my $toml = toml_or_enoent($try, "package manifest") // next;
276 my $p = $toml->{package}{name};
279 "$self: warning: $subdir: missing package.name in $try, ignoring\n";
282 $manifests{$manifest} = $toml;
289 foreach my $p (keys %{ $nail->{packages} }) {
290 my $v = $nail->{packages}{$p};
291 my $subdir = ref($v) ? $v->{subdir} : $v;
292 my $gotpackage = read_manifest($subdir) // '<nothing!>';
293 if ($gotpackage ne $p) {
295 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
297 die if defined $packagemap{$p};
298 $packagemap{$p} = $subdir;
300 foreach my $subdir (@{ $nail->{subdirs} }) {
301 my $gotpackage = read_manifest($subdir);
302 if (!defined $gotpackage) {
304 "$self: warning: ignoring subdir $subdir which has no Cargo.toml\n";
307 $packagemap{$gotpackage} //= $subdir;
312 foreach my $p (sort keys %packagemap) {
313 print STDERR "$self: package $p in $packagemap{$p}\n" if $verbose>=2;
315 foreach my $mf (keys %manifests) {
316 my $toml = $manifests{$mf};
317 foreach my $k (qw(dependencies build-dependencies dev-dependencies)) {
318 my $deps = $toml->{$k};
320 foreach my $p (keys %packagemap) {
321 my $info = $deps->{$p};
322 next unless defined $info;
323 $deps->{$p} = $info = { } unless ref $info;
324 delete $info->{version};
325 $info->{path} = $worksphere.'/'.$packagemap{$p};
328 my $nailing = "$mf.nailing~";
329 unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
330 open N, '>', $nailing or die "$self: create new $nailing: $!\n";
331 print N to_toml($toml) or die "$self: write new $nailing: $!\n";
332 close N or die "$self: close new $nailing: $!\n";
338 $ARGV[0] =~ m{\bcargo\b} &&
339 $ARGV[1] =~ m/generate-lockfile|update/) {
340 $cargo_lock_update //= 1;
342 $cargo_lock_update //= 0;
344 $cargo_manifest_args //=
345 (defined $oot_dir) && !$cargo_lock_update;
347 if ($cargo_manifest_args) {
348 push @ARGV, "--manifest-path=${src_absdir}/Cargo.toml",
349 qw(--locked --target-dir=target);
352 if (defined $target) {
353 if ($target =~ m{^[A-Z]}) {
354 $target = (cfgs 'arch', $target) // $archmap{$target}
355 // die "$self: --target=$target alias specified; not in cfg or map\n";
357 push @ARGV, "--target=$target";
362 our $build_absdir; # .../Build/<subdir>
364 sub oot_massage_cmdline () {
365 return unless defined $oot_dir;
367 my $use = cfgs qw(oot use);
368 $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;
369 $build_absdir = "$oot_absdir/$subdir";
373 if (!$cargo_lock_update) {
374 push @xargs, $build_absdir;
375 ($pre, $post) = ('cd "$1"; shift; ', '');
377 push @xargs, $oot_absdir, $subdir, $src_absdir;
380 mkdir -p -- "$1"; cd "$1"; shift;
381 cp -- "$1"/Cargo.toml .;
384 cp -- "$1"/Cargo.lock .;
387 cp -- "$1"/Cargo.lock .;
391 mkdir -p src; >src/lib.rs;
394 rm -r src Cargo.toml;
397 my $addpath = (cfg_uc qw(oot path_add)) //
398 $use eq 'really' ? Types::Serialiser::true : Types::Serialiser::false;
400 !Types::Serialiser::is_bool $addpath ? $addpath :
401 $addpath ? '$HOME/.cargo/bin' :
403 if (defined $addpath) {
405 PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
409 $pre =~ s/^\s+//mg; $pre =~ s/\s+/ /g;
410 $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;
412 my $getuser = sub { cfgsn qw(oot user) };
414 my $xe = $verbose >= 2 ? 'xe' : 'e';
417 @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
419 @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
421 push @command, @ARGV;
423 my $command_sh = sub {
424 my $quoted = join ' ', map {
429 @command = @_, "set -${xe}; $pre $quoted; $post";
431 print STDERR "$self: out-of-tree, building in: \`$build_absdir'\n"
433 if ($use eq 'really') {
434 my $user = $getuser->();
435 my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
436 my $homedir = $pw[7];
437 $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
438 print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
439 } elsif ($use eq 'ssh') {
440 my $user = $getuser->();
441 $user .= '@localhost' unless $user =~ m/\@/;
442 $command_sh->('ssh',$user);
443 print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
444 } elsif ($use eq 'command_args') {
445 my @c = cfgn_list qw(oot command);
447 print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
448 } elsif ($use eq 'command_sh') {
449 my @c = cfgn_list qw(oot command);
451 print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
452 } elsif ($use eq 'null') {
455 die "$self: oot.use mode $use not recognised\n";
462 $ENV{NAILINGCARGO_WORKSPHERE} = $worksphere;
463 $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir;
464 $ENV{NAILINGCARGO_BUILDSPHERE} = $oot_absdir;
465 delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
466 $ENV{NAILINGCARGO_BUILD_DIR} = $build_absdir // $src_absdir;
472 if ($want_uninstall) {
474 foreach my $mf (keys %manifests) {
475 eval { uninstall1($mf,1); 1; } or warn "$@";
481 foreach my $mf (keys %manifests) {
482 link "$mf", "$mf.unnailed" or $!==EEXIST
483 or die "$self: make backup link $mf.unnailed: $!\n";
489 my $nailed = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
494 foreach my $mf (keys %manifests) {
495 my $nailing = "$mf.nailing~";
496 my $nailed = nailed($mf);
499 if (open NN, '<', $nailed) {
500 $diff = compare($nailing, \*NN);
501 die "$self: compare $nailing and $nailed: $!" if $diff<0;
503 $!==ENOENT or die "$self: check previous $nailed: $!\n";
513 rename $use, $mf or die "$self: install nailed $use: $!\n";
514 unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
515 print STDERR "$self: nailed $mf\n" if $verbose>=3;
520 my $r = system @ARGV;
524 print STDERR "$self: could not execute $ARGV[0]: $!\n";
526 } elsif ($r & 0xff00) {
527 print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
530 print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
535 sub cargo_lock_update_after () {
536 return unless $cargo_lock_update;
537 # avoids importing File::Copy and the error handling is about as good
539 my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
540 die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
541 die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
544 sub uninstall1 ($$) {
545 my ($mf, $enoentok) = @_;
546 my $unnailed = "$mf.unnailed";
547 rename $unnailed, $mf or ($enoentok && $!==ENOENT)
548 or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
552 foreach my $mf (keys %manifests) {
553 my $nailed = nailed($mf);
554 link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
559 while (@ARGV && $ARGV[0] =~ m/^-/) {
566 } elsif (s{^-q}{-}) {
568 } elsif (s{^-n}{-}) {
570 } elsif (s{^-D}{-}) {
572 } elsif (s{^-T(.+)}{-}s) {
574 } elsif (s{^-([uU])}{-}) {
575 $cargo_lock_update= $1=~m/[a-z]/;
576 } elsif (s{^-([mM])}{-}) {
577 $cargo_manifest_args= $1=~m/[a-z]/;
579 die "$self: unknown short option(s) $_\n";
582 } elsif (s{^--target=}{}) {
584 } elsif (m{^--(no-)?cargo-lock-update}) {
585 $cargo_lock_update= !!$1;
586 } elsif (m{^--(no-)?cargo-manifest-args}) {
587 $cargo_manifest_args= !!$1;
589 die "$self: unknown long option $_\n";
593 die "$self: need command to run\n" unless @ARGV || $noact;
601 our @display_cmd = @ARGV;
602 oot_massage_cmdline();
608 print STDERR Dumper(\%manifests) if $dump>=2;
609 print STDERR Dumper(\%packagemap, \@ARGV,
610 { src_absdir => $src_absdir,
611 worksphere => $worksphere,
614 oot_absdir => $oot_absdir,
615 build_absdir => $build_absdir });
625 printf STDERR "$self: nailed (%s manifests, %s packages)\n",
626 (scalar keys %manifests), (scalar keys %packagemap)
629 print STDERR "$self: invoking: @display_cmd\n" if $verbose;
630 my $estatus = invoke();
635 cargo_lock_update_after();
637 print STDERR "$self: unnailed. status $estatus.\n" if $verbose;