#figuring out paths in a project

10 messages · Page 1 of 1 (latest)

shadow canyon
#
use std::env;
use std::path::PathBuf;

fn main() {
    let mut proj_dir = PathBuf::from("/");
    let cargo_location = env::var("CARGO_MANIFEST_DIR");
    if cargo_location.is_ok(){
        proj_dir = match cargo_location {
            Ok(s) => PathBuf::from(&s),
            Err(e) => panic!("{e}"),
        };
    }
    proj_dir.push("src"); // get the src path for example
    println!("{proj_dir:#?}");
}

I've been figuring out how to get the current project dir and this is one of the solutions i arrived at

why i need this is simply, i work with files a lot and i want a way to get locations within the project without hardcoding it into the file, so everything is relative.
so say, from this path proj_dir i can do .push("src") and get the path to the src folder, etc.

is there a better, more robust way of doing it?

oblique otter
#

If it's at runtime you'd usually just have the filepaths be relative (not to the cargo manifest dir)...then they'll be relative to the current working directory

Cargo manifest dir isn't set if you're not running through cargo

shadow canyon
#

i believe i have misunderstood stuff in rust, since it is compiled, it's just gonna be one executable in the end and std::env::current_dir should be enough

my worries was with "if i move this executable elsewhere, it should still work with the paths i've set" and its basically pwd

blissful kite
shadow canyon
oblique otter
#

I think it's just saying it's a security issue because people can change files on their storage arbitrarily, so just don't execute the thing at that path because it can be anything

low garden
#

afaik the security issue is only relevant to things like setuid executables, where your process has more permissions than the process that started it and therefore controls its environment