use anyhow::Context;
use std::path::{Path, PathBuf};
pub fn find_project_root(start: &Path) -> Option<PathBuf> {
let mut dir = start;
loop {
let gobby_dir = dir.join(".gobby");
if gobby_dir.join("project.json").exists() || gobby_dir.join("gcode.json").exists() {
return Some(dir.to_path_buf());
}
match dir.parent() {
Some(parent) => dir = parent,
None => return None,
}
}
}
pub fn read_project_id(project_root: &Path) -> anyhow::Result<String> {
let path = project_root.join(".gobby").join("project.json");
let contents = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read {}", path.display()))?;
let json: serde_json::Value = serde_json::from_str(&contents)?;
json.get("id")
.or_else(|| json.get("project_id"))
.and_then(|v| v.as_str())
.map(String::from)
.context("'id' field not found in .gobby/project.json")
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn read_project_id_is_non_destructive() {
let tmp = tempfile::tempdir().expect("tempdir");
let gobby_dir = tmp.path().join(".gobby");
fs::create_dir(&gobby_dir).expect("create .gobby");
let project_json = gobby_dir.join("project.json");
let contents = r#"{
"id": "project-id",
"name": "example"
}
"#;
fs::write(&project_json, contents).expect("write project json");
let project_id = read_project_id(tmp.path()).expect("read project id");
assert_eq!(project_id, "project-id");
assert_eq!(
fs::read_to_string(&project_json).expect("read project json"),
contents
);
}
}