diff options
author | Daniel Silverstone <dsilvers@digital-scurf.org> | 2021-01-10 11:56:11 +0000 |
---|---|---|
committer | Daniel Silverstone <dsilvers@digital-scurf.org> | 2021-01-10 11:56:11 +0000 |
commit | daa0761dedf1a970400f6052f7a36bf2a95ff283 (patch) | |
tree | 17795e6dd959c684d0fa0d1caa2b089932bf39c1 /src/resource.rs | |
parent | 78358aca233d3cb369b83bd958a595ca3ae90ae5 (diff) | |
download | subplot-daa0761dedf1a970400f6052f7a36bf2a95ff283.tar.gz |
resource: Support setting the template name
Signed-off-by: Daniel Silverstone <dsilvers@digital-scurf.org>
Diffstat (limited to 'src/resource.rs')
-rw-r--r-- | src/resource.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/resource.rs b/src/resource.rs index 2c1df0a..d8fab16 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -41,6 +41,7 @@ lazy_static! { let ret = Vec::new(); Mutex::new(ret) }; + static ref TEMPLATE_NAME: Mutex<Option<String>> = Mutex::new(None); } static EMBEDDED_FILES: &[(&str, &[u8])] = include!(concat!(env!("OUT_DIR"), "/embedded_files.inc")); @@ -53,10 +54,41 @@ pub fn add_search_path<P: AsRef<Path>>(path: P) { .push(path.as_ref().into()); } +/// Set the template name, for use in searching for content... +pub fn set_template(template: &str) { + *TEMPLATE_NAME.lock().expect("Unable to lock TEMPLATE_NAME") = Some(template.to_string()); +} + /// 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<dyn Read>> { let subpath = subpath.as_ref(); + match internal_open(subpath) { + Ok(r) => Ok(r), + Err(e) => { + let template = TEMPLATE_NAME.lock().expect("Unable to lock TEMPLATE_NAME"); + if let Some(templ) = template.as_deref() { + let subpath = Path::new(templ).join(subpath); + match internal_open(&subpath) { + Ok(r) => Ok(r), + Err(sub_e) => { + if sub_e.kind() != io::ErrorKind::NotFound + && e.kind() == io::ErrorKind::NotFound + { + Err(sub_e) + } else { + Err(e) + } + } + } + } else { + Err(e) + } + } + } +} + +fn internal_open(subpath: &Path) -> io::Result<Box<dyn Read>> { 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() |