fornwall / rust-script

Run Rust files and expressions as scripts without any setup or compilation step.
https://rust-script.org
Apache License 2.0
1.2k stars 41 forks source link

Obtaining the path to a script and/or its containing directory through a symlink #121

Open kellytk opened 9 months ago

kellytk commented 9 months ago
#!/usr/bin/env rust-script

// Layout:
// /home/kellytk/symlinkedscript/
// /home/kellytk/symlinkedscript/script/script.rs - this file.
// /home/kellytk/symlinkedscript/symlink/script.rs - symlink (ln -s /home/kellytk/symlinkedscript/script/script.rs /home/kellytk/symlinkedscript/symlink/script.rs)

let path = std::env::var("RUST_SCRIPT_BASE_PATH").expect("fetch failure");

println!(
    "RUST_SCRIPT_BASE_PATH: {:?}",
    path,
);

println!("canonicalized path: {:?}", std::fs::canonicalize(path).expect("canonicalize failure"));

/*
$ pwd
/home/kellytk/symlinkedscript

As expected:
$ ./script/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./script"
canonicalized path: "/home/kellytk/symlinkedscript/script"

Unexpected:
$ ./symlink/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./symlink"
canonicalized path: "/home/kellytk/symlinkedscript/symlink"

Expected:
$ ./symlink/script.rs
RUST_SCRIPT_BASE_PATH: "/home/kellytk/symlinkedscript/./script"
canonicalized path: "/home/kellytk/symlinkedscript/script"
*/

How please can the expected result be obtained in both cases?