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
9#[cfg(feature = "file_watcher")]
10pub use file_watcher::*;
11use tracing::{debug, error};
12
13use alloc::borrow::ToOwned;
14use std::{
15    env,
16    path::{Path, PathBuf},
17};
18
19pub(crate) fn get_base_path() -> PathBuf {
20    if let Ok(manifest_dir) = env::var("BEVY_ASSET_ROOT") {
21        PathBuf::from(manifest_dir)
22    } else if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
23        PathBuf::from(manifest_dir)
24    } else {
25        env::current_exe()
26            .map(|path| path.parent().map(ToOwned::to_owned).unwrap())
27            .unwrap()
28    }
29}
30
31/// I/O implementation for the local filesystem.
32///
33/// This asset I/O is fully featured but it's not available on `android` and `wasm` targets.
34pub struct FileAssetReader {
35    root_path: PathBuf,
36}
37
38impl FileAssetReader {
39    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
40    /// watching for changes.
41    ///
42    /// See `get_base_path` below.
43    pub fn new<P: AsRef<Path>>(path: P) -> Self {
44        let root_path = Self::get_base_path().join(path.as_ref());
45        debug!(
46            "Asset Server using {} as its base path.",
47            root_path.display()
48        );
49        Self { root_path }
50    }
51
52    /// Returns the base path of the assets directory, which is normally the executable's parent
53    /// directory.
54    ///
55    /// To change this, set [`AssetPlugin.file_path`].
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
68/// A writer for the local filesystem.
69pub struct FileAssetWriter {
70    root_path: PathBuf,
71}
72
73impl FileAssetWriter {
74    /// Creates a new [`FileAssetWriter`] at a path relative to the executable's directory, optionally
75    /// watching for changes.
76    pub fn new<P: AsRef<Path> + core::fmt::Debug>(path: P, create_root: bool) -> Self {
77        let root_path = get_base_path().join(path.as_ref());
78        if create_root {
79            if let Err(e) = std::fs::create_dir_all(&root_path) {
80                error!(
81                    "Failed to create root directory {} for file asset writer: {}",
82                    root_path.display(),
83                    e
84                );
85            }
86        }
87        Self { root_path }
88    }
89}