config.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. //! Where the user's files live.
  2. //!
  3. //! Resolution order for each value: environment variable, then the config
  4. //! file (`VICTORY_CONFIG`, else `./victory.toml`), then the default.
  5. //! See `victory.example.toml` at the repository root.
  6. use std::path::{Path, PathBuf};
  7. use anyhow::{Context, Result};
  8. use serde::Deserialize;
  9. use crate::policy::ensure_outside_repo;
  10. #[derive(Debug, Default, Clone)]
  11. pub struct Config {
  12. /// The user's dump of the title.
  13. pub game_dir: Option<PathBuf>,
  14. /// Root for all derived data. Always outside the repository.
  15. pub cache_dir: PathBuf,
  16. /// What titles write and must keep (persistent local storage). Never
  17. /// inside the cache, which may be deleted at any time.
  18. pub data_dir: PathBuf,
  19. /// Other titles used to exercise platform-level code.
  20. pub test_titles: Vec<PathBuf>,
  21. /// The config file that was read, if any.
  22. pub source: Option<PathBuf>,
  23. }
  24. #[derive(Debug, Default, Deserialize)]
  25. #[serde(deny_unknown_fields)]
  26. struct FileConfig {
  27. #[serde(default)]
  28. paths: FilePaths,
  29. }
  30. #[derive(Debug, Default, Deserialize)]
  31. #[serde(deny_unknown_fields)]
  32. struct FilePaths {
  33. game_dir: Option<PathBuf>,
  34. cache_dir: Option<PathBuf>,
  35. data_dir: Option<PathBuf>,
  36. #[serde(default)]
  37. test_titles: Vec<PathBuf>,
  38. }
  39. impl Config {
  40. /// Loads configuration from the environment and the config file.
  41. pub fn load() -> Result<Self> {
  42. let explicit = explicit_config_path(|k| std::env::var_os(k));
  43. let path = explicit
  44. .clone()
  45. .unwrap_or_else(|| PathBuf::from("victory.toml"));
  46. let file = if path.is_file() {
  47. let text = std::fs::read_to_string(&path)
  48. .with_context(|| format!("reading {}", path.display()))?;
  49. Some((path, text))
  50. } else if let Some(p) = explicit {
  51. anyhow::bail!(
  52. "VICTORY_CONFIG points at {}, which does not exist",
  53. p.display()
  54. );
  55. } else {
  56. None
  57. };
  58. let (source, parsed) = match file {
  59. Some((path, text)) => {
  60. let parsed: FileConfig =
  61. toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
  62. (Some(path), parsed)
  63. }
  64. None => (None, FileConfig::default()),
  65. };
  66. Self::resolve(parsed.paths, source, |k| std::env::var_os(k))
  67. }
  68. fn resolve(
  69. file: FilePaths,
  70. source: Option<PathBuf>,
  71. env: impl Fn(&str) -> Option<std::ffi::OsString>,
  72. ) -> Result<Self> {
  73. let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
  74. let test_titles = match env("VICTORY_TEST_TITLES") {
  75. Some(v) if !v.is_empty() => std::env::split_paths(&v)
  76. .filter(|p| !p.as_os_str().is_empty())
  77. .collect(),
  78. _ => file.test_titles,
  79. };
  80. let cache_dir = env_path("VICTORY_CACHE_DIR")
  81. .or(file.cache_dir)
  82. .map_or_else(|| default_dir("cache"), Ok)?;
  83. let data_dir = env_path("VICTORY_DATA_DIR")
  84. .or(file.data_dir)
  85. .map_or_else(|| default_dir("data"), Ok)?;
  86. Ok(Config {
  87. game_dir: env_path("VICTORY_GAME_DIR").or(file.game_dir),
  88. cache_dir,
  89. data_dir,
  90. test_titles,
  91. source,
  92. })
  93. }
  94. /// The game directory, or a helpful error if it is not configured.
  95. pub fn require_game_dir(&self) -> Result<&Path> {
  96. self.game_dir.as_deref().context(
  97. "no game directory configured: set VICTORY_GAME_DIR or [paths].game_dir in \
  98. victory.toml (see victory.example.toml)",
  99. )
  100. }
  101. /// Returns `<cache>/<sub>`, creating it, after checking the asset policy.
  102. pub fn cache_subdir(&self, sub: &str) -> Result<PathBuf> {
  103. subdir(&self.cache_dir, sub)
  104. }
  105. /// Returns `<data>/<sub>`, creating it, after checking the asset policy.
  106. pub fn data_subdir(&self, sub: &str) -> Result<PathBuf> {
  107. subdir(&self.data_dir, sub)
  108. }
  109. }
  110. /// The config file explicitly named by the environment, if any. An empty
  111. /// `VICTORY_CONFIG` means unset, like the other path variables.
  112. fn explicit_config_path(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
  113. env("VICTORY_CONFIG")
  114. .filter(|v| !v.is_empty())
  115. .map(PathBuf::from)
  116. }
  117. fn subdir(root: &Path, sub: &str) -> Result<PathBuf> {
  118. let dir = root.join(sub);
  119. ensure_outside_repo(&dir)?;
  120. std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
  121. Ok(dir)
  122. }
  123. /// `%LOCALAPPDATA%/victory/<name>` (elsewhere the XDG or home cache).
  124. fn default_dir(name: &str) -> Result<PathBuf> {
  125. let base = std::env::var_os("LOCALAPPDATA")
  126. .or_else(|| std::env::var_os("XDG_CACHE_HOME"))
  127. .map(PathBuf::from)
  128. .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
  129. .context("cannot determine a user directory; set VICTORY_CACHE_DIR and VICTORY_DATA_DIR")?;
  130. Ok(base.join("victory").join(name))
  131. }
  132. #[cfg(test)]
  133. mod tests {
  134. use super::*;
  135. use std::ffi::OsString;
  136. #[test]
  137. fn environment_overrides_file() {
  138. let file = FilePaths {
  139. game_dir: Some("from-file".into()),
  140. cache_dir: Some("cache-from-file".into()),
  141. ..Default::default()
  142. };
  143. let env = |k: &str| (k == "VICTORY_GAME_DIR").then(|| OsString::from("from-env"));
  144. let cfg = Config::resolve(file, None, env).unwrap();
  145. assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env"));
  146. assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file"));
  147. }
  148. #[test]
  149. fn empty_env_values_are_ignored() {
  150. let file = FilePaths {
  151. game_dir: Some("from-file".into()),
  152. ..Default::default()
  153. };
  154. let env = |k: &str| (k == "VICTORY_GAME_DIR").then(OsString::new);
  155. let cfg = Config::resolve(file, None, env).unwrap();
  156. assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file"));
  157. }
  158. #[test]
  159. fn empty_test_titles_env_is_ignored() {
  160. let file = FilePaths {
  161. test_titles: vec!["from-file".into()],
  162. ..Default::default()
  163. };
  164. let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new);
  165. let cfg = Config::resolve(file, None, env).unwrap();
  166. assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]);
  167. }
  168. #[test]
  169. fn test_titles_env_splits_paths() {
  170. let value = std::env::join_paths(["first", "second"]).unwrap();
  171. let file = FilePaths::default();
  172. let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone());
  173. let cfg = Config::resolve(file, None, env).unwrap();
  174. assert_eq!(
  175. cfg.test_titles,
  176. vec![PathBuf::from("first"), PathBuf::from("second")]
  177. );
  178. }
  179. #[test]
  180. fn empty_config_env_is_ignored() {
  181. let empty = |k: &str| (k == "VICTORY_CONFIG").then(OsString::new);
  182. assert_eq!(explicit_config_path(empty), None);
  183. let set = |k: &str| (k == "VICTORY_CONFIG").then(|| OsString::from("custom.toml"));
  184. assert_eq!(
  185. explicit_config_path(set),
  186. Some(PathBuf::from("custom.toml"))
  187. );
  188. }
  189. #[test]
  190. fn example_config_parses() {
  191. let text = include_str!("../../../victory.example.toml");
  192. let parsed: FileConfig = toml::from_str(text).unwrap();
  193. assert!(parsed.paths.game_dir.is_some());
  194. }
  195. #[test]
  196. fn cache_inside_repo_is_refused() {
  197. let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache");
  198. let cfg = Config {
  199. cache_dir: inside,
  200. ..Default::default()
  201. };
  202. assert!(cfg.cache_subdir("x").is_err());
  203. }
  204. #[test]
  205. fn data_inside_repo_is_refused() {
  206. let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data");
  207. let cfg = Config {
  208. data_dir: inside,
  209. ..Default::default()
  210. };
  211. assert!(cfg.data_subdir("x").is_err());
  212. }
  213. }