tracevault_cli/commands/
context.rs1use crate::context::{resolve_context_paths, Context, WorktreeScope};
2use std::io;
3use std::path::{Path, PathBuf};
4
5pub 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
25fn 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
36fn 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
46pub 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 ¶ms {
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 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
91pub 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 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 if let Some(f) = flow {
124 ctx.flow_id = Some(f);
125 }
126
127 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 for raw in ¶ms {
137 let (k, v) = parse_param(raw)?;
138 ctx.params.insert(k, v);
139 }
140
141 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 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
162pub 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 !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 }
200 }
201
202 println!("\n=== Effective ===");
203 println!("{}", serde_json::to_string_pretty(&effective)?);
204
205 Ok(())
206}
207
208pub fn run_clear(cwd: &Path, global: bool) -> Result<(), Box<dyn std::error::Error>> {
221 let paths = resolve_context_paths(cwd);
222
223 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 Context::default()
234 .save_global(&paths)
235 .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
236 } else {
237 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 => {} 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 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}