1mod clean;
4mod common;
5mod status;
6mod sync;
7
8use anyhow::{Context, Result};
9use clap::{Parser, Subcommand};
10use serde::Serialize;
11
12pub use common::OutputFormat;
13
14pub type SkillsFormat = OutputFormat;
19
20#[derive(Parser)]
22pub struct SkillsCommand {
23 #[command(subcommand)]
25 pub command: SkillsSubcommands,
26}
27
28#[derive(Subcommand)]
30pub enum SkillsSubcommands {
31 Sync(sync::SyncCommand),
33 Clean(clean::CleanCommand),
35 Status(status::StatusCommand),
37}
38
39impl SkillsCommand {
40 pub fn execute(self) -> Result<()> {
42 match self.command {
43 SkillsSubcommands::Sync(cmd) => cmd.execute(),
44 SkillsSubcommands::Clean(cmd) => cmd.execute(),
45 SkillsSubcommands::Status(cmd) => cmd.execute(),
46 }
47 }
48}
49
50pub fn run_sync(
66 base_dir: Option<&std::path::Path>,
67 worktrees: bool,
68 format: OutputFormat,
69) -> Result<String> {
70 let base = resolve_base_dir(base_dir)?;
71 let source_root = common::resolve_toplevel(&base)?;
72 let target_root = source_root.clone();
73
74 let mut targets = vec![target_root.clone()];
75 if worktrees {
76 for wt in common::list_worktrees(&target_root)? {
77 if !targets.iter().any(|t| t == &wt) {
78 targets.push(wt);
79 }
80 }
81 }
82
83 let report = sync::run_sync(&source_root, &targets, false)?;
84 render_sync_report(&report, format)
85}
86
87pub fn run_clean(
91 base_dir: Option<&std::path::Path>,
92 worktrees: bool,
93 format: OutputFormat,
94) -> Result<String> {
95 let base = resolve_base_dir(base_dir)?;
96 let target_root = common::resolve_toplevel(&base)?;
97
98 let mut targets = vec![target_root.clone()];
99 if worktrees {
100 for wt in common::list_worktrees(&target_root)? {
101 if !targets.iter().any(|t| t == &wt) {
102 targets.push(wt);
103 }
104 }
105 }
106
107 let report = clean::run_clean(&targets, false)?;
108 render_clean_report(&report, format)
109}
110
111pub fn run_status(
115 base_dir: Option<&std::path::Path>,
116 worktrees: bool,
117 format: OutputFormat,
118) -> Result<String> {
119 let base = resolve_base_dir(base_dir)?;
120 let target_root = common::resolve_toplevel(&base)?;
121
122 let mut targets = vec![target_root.clone()];
123 if worktrees {
124 for wt in common::list_worktrees(&target_root)? {
125 if !targets.iter().any(|t| t == &wt) {
126 targets.push(wt);
127 }
128 }
129 }
130
131 let report = status::run_status(&targets)?;
132 render_status_report(&report, format)
133}
134
135fn resolve_base_dir(base_dir: Option<&std::path::Path>) -> Result<std::path::PathBuf> {
136 match base_dir {
137 Some(p) => Ok(p.to_path_buf()),
138 None => std::env::current_dir().context("Failed to determine current directory"),
139 }
140}
141
142#[derive(Serialize)]
143struct SyncOutput<'a> {
144 dry_run: bool,
145 actions: &'a [sync::SyncAction],
146 errors: &'a [sync::SyncError],
147}
148
149#[derive(Serialize)]
150struct CleanOutput<'a> {
151 dry_run: bool,
152 actions: &'a [clean::CleanAction],
153}
154
155#[derive(Serialize)]
156struct StatusOutput<'a> {
157 targets: &'a [status::TargetStatus],
158}
159
160fn render_sync_report(report: &sync::SyncReport, format: OutputFormat) -> Result<String> {
161 match format {
162 OutputFormat::Text => Ok(render_sync_text(report)),
163 OutputFormat::Yaml => {
164 let output = SyncOutput {
165 dry_run: false,
166 actions: &report.actions,
167 errors: &report.errors,
168 };
169 serde_yaml::to_string(&output).context("Failed to serialize sync report as YAML")
170 }
171 }
172}
173
174fn render_sync_text(report: &sync::SyncReport) -> String {
175 use std::fmt::Write;
176 let mut out = String::new();
177 for action in &report.actions {
178 match action {
179 sync::SyncAction::Linked { link, points_to } => {
180 let _ = writeln!(out, "linked {} -> {}", link.display(), points_to.display());
181 }
182 sync::SyncAction::Relinked { link, points_to } => {
183 let _ = writeln!(
184 out,
185 "relinked {} -> {}",
186 link.display(),
187 points_to.display()
188 );
189 }
190 sync::SyncAction::Excluded {
191 exclude_file,
192 entry,
193 } => {
194 let _ = writeln!(out, "excluded {} in {}", entry, exclude_file.display());
195 }
196 sync::SyncAction::SkippedSameTarget { target } => {
197 let _ = writeln!(out, "skipped {} (target equals source)", target.display());
198 }
199 }
200 }
201 for err in &report.errors {
202 let _ = writeln!(out, "error: {} -- {}", err.target.display(), err.reason);
203 }
204 out
205}
206
207fn render_clean_report(report: &clean::CleanReport, format: OutputFormat) -> Result<String> {
208 match format {
209 OutputFormat::Text => Ok(render_clean_text(report)),
210 OutputFormat::Yaml => {
211 let output = CleanOutput {
212 dry_run: false,
213 actions: &report.actions,
214 };
215 serde_yaml::to_string(&output).context("Failed to serialize clean report as YAML")
216 }
217 }
218}
219
220fn render_clean_text(report: &clean::CleanReport) -> String {
221 use std::fmt::Write;
222 let mut out = String::new();
223 for action in &report.actions {
224 match action {
225 clean::CleanAction::Unlinked { link } => {
226 let _ = writeln!(out, "unlinked {}", link.display());
227 }
228 clean::CleanAction::Preserved { path, reason } => {
229 let _ = writeln!(out, "preserved {} ({reason})", path.display());
230 }
231 clean::CleanAction::ExcludeRemoved {
232 exclude_file,
233 entry,
234 } => {
235 let _ = writeln!(
236 out,
237 "removed exclude entry {} from {}",
238 entry,
239 exclude_file.display()
240 );
241 }
242 clean::CleanAction::DirectoryRemoved { path } => {
243 let _ = writeln!(out, "removed empty {}", path.display());
244 }
245 }
246 }
247 out
248}
249
250fn render_status_report(report: &status::StatusReport, format: OutputFormat) -> Result<String> {
251 match format {
252 OutputFormat::Text => Ok(render_status_text(report)),
253 OutputFormat::Yaml => {
254 let output = StatusOutput {
255 targets: &report.targets,
256 };
257 serde_yaml::to_string(&output).context("Failed to serialize status report as YAML")
258 }
259 }
260}
261
262fn render_status_text(report: &status::StatusReport) -> String {
263 report
264 .targets
265 .iter()
266 .filter(|t| !(t.symlinks.is_empty() && t.exclude_entries.is_empty()))
267 .map(render_status_target)
268 .collect::<Vec<_>>()
269 .join("\n")
270}
271
272fn render_status_target(target: &status::TargetStatus) -> String {
273 use std::fmt::Write;
274 let mut out = String::new();
275 let _ = writeln!(out, "{}", target.root.display());
276 if !target.symlinks.is_empty() {
277 out.push_str(" symlinks:\n");
278 for link in &target.symlinks {
279 let _ = writeln!(
280 out,
281 " {} -> {}",
282 link.path.display(),
283 link.points_to.display()
284 );
285 }
286 }
287 if !target.exclude_entries.is_empty() {
288 let _ = writeln!(out, " exclude block ({}):", target.exclude_file.display());
289 for entry in &target.exclude_entries {
290 let _ = writeln!(out, " {entry}");
291 }
292 }
293 out
294}
295
296#[cfg(test)]
297#[allow(clippy::unwrap_used, clippy::expect_used)]
298mod skills_api_tests {
299 use super::*;
300
301 use std::fs;
302 use std::path::{Path, PathBuf};
303
304 use tempfile::TempDir;
305
306 use super::common::test_git::{init_repo, init_repo_with_commit, worktree_add};
307
308 fn tempdir() -> TempDir {
309 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
312 fs::create_dir_all(&root).ok();
313 TempDir::new_in(&root).unwrap()
314 }
315
316 fn make_source_skills(root: &Path, names: &[&str]) {
317 let dir = root.join(".claude/skills");
318 fs::create_dir_all(&dir).unwrap();
319 for n in names {
320 let d = dir.join(n);
321 fs::create_dir_all(&d).unwrap();
322 fs::write(d.join("SKILL.md"), format!("# {n}")).unwrap();
323 }
324 }
325
326 #[test]
327 fn run_sync_mcp_with_worktrees_links_skills_and_returns_yaml() {
328 let src = tempdir();
329 let wt_parent = tempdir();
330 let linked = wt_parent.path().join("linked");
331 init_repo_with_commit(src.path());
332 make_source_skills(src.path(), &["alpha"]);
333 worktree_add(src.path(), &linked);
334
335 let out = run_sync(Some(&linked), true, OutputFormat::Yaml).unwrap();
336 assert!(out.contains("dry_run: false"), "missing dry_run: {out}");
337 assert!(out.contains("actions:"), "missing actions: {out}");
338 }
339
340 #[test]
341 fn run_sync_mcp_same_source_target_reports_skipped() {
342 let src = tempdir();
343 init_repo(src.path());
344 make_source_skills(src.path(), &["alpha"]);
345 let out = run_sync(Some(src.path()), false, OutputFormat::Text).unwrap();
346 assert!(out.contains("skipped"), "expected skipped action: {out}");
347 }
348
349 #[test]
350 fn run_clean_mcp_empty_repo_returns_empty_string_text() {
351 let tgt = tempdir();
352 init_repo(tgt.path());
353 let out = run_clean(Some(tgt.path()), false, OutputFormat::Text).unwrap();
354 assert!(out.is_empty(), "expected no actions, got: {out}");
355 }
356
357 #[test]
358 fn run_clean_mcp_yaml_reports_empty_actions() {
359 let tgt = tempdir();
360 init_repo(tgt.path());
361 let out = run_clean(Some(tgt.path()), false, OutputFormat::Yaml).unwrap();
362 assert!(out.contains("dry_run: false"), "missing dry_run: {out}");
363 assert!(out.contains("actions:"), "missing actions: {out}");
364 }
365
366 #[test]
367 fn run_clean_mcp_with_worktrees_covers_all_worktrees() {
368 let main = tempdir();
369 init_repo_with_commit(main.path());
370 let wt_parent = tempdir();
371 let linked = wt_parent.path().join("linked");
372 worktree_add(main.path(), &linked);
373
374 let out = run_clean(Some(main.path()), true, OutputFormat::Yaml).unwrap();
375 assert!(out.contains("actions:"), "missing actions: {out}");
376 }
377
378 #[test]
379 fn run_status_mcp_empty_repo_text_is_empty() {
380 let tgt = tempdir();
381 init_repo(tgt.path());
382 let out = run_status(Some(tgt.path()), false, OutputFormat::Text).unwrap();
383 assert!(out.is_empty(), "expected no residue, got: {out}");
384 }
385
386 #[test]
387 fn run_status_mcp_yaml_emits_targets_array() {
388 let tgt = tempdir();
389 init_repo(tgt.path());
390 let out = run_status(Some(tgt.path()), false, OutputFormat::Yaml).unwrap();
391 assert!(out.contains("targets:"), "missing targets: {out}");
392 }
393
394 #[cfg(unix)]
395 #[test]
396 fn run_status_mcp_reports_symlinks_in_text() {
397 let src = tempdir();
398 let tgt = tempdir();
399 init_repo(tgt.path());
400 let src_skill = src.path().join("alpha");
401 fs::create_dir_all(&src_skill).unwrap();
402 let skills_dir = tgt.path().join(".claude/skills");
403 fs::create_dir_all(&skills_dir).unwrap();
404 std::os::unix::fs::symlink(&src_skill, skills_dir.join("alpha")).unwrap();
405
406 let out = run_status(Some(tgt.path()), false, OutputFormat::Text).unwrap();
407 assert!(out.contains(".claude/skills/alpha"), "got: {out}");
408 }
409
410 #[test]
411 fn run_status_mcp_includes_worktrees_when_requested() {
412 let tgt_main = tempdir();
413 let wt_parent = tempdir();
414 let linked = wt_parent.path().join("linked");
415 init_repo_with_commit(tgt_main.path());
416 worktree_add(tgt_main.path(), &linked);
417
418 let out = run_status(Some(tgt_main.path()), true, OutputFormat::Yaml).unwrap();
419 assert!(out.contains("targets:"), "missing targets: {out}");
420 }
421
422 #[test]
423 fn run_sync_mcp_errors_outside_repo() {
424 let plain = TempDir::new().unwrap();
425 let err = run_sync(Some(plain.path()), false, OutputFormat::Text).unwrap_err();
426 let msg = format!("{err:?}");
427 assert!(
428 msg.contains("git rev-parse --show-toplevel failed")
429 || msg.contains("Failed to run git"),
430 "unexpected error: {msg}"
431 );
432 }
433
434 #[test]
435 fn run_clean_mcp_errors_outside_repo() {
436 let plain = TempDir::new().unwrap();
437 let err = run_clean(Some(plain.path()), false, OutputFormat::Text).unwrap_err();
438 let msg = format!("{err:?}");
439 assert!(msg.contains("git rev-parse"), "unexpected: {msg}");
440 }
441
442 #[test]
443 fn run_status_mcp_errors_outside_repo() {
444 let plain = TempDir::new().unwrap();
445 let err = run_status(Some(plain.path()), false, OutputFormat::Text).unwrap_err();
446 let msg = format!("{err:?}");
447 assert!(msg.contains("git rev-parse"), "unexpected: {msg}");
448 }
449
450 #[test]
451 fn run_status_mcp_defaults_base_dir_to_cwd() {
452 let _ = run_status(None, false, OutputFormat::Text);
455 }
456
457 #[test]
458 fn render_sync_text_covers_all_variants() {
459 let report = sync::SyncReport {
460 actions: vec![
461 sync::SyncAction::Linked {
462 link: PathBuf::from("/a"),
463 points_to: PathBuf::from("/b"),
464 },
465 sync::SyncAction::Relinked {
466 link: PathBuf::from("/c"),
467 points_to: PathBuf::from("/d"),
468 },
469 sync::SyncAction::Excluded {
470 exclude_file: PathBuf::from("/e"),
471 entry: ".claude/skills/x/".into(),
472 },
473 sync::SyncAction::SkippedSameTarget {
474 target: PathBuf::from("/f"),
475 },
476 ],
477 errors: vec![sync::SyncError {
478 target: PathBuf::from("/g"),
479 reason: "blocked".into(),
480 }],
481 };
482 let out = render_sync_text(&report);
483 for s in [
484 "linked /a -> /b",
485 "relinked /c -> /d",
486 "excluded .claude/skills/x/ in /e",
487 "skipped /f",
488 "error: /g",
489 ] {
490 assert!(out.contains(s), "missing {s}: {out}");
491 }
492 }
493
494 #[test]
495 fn render_clean_text_covers_all_variants() {
496 let report = clean::CleanReport {
497 actions: vec![
498 clean::CleanAction::Unlinked {
499 link: PathBuf::from("/a"),
500 },
501 clean::CleanAction::Preserved {
502 path: PathBuf::from("/b"),
503 reason: "real file".into(),
504 },
505 clean::CleanAction::ExcludeRemoved {
506 exclude_file: PathBuf::from("/c"),
507 entry: ".claude/skills/x/".into(),
508 },
509 clean::CleanAction::DirectoryRemoved {
510 path: PathBuf::from("/d"),
511 },
512 ],
513 };
514 let out = render_clean_text(&report);
515 for s in [
516 "unlinked /a",
517 "preserved /b (real file)",
518 "removed exclude entry .claude/skills/x/ from /c",
519 "removed empty /d",
520 ] {
521 assert!(out.contains(s), "missing {s}: {out}");
522 }
523 }
524
525 #[test]
526 fn render_status_text_covers_mixed_targets() {
527 let report = status::StatusReport {
528 targets: vec![
529 status::TargetStatus {
530 root: PathBuf::from("/empty"),
531 symlinks: Vec::new(),
532 exclude_file: PathBuf::from("/empty/.git/info/exclude"),
533 exclude_entries: Vec::new(),
534 },
535 status::TargetStatus {
536 root: PathBuf::from("/first"),
537 symlinks: Vec::new(),
538 exclude_file: PathBuf::from("/first/.git/info/exclude"),
539 exclude_entries: vec![".claude/skills/beta/".into()],
540 },
541 status::TargetStatus {
542 root: PathBuf::from("/both"),
543 symlinks: vec![status::SymlinkInfo {
544 path: PathBuf::from("/both/.claude/skills/alpha"),
545 points_to: PathBuf::from("/src/alpha"),
546 }],
547 exclude_file: PathBuf::from("/both/.git/info/exclude"),
548 exclude_entries: vec![".claude/skills/alpha/".into()],
549 },
550 ],
551 };
552 let out = render_status_text(&report);
553 assert!(out.contains("/first"), "missing /first: {out}");
554 assert!(out.contains("/both"), "missing /both: {out}");
555 assert!(out.contains("symlinks:"), "missing symlinks: {out}");
556 assert!(
557 out.contains("exclude block"),
558 "missing exclude block: {out}"
559 );
560 assert!(
562 out.contains("\n\n"),
563 "missing blank-line separator between targets: {out}"
564 );
565 assert!(
566 !out.contains("/empty\n"),
567 "should skip empty target header: {out}"
568 );
569 }
570
571 #[test]
572 fn render_sync_yaml_contains_dry_run_and_actions_keys() {
573 let report = sync::SyncReport {
574 actions: Vec::new(),
575 errors: Vec::new(),
576 };
577 let out = render_sync_report(&report, OutputFormat::Yaml).unwrap();
578 assert!(out.contains("dry_run: false"));
579 assert!(out.contains("actions:"));
580 assert!(out.contains("errors:"));
581 }
582
583 #[test]
584 fn render_clean_yaml_contains_dry_run_and_actions_keys() {
585 let report = clean::CleanReport {
586 actions: Vec::new(),
587 };
588 let out = render_clean_report(&report, OutputFormat::Yaml).unwrap();
589 assert!(out.contains("dry_run: false"));
590 assert!(out.contains("actions:"));
591 }
592
593 #[test]
594 fn render_status_yaml_contains_targets_key() {
595 let report = status::StatusReport {
596 targets: Vec::new(),
597 };
598 let out = render_status_report(&report, OutputFormat::Yaml).unwrap();
599 assert!(out.contains("targets:"));
600 }
601
602 #[allow(dead_code)]
604 fn _unused(_: PathBuf) {}
605}
606
607#[cfg(test)]
608#[allow(clippy::unwrap_used, clippy::expect_used)]
609mod tests {
610 use super::*;
611
612 use std::fs;
613 use std::path::Path;
614
615 use tempfile::TempDir;
616
617 use super::common::test_git::init_repo;
618 use common::OutputFormat;
619
620 fn tempdir() -> TempDir {
621 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
624 fs::create_dir_all(&root).ok();
625 TempDir::new_in(&root).unwrap()
626 }
627
628 #[test]
629 fn dispatch_sync() {
630 let src = tempdir();
631 let tgt = tempdir();
632 init_repo(src.path());
633 init_repo(tgt.path());
634 let skills_dir = src.path().join(".claude/skills/alpha");
635 fs::create_dir_all(&skills_dir).unwrap();
636 fs::write(skills_dir.join("SKILL.md"), "# alpha").unwrap();
637
638 let cmd = SkillsCommand {
639 command: SkillsSubcommands::Sync(sync::SyncCommand {
640 source: Some(src.path().to_path_buf()),
641 target: Some(tgt.path().to_path_buf()),
642 worktrees: false,
643 dry_run: false,
644 format: OutputFormat::Text,
645 }),
646 };
647 cmd.execute().unwrap();
648 assert!(tgt.path().join(".claude/skills/alpha").exists());
649 }
650
651 #[test]
652 fn dispatch_clean() {
653 let tgt = tempdir();
654 init_repo(tgt.path());
655
656 let cmd = SkillsCommand {
657 command: SkillsSubcommands::Clean(clean::CleanCommand {
658 target: Some(tgt.path().to_path_buf()),
659 worktrees: false,
660 dry_run: false,
661 format: OutputFormat::Text,
662 }),
663 };
664 cmd.execute().unwrap();
665 }
666
667 #[test]
668 fn dispatch_status() {
669 let tgt = tempdir();
670 init_repo(tgt.path());
671
672 let cmd = SkillsCommand {
673 command: SkillsSubcommands::Status(status::StatusCommand {
674 target: Some(tgt.path().to_path_buf()),
675 worktrees: false,
676 format: OutputFormat::Text,
677 }),
678 };
679 cmd.execute().unwrap();
680 }
681}