bevy_asset/io/file/
mod.rs

1#[cfg(feature = "file_watcher")]
2mod file_watcher;
3
4#[cfg(feature = "multi_threaded")]
5mod file_asset;
6#[cfg(not(feature = "multi_threaded"))]
7mod sync_file_asset;
8
9use bevy_utils::tracing::error;
10#[cfg(feature = "file_watcher")]
11pub use file_watcher::*;
12
13use std::{
14    env,
15    path::{Path, PathBuf},
16};
17
18pub(crate) fn get_base_path() -> PathBuf {
19    if let Ok(manifest_dir) = env::var("BEVY_ASSET_ROOT") {
20        PathBuf::from(manifest_dir)
21    } else if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
22        PathBuf::from(manifest_dir)
23    } else {
24        env::current_exe()
25            .map(|path| {
26                path.parent()
27                    .map(|exe_parent_path| exe_parent_path.to_owned())
28                    .unwrap()
29            })
30            .unwrap()
31    }
32}
33
34/// I/O implementation for the local filesystem.
35///
36/// This asset I/O is fully featured but it's not available on `android` and `wasm` targets.
37pub struct FileAssetReader {
38    root_path: PathBuf,
39}
40
41impl FileAssetReader {
42    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
43    /// watching for changes.
44    ///
45    /// See `get_base_path` below.
46    pub fn new<P: AsRef<Path>>(path: P) -> Self {
47        let root_path = Self::get_base_path().join(path.as_ref());
48        Self { root_path }
49    }
50
51    /// Returns the base path of the assets directory, which is normally the executable's parent
52    /// directory.
53    ///
54    /// If the `CARGO_MANIFEST_DIR` environment variable is set, then its value will be used
55    /// instead. It's set by cargo when running with `cargo run`.
56    pub fn get_base_path() -> PathBuf {
57        get_base_path()
58    }
59
60    /// Returns the root directory where assets are loaded from.
61    ///
62    /// See `get_base_path`.
63    pub fn root_path(&self) -> &PathBuf {
64        &self.root_path
65    }
66}
67
68pub struct FileAssetWriter {
69    root_path: PathBuf,
70}
71
72impl FileAssetWriter {
73    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
74    /// watching for changes.
75    ///
76    /// See `get_base_path` below.
77    pub fn new<P: AsRef<Path> + std::fmt::Debug>(path: P, create_root: bool) -> Self {
78        let root_path = get_base_path().join(path.as_ref());
79        if create_root {
80            if let Err(e) = std::fs::create_dir_all(&root_path) {
81                error!(
82                    "Failed to create root directory {:?} for file asset writer: {:?}",
83                    root_path, e
84                );
85            }
86        }
87        Self { root_path }
88    }
89}