Skip to main content

yog_script_build/
files.rs

1//! A mod's files as its sources include them (`include_str!`): each path
2//! beside its source, inside the folder the sources are named from.
3
4use std::path::{Path, PathBuf};
5
6use yog_script_analyze::macros::ModFiles;
7
8/// Files beside their sources, the sources named from `base` (a mod's
9/// root, the folder a tool runs in); none read from outside it.
10pub struct FilesBeside {
11    pub base: PathBuf,
12}
13
14impl ModFiles for FilesBeside {
15    fn read(&self, source: &str, path: &str) -> Result<String, String> {
16        let beside = self
17            .base
18            .join(source)
19            .parent()
20            .map_or_else(|| self.base.clone(), Path::to_path_buf)
21            .join(path);
22        let file = beside.canonicalize().map_err(|e| e.to_string())?;
23        let base = self.base.canonicalize().map_err(|e| e.to_string())?;
24        if !file.starts_with(&base) {
25            return Err(format!("it's outside `{}`", base.display()));
26        }
27        std::fs::read_to_string(&file).map_err(|e| e.to_string())
28    }
29}