summaryrefslogtreecommitdiff
path: root/src/resource.rs
diff options
context:
space:
mode:
authorDaniel Silverstone <dsilvers@digital-scurf.org>2021-01-09 15:58:06 +0000
committerDaniel Silverstone <dsilvers@digital-scurf.org>2021-01-09 15:58:06 +0000
commite9b941e5218e5e4293bb915b13f831baba246a89 (patch)
tree0f2212a44b4831a7853662486b47dc170c792175 /src/resource.rs
parent9d5758cd7b6bf63c83232fc0a71ae906a2be9c8b (diff)
downloadsubplot-e9b941e5218e5e4293bb915b13f831baba246a89.tar.gz
resource: Add support for multiple search paths
Signed-off-by: Daniel Silverstone <dsilvers@digital-scurf.org>
Diffstat (limited to 'src/resource.rs')
-rw-r--r--src/resource.rs38
1 files changed, 36 insertions, 2 deletions
diff --git a/src/resource.rs b/src/resource.rs
index f34d806..dd30678 100644
--- a/src/resource.rs
+++ b/src/resource.rs
@@ -6,13 +6,47 @@
//! binary and present on disk.
use std::io::{self, Read};
-use std::path::Path;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+
+use lazy_static::lazy_static;
+
+lazy_static! {
+ static ref SEARCH_PATHS: Mutex<Vec<PathBuf>> = {
+ let ret = Vec::new();
+ Mutex::new(ret)
+ };
+}
+
+/// Put a path at the back of the queue to search in
+pub fn add_search_path<P: AsRef<Path>>(path: P) {
+ SEARCH_PATHS
+ .lock()
+ .expect("Unable to lock SEARCH_PATHS")
+ .push(path.as_ref().into());
+}
/// Open a file for reading, honouring search paths established during
/// startup, and falling back to potentially embedded file content
pub fn open<P: AsRef<Path>>(subpath: P) -> io::Result<Box<impl Read>> {
let subpath = subpath.as_ref();
- Ok(Box::new(std::fs::File::open(subpath)?))
+ let search_paths = SEARCH_PATHS.lock().expect("Unable to lock SEARCH_PATHS");
+ let search_paths = search_paths.iter().map(|p| p.as_path());
+ let search_paths = std::iter::empty()
+ .chain(Some(Path::new(".")))
+ .chain(search_paths);
+ let mut ret = Err(io::Error::new(
+ io::ErrorKind::NotFound,
+ format!("Unable to find {} in resource paths", subpath.display()),
+ ));
+ for basepath in search_paths {
+ let full_path = basepath.join(subpath);
+ ret = std::fs::File::open(full_path);
+ if ret.is_ok() {
+ break;
+ }
+ }
+ Ok(Box::new(ret?))
}
/// Read a file, honouring search paths established during startup, and