I just published my first crate, however the executable can't find the file in the working directory

let songs_info = get_songs_info("playlist/jay.json");


pub fn get_songs_info(path: &str) -> SongsInfo {
    let file = std::fs::File::open(path).expect("file not found");
    let reader = std::io::BufReader::new(file);

    let jay_music: JayMusic = serde_json::from_reader(reader).expect("json parse error");
    jay_music.list
}

I read file with relative path, and the file is in my working directory:

2023-08-07 at 8.58 PM

I can successfully run it with cargo run, however after publishing the crate and downloading it, run the executable in a different directory, it complains:

thread 'main' panicked at 'file not found: Os { code: 2, kind: NotFound, message: "No such file or directory" }

Publishing doesn't upload arbitrary files. It only uploads sources and Cargo metadata.

Okayyyy, would you mind sharing some best practices of including a json alongside the current crate?

cargo install only works for programs that don't need any auxiliary files. For programs that do, there is little use in cargo publishing them.

Cargo in general doesn't deal with auxiliary files and nontrivial packaging/distribution problems — its job stops at producing an executable. You have to do the rest yourself. (And libraries are expected to not need any such files at all.)

Note that if you want to, it is easy to embed files in the program (so they are read at compile time, and not needed later), with include_str!("playlist/jay.json"). Many Rust programs do this. Of course, this is less flexible in that users can't edit the files after compilation.

5 Likes

If it's really static data, then as @kpreid mentioned, you should be able to include_str! it.

Although I strongly doubt that a playlist is (or should be) static data. Why don't you just make the path an argument of the application?

Not the OP, but I was actually wondering about this very thing this morning. Good to know!

In my case, the json file is actually static data. Thanks for the help!