Skip to main content

bevy_asset/io/file/
mod.rs

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