use std::path::{Path, PathBuf};
pub fn resolve_state_dir(config_path: &Path, state_dir: Option<&str>) -> PathBuf {
let base = config_path.parent().unwrap_or_else(|| Path::new(""));
match state_dir {
Some(s) => {
let p = Path::new(s);
if p.is_absolute() {
p.to_path_buf()
} else {
base.join(p)
}
}
None => base.join("state"),
}
}
pub fn resolve_state_dir_opt(config_path: Option<&str>, state_dir: Option<&str>) -> PathBuf {
match config_path {
Some(cp) => resolve_state_dir(Path::new(cp), state_dir),
None => PathBuf::from(state_dir.unwrap_or("state")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_beside_the_config_not_the_cwd() {
assert_eq!(
resolve_state_dir(Path::new("/tmp/proj/forjar.yaml"), None),
PathBuf::from("/tmp/proj/state"),
"the regression: an absolute config path must not have its state \
looked for in the server's cwd (GH-208)"
);
}
#[test]
fn absolute_override_is_honoured_verbatim() {
assert_eq!(
resolve_state_dir(Path::new("/tmp/proj/forjar.yaml"), Some("/var/lib/st")),
PathBuf::from("/var/lib/st")
);
}
#[test]
fn relative_override_resolves_against_the_config_dir() {
assert_eq!(
resolve_state_dir(Path::new("/tmp/proj/forjar.yaml"), Some("alt-state")),
PathBuf::from("/tmp/proj/alt-state"),
"a relative override names a place inside the project"
);
}
#[test]
fn bare_config_name_keeps_historical_behaviour() {
assert_eq!(
resolve_state_dir(Path::new("forjar.yaml"), None),
PathBuf::from("state")
);
}
#[test]
fn nested_relative_override() {
assert_eq!(
resolve_state_dir(Path::new("/a/b/forjar.yaml"), Some("x/y")),
PathBuf::from("/a/b/x/y")
);
}
}