Skip to main content

gobby_code/
project.rs

1//! Project identity resolution for gcode standalone mode.
2//!
3//! Resolution order: .gobby/project.json (gobby) > .gobby/gcode.json (standalone) > generate on-the-fly.
4//! gcode never writes to project.json — that's gobby's file.
5
6use std::path::{Path, PathBuf};
7
8use anyhow::Context as _;
9use gobby_core::project::read_project_id;
10use uuid::Uuid;
11
12use crate::models::CODE_INDEX_UUID_NAMESPACE;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct IsolationMarker {
16    pub parent_project_path: Option<String>,
17    pub parent_project_id: Option<String>,
18}
19
20/// Read project ID from `.gobby/gcode.json`.
21pub fn read_gcode_json(project_root: &Path) -> anyhow::Result<String> {
22    let path = project_root.join(".gobby").join("gcode.json");
23    let contents = std::fs::read_to_string(&path)
24        .with_context(|| format!("failed to read {}", path.display()))?;
25    let json: serde_json::Value = serde_json::from_str(&contents)?;
26    json.get("id")
27        .and_then(|v| v.as_str())
28        .map(String::from)
29        .context("'id' field not found in .gobby/gcode.json")
30}
31
32/// Generate a deterministic code-index ID from the canonical project root path.
33/// Uses UUID5 with the same namespace as symbol IDs — key format (bare path)
34/// differs from symbol keys so there's no collision risk.
35pub fn code_index_id_for_root(root: &Path) -> String {
36    let canonical = root
37        .canonicalize()
38        .unwrap_or_else(|_| absolute_fallback(root));
39    Uuid::new_v5(
40        &CODE_INDEX_UUID_NAMESPACE,
41        canonical.to_string_lossy().as_bytes(),
42    )
43    .to_string()
44}
45
46/// Backward-compatible name for standalone gcode identity generation.
47pub fn generate_project_id(project_root: &Path) -> String {
48    code_index_id_for_root(project_root)
49}
50
51/// Read the isolated-root marker from `.gobby/project.json`, if present.
52pub fn read_isolation_marker(project_root: &Path) -> Option<IsolationMarker> {
53    let path = project_root.join(".gobby").join("project.json");
54    let contents = std::fs::read_to_string(path).ok()?;
55    let json: serde_json::Value = serde_json::from_str(&contents).ok()?;
56    let parent_project_path = json
57        .get("parent_project_path")
58        .and_then(|v| v.as_str())
59        .filter(|s| !s.is_empty())
60        .map(ToOwned::to_owned);
61    let parent_project_id = json
62        .get("parent_project_id")
63        .and_then(|v| v.as_str())
64        .filter(|s| !s.is_empty())
65        .map(ToOwned::to_owned);
66
67    if parent_project_path.is_some() || parent_project_id.is_some() {
68        Some(IsolationMarker {
69            parent_project_path,
70            parent_project_id,
71        })
72    } else {
73        None
74    }
75}
76
77/// Ensure a gcode identity file exists. Non-destructive:
78/// - If `project.json` exists, reads its ID (gobby owns this project)
79/// - If `gcode.json` exists, reads its ID
80/// - If neither exists, creates `gcode.json`
81///
82/// Returns `(project_id, was_created)`.
83pub fn ensure_gcode_json(project_root: &Path) -> anyhow::Result<(String, bool)> {
84    // Gobby's file takes priority
85    let project_json = project_root.join(".gobby").join("project.json");
86    if project_json.exists() {
87        return Ok((read_project_id(project_root)?, false));
88    }
89
90    // Already initialized by gcode
91    let gcode_json = project_root.join(".gobby").join("gcode.json");
92    if gcode_json.exists() {
93        return Ok((read_gcode_json(project_root)?, false));
94    }
95
96    // Create .gobby/ directory and gcode.json
97    let gobby_dir = project_root.join(".gobby");
98    std::fs::create_dir_all(&gobby_dir)
99        .with_context(|| format!("failed to create {}", gobby_dir.display()))?;
100
101    let project_id = generate_project_id(project_root);
102    let project_name = project_root
103        .file_name()
104        .map(|n| n.to_string_lossy().to_string())
105        .unwrap_or_else(|| "unknown".to_string());
106
107    let created_at = now_iso8601();
108
109    let content = serde_json::json!({
110        "id": project_id,
111        "name": project_name,
112        "created_at": created_at
113    });
114
115    let json_str = serde_json::to_string_pretty(&content)?;
116    std::fs::write(&gcode_json, &json_str)
117        .with_context(|| format!("failed to write {}", gcode_json.display()))?;
118
119    Ok((project_id, true))
120}
121
122/// Check whether any identity file exists for this project root.
123pub fn has_identity_file(project_root: &Path) -> bool {
124    let gobby_dir = project_root.join(".gobby");
125    gobby_dir.join("project.json").exists() || gobby_dir.join("gcode.json").exists()
126}
127
128// ── Internal helpers ────────────────────────────────────────────────
129
130/// Format current UTC time as ISO 8601.
131fn now_iso8601() -> String {
132    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
133}
134
135fn absolute_fallback(path: &Path) -> PathBuf {
136    if path.is_absolute() {
137        path.to_path_buf()
138    } else {
139        std::env::current_dir()
140            .unwrap_or_else(|_| std::env::temp_dir())
141            .join(path)
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn test_generate_project_id_deterministic() {
151        let dir = tempfile::tempdir().unwrap();
152        let id1 = generate_project_id(dir.path());
153        let id2 = generate_project_id(dir.path());
154        assert_eq!(id1, id2);
155        // Should be valid UUID
156        assert!(uuid::Uuid::parse_str(&id1).is_ok());
157    }
158
159    #[test]
160    fn test_generate_project_id_different_paths() {
161        let dir1 = tempfile::tempdir().unwrap();
162        let dir2 = tempfile::tempdir().unwrap();
163        let id1 = generate_project_id(dir1.path());
164        let id2 = generate_project_id(dir2.path());
165        assert_ne!(id1, id2);
166    }
167
168    #[test]
169    fn test_read_isolation_marker_detects_parent_fields() {
170        let dir = tempfile::tempdir().unwrap();
171        let gobby_dir = dir.path().join(".gobby");
172        std::fs::create_dir_all(&gobby_dir).unwrap();
173        std::fs::write(
174            gobby_dir.join("project.json"),
175            serde_json::json!({
176                "id": "copied-parent-id",
177                "parent_project_path": "/parent/root",
178                "parent_project_id": "parent-id"
179            })
180            .to_string(),
181        )
182        .unwrap();
183
184        let marker = read_isolation_marker(dir.path()).expect("isolation marker");
185
186        assert_eq!(marker.parent_project_path.as_deref(), Some("/parent/root"));
187        assert_eq!(marker.parent_project_id.as_deref(), Some("parent-id"));
188    }
189
190    #[test]
191    fn test_ensure_gcode_json_creates_new() {
192        let dir = tempfile::tempdir().unwrap();
193        let (id, created) = ensure_gcode_json(dir.path()).unwrap();
194        assert!(created);
195        assert!(uuid::Uuid::parse_str(&id).is_ok());
196
197        // Verify file exists with correct content
198        let path = dir.path().join(".gobby").join("gcode.json");
199        assert!(path.exists());
200        let contents: serde_json::Value =
201            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
202        assert_eq!(contents["id"].as_str().unwrap(), id);
203
204        // ID should match deterministic generation
205        assert_eq!(id, generate_project_id(dir.path()));
206    }
207
208    #[test]
209    fn test_ensure_gcode_json_skips_when_project_json_exists() {
210        let dir = tempfile::tempdir().unwrap();
211        let gobby_dir = dir.path().join(".gobby");
212        std::fs::create_dir_all(&gobby_dir).unwrap();
213
214        // Write a gobby project.json
215        let project_json = serde_json::json!({
216            "id": "gobby-owned-id-123",
217            "name": "test-project"
218        });
219        std::fs::write(
220            gobby_dir.join("project.json"),
221            serde_json::to_string_pretty(&project_json).unwrap(),
222        )
223        .unwrap();
224
225        let (id, created) = ensure_gcode_json(dir.path()).unwrap();
226        assert!(!created);
227        assert_eq!(id, "gobby-owned-id-123");
228
229        // gcode.json should NOT exist
230        assert!(!gobby_dir.join("gcode.json").exists());
231    }
232
233    #[test]
234    fn test_ensure_gcode_json_reads_existing() {
235        let dir = tempfile::tempdir().unwrap();
236
237        // Create gcode.json first
238        let (id1, created1) = ensure_gcode_json(dir.path()).unwrap();
239        assert!(created1);
240
241        // Second call should read, not overwrite
242        let original_bytes = std::fs::read(dir.path().join(".gobby").join("gcode.json")).unwrap();
243        let (id2, created2) = ensure_gcode_json(dir.path()).unwrap();
244        assert!(!created2);
245        assert_eq!(id1, id2);
246
247        // File should be byte-identical
248        let after_bytes = std::fs::read(dir.path().join(".gobby").join("gcode.json")).unwrap();
249        assert_eq!(original_bytes, after_bytes);
250    }
251
252    #[test]
253    fn test_now_iso8601_format() {
254        let ts = now_iso8601();
255        // Should match YYYY-MM-DDTHH:MM:SS.ffffffZ
256        assert!(ts.len() >= 27, "timestamp too short: {ts}");
257        assert!(ts.ends_with('Z'));
258        assert!(ts.contains('T'));
259    }
260
261    #[test]
262    fn test_has_identity_file() {
263        let dir = tempfile::tempdir().unwrap();
264        assert!(!has_identity_file(dir.path()));
265
266        let gobby_dir = dir.path().join(".gobby");
267        std::fs::create_dir_all(&gobby_dir).unwrap();
268        std::fs::write(gobby_dir.join("gcode.json"), "{}").unwrap();
269        assert!(has_identity_file(dir.path()));
270    }
271}