Skip to main content

tracevault_cli/commands/
context.rs

1use crate::context::{resolve_context_paths, Context, WorktreeScope};
2use std::io;
3use std::path::{Path, PathBuf};
4
5/// Walk up from `start` to find the nearest ancestor that contains a
6/// `.tracevault/` directory. Returns that ancestor. Errors if none found.
7///
8/// Kept as a public utility for integration tests and callers that need the
9/// classic "must have .tracevault/" guarantee (e.g. legacy hooks, tests).
10/// Worktree-aware commands use `resolve_context_paths` directly instead.
11pub fn find_project_root(start: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
12    for ancestor in start.ancestors() {
13        if ancestor.join(".tracevault").is_dir() {
14            return Ok(ancestor.to_path_buf());
15        }
16    }
17    Err(format!(
18        "No .tracevault/ directory found in '{}' or any parent directory. \
19         Run `tracevault init` first.",
20        start.display()
21    )
22    .into())
23}
24
25/// Parse a `--param` value of the form `key=value`.
26/// Rejects values with no `=`.
27fn parse_param(raw: &str) -> Result<(String, String), Box<dyn std::error::Error>> {
28    let pos = raw
29        .find('=')
30        .ok_or_else(|| format!("invalid --param '{raw}': expected key=value"))?;
31    let key = raw[..pos].to_string();
32    let value = raw[pos + 1..].to_string();
33    Ok((key, value))
34}
35
36/// Split a label argument on commas, trimming whitespace.
37fn split_labels(labels: &[String]) -> Vec<String> {
38    labels
39        .iter()
40        .flat_map(|l| l.split(','))
41        .map(|s| s.trim().to_string())
42        .filter(|s| !s.is_empty())
43        .collect()
44}
45
46/// `tracevault context set` — build a fresh Context from flags, save it.
47/// Omitted dimensions are empty. Clears anything not explicitly provided.
48///
49/// Default scope:
50/// - Linked worktree → writes `worktrees/<key>/context.json`.
51/// - Primary checkout → writes the global `context.json`.
52///
53/// `global = true` forces the global file from any worktree.
54pub fn run_set(
55    cwd: &Path,
56    flow: Option<String>,
57    labels: Vec<String>,
58    params: Vec<String>,
59    global: bool,
60) -> Result<(), Box<dyn std::error::Error>> {
61    let mut parsed_params = std::collections::BTreeMap::new();
62    for raw in &params {
63        let (k, v) = parse_param(raw)?;
64        parsed_params.insert(k, v);
65    }
66
67    let ctx = Context {
68        flow_id: flow,
69        labels: split_labels(&labels),
70        params: parsed_params,
71    };
72
73    let paths = resolve_context_paths(cwd);
74
75    // Require an initialised .tracevault/ before mutating.
76    if !paths.tracevault_dir.exists() {
77        return Err("no .tracevault/ found — run 'tracevault init' first".into());
78    }
79
80    if global || matches!(paths.scope, WorktreeScope::Primary) {
81        ctx.save_global(&paths)
82    } else {
83        ctx.save_worktree(&paths)
84    }
85    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
86
87    println!("Context set.");
88    Ok(())
89}
90
91/// `tracevault context update` — load existing, apply mutations, save.
92///
93/// Default scope:
94/// - Linked worktree → reads/writes `worktrees/<key>/context.json`.
95/// - Primary checkout → reads/writes the global `context.json`.
96///
97/// `global = true` forces the global file from any worktree.
98pub fn run_update(
99    cwd: &Path,
100    flow: Option<String>,
101    labels: Vec<String>,
102    params: Vec<String>,
103    remove_labels: Vec<String>,
104    remove_params: Vec<String>,
105    global: bool,
106) -> Result<(), Box<dyn std::error::Error>> {
107    let paths = resolve_context_paths(cwd);
108
109    // Require an initialised .tracevault/ before mutating.
110    if !paths.tracevault_dir.exists() {
111        return Err("no .tracevault/ found — run 'tracevault init' first".into());
112    }
113
114    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
115
116    let mut ctx = if use_global {
117        Context::load_global(&paths)
118    } else {
119        Context::load_worktree(&paths).unwrap_or_default()
120    };
121
122    // Set flow if provided
123    if let Some(f) = flow {
124        ctx.flow_id = Some(f);
125    }
126
127    // Union-add labels (dedup guarded inline by the contains check below; save also normalises)
128    let new_labels = split_labels(&labels);
129    for l in new_labels {
130        if !ctx.labels.contains(&l) {
131            ctx.labels.push(l);
132        }
133    }
134
135    // Insert/overwrite params
136    for raw in &params {
137        let (k, v) = parse_param(raw)?;
138        ctx.params.insert(k, v);
139    }
140
141    // Remove labels
142    let remove_set: std::collections::HashSet<String> =
143        split_labels(&remove_labels).into_iter().collect();
144    ctx.labels.retain(|l| !remove_set.contains(l));
145
146    // Remove params
147    for k in &remove_params {
148        ctx.params.remove(k);
149    }
150
151    if use_global {
152        ctx.save_global(&paths)
153    } else {
154        ctx.save_worktree(&paths)
155    }
156    .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
157
158    println!("Context updated.");
159    Ok(())
160}
161
162/// `tracevault context show` — print three labelled sections:
163///   1. Global — the repo-wide `context.json`.
164///   2. This worktree — the per-worktree context (Linked only; "(none)" when missing).
165///   3. Effective — the merged result that the hook stamps on every event.
166///
167/// Also prints the resolved file paths.
168///
169/// Prints a hint if no `.tracevault/` directory is found (i.e. `tracevault init` has
170/// not been run), using `find_project_root` for the diagnostic.
171pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
172    let (paths, global, worktree, effective) = Context::effective_with_parts(cwd);
173
174    // If the tracevault directory doesn't exist yet, hint that init is needed.
175    // find_project_root gives the classic walk-up path; if it also fails, the
176    // user has not run `tracevault init` yet.
177    if !paths.tracevault_dir.exists() && find_project_root(cwd).is_err() {
178        eprintln!("hint: No .tracevault/ directory found. Run `tracevault init` first.");
179    }
180
181    println!("=== Global ===");
182    println!("File: {}", paths.global_path().display());
183    println!("{}", serde_json::to_string_pretty(&global)?);
184
185    match &paths.scope {
186        WorktreeScope::Linked { key } => {
187            let wt_path = paths
188                .worktree_path()
189                .expect("Linked scope always has a worktree_path");
190            println!("\n=== This worktree ({key}) ===");
191            println!("File: {}", wt_path.display());
192            match &worktree {
193                Some(wt) => println!("{}", serde_json::to_string_pretty(wt)?),
194                None => println!("(none)"),
195            }
196        }
197        WorktreeScope::Primary => {
198            // No separate per-worktree section for the primary checkout.
199        }
200    }
201
202    println!("\n=== Effective ===");
203    println!("{}", serde_json::to_string_pretty(&effective)?);
204
205    Ok(())
206}
207
208/// `tracevault context clear` — remove/reset the context for the chosen scope.
209///
210/// Default scope:
211/// - Linked worktree → DELETE `worktrees/<key>/context.json` if it exists.
212///   A missing file means "no per-worktree context" (`load_worktree` returns
213///   `None`, `show` prints "(none)"), so deleting preserves the absent-vs-empty
214///   distinction that the rest of the design relies on.
215/// - Primary checkout → write an empty (default) `context.json`.
216///   The global file is the canonical one; there is no absent-vs-empty
217///   distinction to preserve, and `show`/`effective` always read it.
218///
219/// `global = true` forces clearing the global file from any worktree.
220pub fn run_clear(cwd: &Path, global: bool) -> Result<(), Box<dyn std::error::Error>> {
221    let paths = resolve_context_paths(cwd);
222
223    // Require an initialised .tracevault/ before mutating.
224    if !paths.tracevault_dir.exists() {
225        return Err("no .tracevault/ found — run 'tracevault init' first".into());
226    }
227
228    let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
229
230    if use_global {
231        // Global scope: overwrite with an empty context so `show`/`effective`
232        // continue to find a well-formed file.
233        Context::default()
234            .save_global(&paths)
235            .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
236    } else {
237        // Per-worktree scope: delete the file so that `load_worktree` returns
238        // `None` and `show` prints "(none)" — preserving the absent-vs-empty
239        // distinction.
240        if let Some(wt_path) = paths.worktree_path() {
241            match std::fs::remove_file(&wt_path) {
242                Ok(()) => {}
243                Err(e) if e.kind() == io::ErrorKind::NotFound => {} // already absent — fine
244                Err(e) => return Err(format!("failed to clear context: {e}").into()),
245            }
246        }
247    }
248
249    println!("Context cleared.");
250    Ok(())
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn parse_param_valid() {
259        assert_eq!(
260            parse_param("key=value").unwrap(),
261            ("key".to_string(), "value".to_string())
262        );
263    }
264
265    #[test]
266    fn parse_param_value_contains_equals() {
267        // Only split on the FIRST =
268        assert_eq!(
269            parse_param("key=a=b").unwrap(),
270            ("key".to_string(), "a=b".to_string())
271        );
272    }
273
274    #[test]
275    fn parse_param_no_equals_errors() {
276        let err = parse_param("noequals").unwrap_err();
277        assert!(err.to_string().contains("expected key=value"));
278        assert!(err.to_string().contains("noequals"));
279    }
280
281    #[test]
282    fn split_labels_comma_separated() {
283        let result = split_labels(&["a,b,c".to_string(), "d".to_string()]);
284        assert_eq!(result, vec!["a", "b", "c", "d"]);
285    }
286}