1use crate::config::{TracevaultConfig, UserContext};
2use crate::context::{resolve_context_paths, Context, WorktreeScope};
3use std::io;
4use std::path::{Path, PathBuf};
5
6pub fn find_project_root(start: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
13 for ancestor in start.ancestors() {
14 if ancestor.join(".tracevault").is_dir() {
15 return Ok(ancestor.to_path_buf());
16 }
17 }
18 Err(format!(
19 "No .tracevault/ directory found in '{}' or any parent directory. \
20 Run `tracevault init` first.",
21 start.display()
22 )
23 .into())
24}
25
26fn parse_param(raw: &str) -> Result<(String, String), Box<dyn std::error::Error>> {
29 let pos = raw
30 .find('=')
31 .ok_or_else(|| format!("invalid --param '{raw}': expected key=value"))?;
32 let key = raw[..pos].to_string();
33 let value = raw[pos + 1..].to_string();
34 Ok((key, value))
35}
36
37fn split_labels(labels: &[String]) -> Vec<String> {
39 labels
40 .iter()
41 .flat_map(|l| l.split(','))
42 .map(|s| s.trim().to_string())
43 .filter(|s| !s.is_empty())
44 .collect()
45}
46
47fn user_context_path(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
52 let root = find_project_root(cwd)?;
53 let config = TracevaultConfig::try_load(&root)
58 .map_err(|e| format!("cannot resolve --user path: malformed .tracevault/config.toml: {e}"))?
59 .unwrap_or_default();
60 Ok(config.user_context.path())
61}
62
63pub fn run_set(
73 cwd: &Path,
74 flow: Option<String>,
75 labels: Vec<String>,
76 params: Vec<String>,
77 global: bool,
78 user: bool,
79) -> Result<(), Box<dyn std::error::Error>> {
80 let mut parsed_params = std::collections::BTreeMap::new();
81 for raw in ¶ms {
82 let (k, v) = parse_param(raw)?;
83 parsed_params.insert(k, Some(v));
84 }
85
86 let ctx = Context {
87 flow_id: flow,
88 labels: split_labels(&labels),
89 params: parsed_params,
90 };
91
92 if user {
93 let path = user_context_path(cwd)?;
94 ctx.save_to(&path)
95 .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
96 println!("Context set.");
97 return Ok(());
98 }
99
100 let paths = resolve_context_paths(cwd);
101
102 if !paths.tracevault_dir.exists() {
104 return Err("no .tracevault/ found — run 'tracevault init' first".into());
105 }
106
107 if global || matches!(paths.scope, WorktreeScope::Primary) {
108 ctx.save_global(&paths)
109 } else {
110 ctx.save_worktree(&paths)
111 }
112 .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
113
114 println!("Context set.");
115 Ok(())
116}
117
118#[allow(clippy::too_many_arguments)]
127pub fn run_update(
128 cwd: &Path,
129 flow: Option<String>,
130 labels: Vec<String>,
131 params: Vec<String>,
132 remove_labels: Vec<String>,
133 remove_params: Vec<String>,
134 global: bool,
135 user: bool,
136) -> Result<(), Box<dyn std::error::Error>> {
137 if user {
138 let path = user_context_path(cwd)?;
139 let mut ctx = Context::load_from(&path);
140 apply_update_mutations(
141 &mut ctx,
142 flow,
143 &labels,
144 ¶ms,
145 &remove_labels,
146 &remove_params,
147 )?;
148 ctx.save_to(&path)
149 .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
150 println!("Context updated.");
151 return Ok(());
152 }
153
154 let paths = resolve_context_paths(cwd);
155
156 if !paths.tracevault_dir.exists() {
158 return Err("no .tracevault/ found — run 'tracevault init' first".into());
159 }
160
161 let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
162
163 let mut ctx = if use_global {
164 Context::load_global(&paths)
165 } else {
166 Context::load_worktree(&paths).unwrap_or_default()
167 };
168
169 apply_update_mutations(
170 &mut ctx,
171 flow,
172 &labels,
173 ¶ms,
174 &remove_labels,
175 &remove_params,
176 )?;
177
178 if use_global {
179 ctx.save_global(&paths)
180 } else {
181 ctx.save_worktree(&paths)
182 }
183 .map_err(|e: io::Error| format!("failed to save context: {e}"))?;
184
185 println!("Context updated.");
186 Ok(())
187}
188
189fn apply_update_mutations(
193 ctx: &mut Context,
194 flow: Option<String>,
195 labels: &[String],
196 params: &[String],
197 remove_labels: &[String],
198 remove_params: &[String],
199) -> Result<(), Box<dyn std::error::Error>> {
200 if let Some(f) = flow {
202 ctx.flow_id = Some(f);
203 }
204
205 let new_labels = split_labels(labels);
207 for l in new_labels {
208 if !ctx.labels.contains(&l) {
209 ctx.labels.push(l);
210 }
211 }
212
213 for raw in params {
215 let (k, v) = parse_param(raw)?;
216 ctx.params.insert(k, Some(v));
217 }
218
219 let remove_set: std::collections::HashSet<String> =
221 split_labels(remove_labels).into_iter().collect();
222 ctx.labels.retain(|l| !remove_set.contains(l));
223
224 for k in remove_params {
227 ctx.params.insert(k.clone(), None);
228 }
229
230 Ok(())
231}
232
233pub fn run_show(cwd: &Path) -> Result<(), Box<dyn std::error::Error>> {
245 let config = find_project_root(cwd)
249 .ok()
250 .and_then(|root| TracevaultConfig::load(&root))
251 .unwrap_or_default();
252 let user_path = config.user_context.resolve();
253 let user_enabled = user_path.is_some();
254
255 let (paths, user, global, worktree, effective) =
256 Context::effective_with_parts(cwd, user_path.as_deref());
257
258 if !paths.tracevault_dir.exists() && find_project_root(cwd).is_err() {
262 eprintln!("hint: No .tracevault/ directory found. Run `tracevault init` first.");
263 }
264
265 let is_linked = matches!(paths.scope, WorktreeScope::Linked { .. });
266
267 print!(
268 "{}",
269 show_report(
270 user.as_ref(),
271 user_enabled,
272 user_path.as_deref(),
273 &global,
274 worktree.as_ref(),
275 is_linked,
276 &effective,
277 )
278 );
279
280 Ok(())
281}
282
283const LAYER_USER: &str = "user";
285const LAYER_REPO: &str = "repo";
286const LAYER_WORKTREE: &str = "worktree";
287
288fn param_source(
294 user: Option<&Context>,
295 global: &Context,
296 worktree: Option<&Context>,
297 key: &str,
298) -> &'static str {
299 if let Some(w) = worktree {
300 if matches!(w.params.get(key), Some(Some(_))) {
301 return LAYER_WORKTREE;
302 }
303 }
304 if matches!(global.params.get(key), Some(Some(_))) {
305 return LAYER_REPO;
306 }
307 if let Some(u) = user {
308 if matches!(u.params.get(key), Some(Some(_))) {
309 return LAYER_USER;
310 }
311 }
312 "?"
313}
314
315fn label_source(
319 user: Option<&Context>,
320 global: &Context,
321 worktree: Option<&Context>,
322 label: &str,
323) -> &'static str {
324 if let Some(u) = user {
325 if u.labels.iter().any(|l| l == label) {
326 return LAYER_USER;
327 }
328 }
329 if global.labels.iter().any(|l| l == label) {
330 return LAYER_REPO;
331 }
332 if let Some(w) = worktree {
333 if w.labels.iter().any(|l| l == label) {
334 return LAYER_WORKTREE;
335 }
336 }
337 "?"
338}
339
340fn flow_source(
343 user: Option<&Context>,
344 global: &Context,
345 worktree: Option<&Context>,
346) -> &'static str {
347 if let Some(w) = worktree {
348 if w.flow_id.is_some() {
349 return LAYER_WORKTREE;
350 }
351 }
352 if global.flow_id.is_some() {
353 return LAYER_REPO;
354 }
355 if let Some(u) = user {
356 if u.flow_id.is_some() {
357 return LAYER_USER;
358 }
359 }
360 "?"
361}
362
363#[allow(clippy::too_many_arguments)]
373fn show_report(
374 user: Option<&Context>,
375 user_enabled: bool,
376 user_path: Option<&Path>,
377 global: &Context,
378 worktree: Option<&Context>,
379 is_linked: bool,
380 eff: &crate::context::EffectiveContext,
381) -> String {
382 use std::fmt::Write;
383 let mut out = String::new();
384
385 let file_desc = match user_path {
386 Some(p) if user_enabled => p.display().to_string(),
387 _ => "disabled".to_string(),
388 };
389 let _ = writeln!(
390 out,
391 "=== User (enabled: {user_enabled}, file: {file_desc}) ==="
392 );
393 match user {
394 Some(u) => {
395 let _ = writeln!(
396 out,
397 "{}",
398 serde_json::to_string_pretty(u).unwrap_or_default()
399 );
400 }
401 None => {
402 let _ = writeln!(out, "(none)");
403 }
404 }
405
406 let _ = writeln!(out, "\n=== Global ===");
407 let _ = writeln!(
408 out,
409 "{}",
410 serde_json::to_string_pretty(global).unwrap_or_default()
411 );
412
413 if is_linked {
414 let _ = writeln!(out, "\n=== This worktree ===");
415 match worktree {
416 Some(wt) => {
417 let _ = writeln!(
418 out,
419 "{}",
420 serde_json::to_string_pretty(wt).unwrap_or_default()
421 );
422 }
423 None => {
424 let _ = writeln!(out, "(none)");
425 }
426 }
427 }
428
429 let _ = writeln!(out, "\n=== Effective ===");
430 match &eff.flow_id {
431 Some(f) => {
432 let source = flow_source(user, global, worktree);
433 let _ = writeln!(out, "flow_id = {f} [from {source}]");
434 }
435 None => {
436 let _ = writeln!(out, "flow_id = (none)");
437 }
438 }
439
440 let _ = writeln!(out, "labels:");
441 if eff.labels.is_empty() {
442 let _ = writeln!(out, " (none)");
443 } else {
444 for label in &eff.labels {
445 let source = label_source(user, global, worktree, label);
446 let _ = writeln!(out, " {label} [from {source}]");
447 }
448 }
449
450 let _ = writeln!(out, "params:");
451 if eff.params.is_empty() {
452 let _ = writeln!(out, " (none)");
453 } else {
454 for (k, v) in &eff.params {
455 let source = param_source(user, global, worktree, k);
456 let _ = writeln!(out, " {k} = {v} [from {source}]");
457 }
458 }
459
460 out
461}
462
463pub fn run_clear(cwd: &Path, global: bool, user: bool) -> Result<(), Box<dyn std::error::Error>> {
479 if user {
480 let path = user_context_path(cwd)?;
481 Context::default()
482 .save_to(&path)
483 .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
484 println!("Context cleared.");
485 return Ok(());
486 }
487
488 let paths = resolve_context_paths(cwd);
489
490 if !paths.tracevault_dir.exists() {
492 return Err("no .tracevault/ found — run 'tracevault init' first".into());
493 }
494
495 let use_global = global || matches!(paths.scope, WorktreeScope::Primary);
496
497 if use_global {
498 Context::default()
501 .save_global(&paths)
502 .map_err(|e: io::Error| format!("failed to clear context: {e}"))?;
503 } else {
504 if let Some(wt_path) = paths.worktree_path() {
508 match std::fs::remove_file(&wt_path) {
509 Ok(()) => {}
510 Err(e) if e.kind() == io::ErrorKind::NotFound => {} Err(e) => return Err(format!("failed to clear context: {e}").into()),
512 }
513 }
514 }
515
516 println!("Context cleared.");
517 Ok(())
518}
519
520pub fn run_source(
529 cwd: &Path,
530 enable: bool,
531 disable: bool,
532 path: Option<String>,
533 default: bool,
534) -> Result<(), Box<dyn std::error::Error>> {
535 let root = find_project_root(cwd)?;
536 let mut config = match TracevaultConfig::try_load(&root) {
540 Ok(Some(cfg)) => cfg,
541 Ok(None) => {
542 return Err("no .tracevault/config.toml found — run 'tracevault init' first".into())
543 }
544 Err(e) => return Err(format!("malformed .tracevault/config.toml: {e}").into()),
545 };
546
547 config.user_context = if disable {
548 UserContext::Toggle(false)
549 } else if let Some(p) = path {
550 UserContext::Path(p)
551 } else if default || enable {
552 UserContext::Toggle(true)
553 } else {
554 return Err("specify one of --enable, --disable, --path <file>, --default".into());
555 };
556
557 std::fs::write(TracevaultConfig::config_path(&root), config.to_toml())?;
558 println!("Updated user_context.");
559 Ok(())
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565 use std::collections::BTreeMap;
566 use std::fs;
567
568 #[test]
569 fn show_report_includes_user_section_and_repo_provenance() {
570 let user = Context {
571 flow_id: None,
572 labels: vec![],
573 params: BTreeMap::from([("owner".to_string(), Some("alice".to_string()))]),
574 };
575 let global = Context {
576 flow_id: None,
577 labels: vec![],
578 params: BTreeMap::from([("owner".to_string(), Some("bob".to_string()))]),
579 };
580 let eff = Context::merge_layers(&[&user, &global]);
581
582 let report = show_report(
583 Some(&user),
584 true,
585 Some(Path::new("/tmp/user.json")),
586 &global,
587 None,
588 false,
589 &eff,
590 );
591
592 assert!(
593 report.contains("=== User"),
594 "missing User section: {report}"
595 );
596 assert!(
597 report.contains("owner = bob [from repo]"),
598 "missing repo provenance for overridden param: {report}"
599 );
600 }
601
602 fn temp_project() -> tempfile::TempDir {
604 let dir = tempfile::tempdir().unwrap();
605 let tv_dir = dir.path().join(".tracevault");
606 fs::create_dir_all(&tv_dir).unwrap();
607 fs::write(
608 tv_dir.join("config.toml"),
609 TracevaultConfig::default().to_toml(),
610 )
611 .unwrap();
612 dir
613 }
614
615 #[test]
616 fn source_enable_disable_and_path() {
617 let dir = temp_project();
618
619 run_source(dir.path(), true, false, None, false).unwrap();
620 let cfg = TracevaultConfig::load(dir.path()).unwrap();
621 assert!(cfg.user_context.resolve().is_some());
622
623 run_source(dir.path(), false, true, None, false).unwrap();
624 let cfg = TracevaultConfig::load(dir.path()).unwrap();
625 assert!(cfg.user_context.resolve().is_none());
626
627 run_source(dir.path(), false, false, Some("/p".to_string()), false).unwrap();
628 let cfg = TracevaultConfig::load(dir.path()).unwrap();
629 assert_eq!(
630 cfg.user_context.resolve(),
631 Some(std::path::PathBuf::from("/p"))
632 );
633 }
634
635 #[test]
636 fn source_default_flag_enables() {
637 let dir = temp_project();
638 run_source(dir.path(), false, false, None, true).unwrap();
639 let cfg = TracevaultConfig::load(dir.path()).unwrap();
640 assert!(cfg.user_context.resolve().is_some());
641 }
642
643 #[test]
644 fn source_no_flags_errors() {
645 let dir = temp_project();
646 let err = run_source(dir.path(), false, false, None, false).unwrap_err();
647 assert!(err.to_string().contains("--enable"));
648 }
649
650 #[test]
651 fn parse_param_valid() {
652 assert_eq!(
653 parse_param("key=value").unwrap(),
654 ("key".to_string(), "value".to_string())
655 );
656 }
657
658 #[test]
659 fn parse_param_value_contains_equals() {
660 assert_eq!(
662 parse_param("key=a=b").unwrap(),
663 ("key".to_string(), "a=b".to_string())
664 );
665 }
666
667 #[test]
668 fn parse_param_no_equals_errors() {
669 let err = parse_param("noequals").unwrap_err();
670 assert!(err.to_string().contains("expected key=value"));
671 assert!(err.to_string().contains("noequals"));
672 }
673
674 #[test]
675 fn split_labels_comma_separated() {
676 let result = split_labels(&["a,b,c".to_string(), "d".to_string()]);
677 assert_eq!(result, vec!["a", "b", "c", "d"]);
678 }
679
680 fn temp_project_with_user_context(uc_path: &Path) -> tempfile::TempDir {
683 let dir = tempfile::tempdir().unwrap();
684 let tv_dir = dir.path().join(".tracevault");
685 fs::create_dir_all(&tv_dir).unwrap();
686 let config = TracevaultConfig {
687 user_context: UserContext::Path(uc_path.display().to_string()),
688 ..TracevaultConfig::default()
689 };
690 fs::write(tv_dir.join("config.toml"), config.to_toml()).unwrap();
691 dir
692 }
693
694 #[test]
695 fn set_user_writes_resolved_user_context_file() {
696 let uc_dir = tempfile::tempdir().unwrap();
697 let uc_path = uc_dir.path().join("uc.json");
698 let project = temp_project_with_user_context(&uc_path);
699
700 run_set(
701 project.path(),
702 None,
703 vec!["team".to_string()],
704 vec!["env=prod".to_string()],
705 false,
706 true,
707 )
708 .unwrap();
709
710 let ctx = Context::load_from(&uc_path);
711 assert_eq!(ctx.labels, vec!["team".to_string()]);
712 assert_eq!(ctx.params.get("env"), Some(&Some("prod".to_string())));
713 }
714
715 #[test]
716 fn update_user_merges_into_resolved_user_context_file() {
717 let uc_dir = tempfile::tempdir().unwrap();
718 let uc_path = uc_dir.path().join("uc.json");
719 let project = temp_project_with_user_context(&uc_path);
720
721 run_set(
722 project.path(),
723 None,
724 vec!["team".to_string()],
725 vec!["env=prod".to_string()],
726 false,
727 true,
728 )
729 .unwrap();
730
731 run_update(
732 project.path(),
733 None,
734 vec!["extra".to_string()],
735 vec![],
736 vec![],
737 vec!["env".to_string()],
738 false,
739 true,
740 )
741 .unwrap();
742
743 let ctx = Context::load_from(&uc_path);
744 assert_eq!(ctx.labels, vec!["team".to_string(), "extra".to_string()]);
745 assert_eq!(ctx.params.get("env"), Some(&None));
746 }
747
748 #[test]
749 fn clear_user_resets_resolved_user_context_file() {
750 let uc_dir = tempfile::tempdir().unwrap();
751 let uc_path = uc_dir.path().join("uc.json");
752 let project = temp_project_with_user_context(&uc_path);
753
754 run_set(
755 project.path(),
756 None,
757 vec!["team".to_string()],
758 vec![],
759 false,
760 true,
761 )
762 .unwrap();
763
764 run_clear(project.path(), false, true).unwrap();
765
766 let ctx = Context::load_from(&uc_path);
767 assert_eq!(ctx, Context::default());
768 }
769}