1use std::{
2 path::{Path, PathBuf},
3 process::Command,
4};
5
6use tempfile::TempDir;
7use url::Url;
8
9use crate::error::{Result, TuffError};
10use crate::manifest::CapabilityType;
11
12pub fn is_git_url(s: &str) -> bool {
13 s.starts_with("http://")
14 || s.starts_with("https://")
15 || s.starts_with("git@")
16 || s.starts_with("file://")
17}
18
19fn clean_git_url(raw: &str) -> (String, Option<String>) {
20 let parsed = match Url::parse(raw) {
21 Ok(u) => u,
22 Err(_) => return (raw.to_string(), None),
23 };
24
25 let host = parsed.host_str().unwrap_or("");
26 let path = parsed.path();
27 let segments: Vec<&str> = path.trim_start_matches('/').split('/').collect();
28
29 if (host == "github.com" || host.ends_with(".github.com"))
30 && segments.len() >= 4
31 && (segments[2] == "tree" || segments[2] == "blob")
32 {
33 let clean = format!("https://{}/{}/{}", host, segments[0], segments[1]);
34 return (clean, Some(segments[3].to_string()));
35 }
36
37 if (host == "github.com" || host.ends_with(".github.com")) && segments.len() > 2 {
38 return (
39 format!("https://{}/{}/{}", host, segments[0], segments[1]),
40 None,
41 );
42 }
43
44 if (host == "gitlab.com" || host.ends_with(".gitlab.com"))
45 && segments.len() >= 5
46 && segments[2] == "-"
47 && (segments[3] == "tree" || segments[3] == "blob")
48 {
49 let clean = format!("https://{}/{}/{}", host, segments[0], segments[1]);
50 return (clean, Some(segments[4].to_string()));
51 }
52
53 if (host == "gitlab.com" || host.ends_with(".gitlab.com")) && segments.len() > 2 {
54 return (
55 format!("https://{}/{}/{}", host, segments[0], segments[1]),
56 None,
57 );
58 }
59
60 (raw.to_string(), None)
61}
62
63pub fn source_subdirectory(raw: &str) -> Option<String> {
68 let parsed = Url::parse(raw).ok()?;
69 let host = parsed.host_str()?;
70 let segments: Vec<&str> = parsed.path().trim_start_matches('/').split('/').collect();
71
72 if host == "github.com" || host.ends_with(".github.com") {
73 if segments.len() >= 5 && (segments[2] == "tree" || segments[2] == "blob") {
74 return Some(segments[4..].join("/"));
75 }
76 if segments.len() > 2 && segments[2] != "tree" && segments[2] != "blob" {
77 return Some(segments[2..].join("/"));
78 }
79 }
80
81 if host == "gitlab.com" || host.ends_with(".gitlab.com") {
82 if segments.len() >= 6
83 && segments[2] == "-"
84 && (segments[3] == "tree" || segments[3] == "blob")
85 {
86 return Some(segments[5..].join("/"));
87 }
88 if segments.len() > 2 && segments[2] != "-" {
89 return Some(segments[2..].join("/"));
90 }
91 }
92
93 None
94}
95
96pub fn clone_to_temp(
97 raw_url: &str,
98 resolved_ref: Option<&str>,
99) -> Result<(TempDir, PathBuf, String)> {
100 let (clean_url, branch) = clean_git_url(raw_url);
101 let temp = TempDir::new()?;
102 let checkout = temp.path().join("source");
103 let mut clone = Command::new("git");
104 clone.args(["clone", "--quiet"]);
105 if resolved_ref.is_none() {
106 clone.args(["--depth", "1"]);
107 if let Some(branch) = branch.as_deref() {
108 clone.args(["--branch", branch]);
109 }
110 }
111 clone.arg(&clean_url).arg(&checkout);
112 run_git(
113 &mut clone,
114 &format!("git clone failed for {clean_url}; is the repo accessible?"),
115 )?;
116 if let Some(reference) = resolved_ref {
117 run_git(
118 Command::new("git")
119 .args(["checkout", "--quiet", "--detach", reference])
120 .current_dir(&checkout),
121 &format!("could not check out recorded ref {reference}"),
122 )?;
123 }
124 Ok((temp, checkout, clean_url))
125}
126
127pub fn clone_tag_to_temp(raw_url: &str, tag: &str) -> Result<(TempDir, PathBuf, String)> {
130 let (clean_url, _) = clean_git_url(raw_url);
131 let temp = TempDir::new()?;
132 let checkout = temp.path().join("source");
133 run_git(
134 Command::new("git")
135 .args(["clone", "--quiet", "--depth", "1", "--branch", tag])
136 .arg(&clean_url)
137 .arg(&checkout),
138 &format!("git clone failed for {clean_url} at tag {tag}; is the repo accessible?"),
139 )?;
140 Ok((temp, checkout, clean_url))
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct RemoteTag {
146 pub name: String,
147 pub commit: String,
149}
150
151pub fn list_remote_tags(raw_url: &str) -> Result<Vec<RemoteTag>> {
154 let (clean_url, _) = clean_git_url(raw_url);
155 let listing = ls_remote(&clean_url, &["--tags"], &[])?;
156 Ok(parse_ls_remote_tags(&listing))
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct RemoteRefs {
163 pub head: Option<String>,
168 pub tags: Vec<RemoteTag>,
169}
170
171pub fn list_remote_refs(raw_url: &str) -> Result<RemoteRefs> {
175 let (clean_url, branch) = clean_git_url(raw_url);
176 let head_ref = match branch {
177 Some(branch) => format!("refs/heads/{branch}"),
178 None => "HEAD".to_string(),
179 };
180 let listing = ls_remote(&clean_url, &[], &[&head_ref, "refs/tags/*"])?;
181 let head = listing.lines().find_map(|line| {
182 let (sha, reference) = line.split_once('\t')?;
183 (reference == head_ref).then(|| sha.to_string())
184 });
185 Ok(RemoteRefs {
186 head,
187 tags: parse_ls_remote_tags(&listing),
188 })
189}
190
191fn ls_remote(clean_url: &str, flags: &[&str], patterns: &[&str]) -> Result<String> {
193 let output = Command::new("git")
194 .arg("ls-remote")
195 .args(flags)
196 .arg(clean_url)
197 .args(patterns)
198 .output()?;
199 if !output.status.success() {
200 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
201 let context = format!("git ls-remote failed for {clean_url}; is the repo accessible?");
202 return Err(TuffError::source_failed(if stderr.is_empty() {
203 context
204 } else {
205 format!("{context}: {stderr}")
206 }));
207 }
208 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
209}
210
211fn parse_ls_remote_tags(output: &str) -> Vec<RemoteTag> {
215 let mut tags: Vec<RemoteTag> = Vec::new();
216 for line in output.lines() {
217 let Some((sha, reference)) = line.split_once('\t') else {
218 continue;
219 };
220 let Some(name) = reference.strip_prefix("refs/tags/") else {
221 continue;
222 };
223 match name.strip_suffix("^{}") {
224 Some(peeled) => {
225 if let Some(tag) = tags.iter_mut().find(|tag| tag.name == peeled) {
226 tag.commit = sha.to_string();
227 }
228 }
229 None => tags.push(RemoteTag {
230 name: name.to_string(),
231 commit: sha.to_string(),
232 }),
233 }
234 }
235 tags
236}
237
238fn run_git(cmd: &mut Command, context: &str) -> Result<()> {
239 let output = cmd.output()?;
240 if output.status.success() {
241 return Ok(());
242 }
243
244 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
245 if stderr.is_empty() {
246 Err(TuffError::source_failed(context.to_string()))
247 } else {
248 Err(TuffError::source_failed(format!("{context}: {stderr}")))
249 }
250}
251
252pub fn resolve_ref(repo: &Path) -> Result<String> {
253 let output = Command::new("git")
254 .args(["rev-parse", "HEAD"])
255 .current_dir(repo)
256 .output()?;
257
258 if !output.status.success() {
259 return Err(TuffError::source_failed("failed to resolve git ref"));
260 }
261
262 let sha = String::from_utf8_lossy(&output.stdout).trim().to_string();
263 if sha.is_empty() {
264 return Err(TuffError::source_failed("empty git ref"));
265 }
266 Ok(sha)
267}
268
269pub fn discover_capability(
270 repo: &Path,
271 name: &str,
272 capability_type: CapabilityType,
273) -> Result<PathBuf> {
274 locate_capability(repo, name, capability_type).map(|found| found.dir)
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct LocatedCapability {
280 pub dir: PathBuf,
281 pub searched: bool,
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
289pub struct FoundCapability {
290 pub name: String,
293 pub path: String,
295}
296
297const SKIPPED_SEARCH_DIRS: &[&str] = &[".git", "node_modules", "target", ".venv", "vendor"];
300
301const MAX_SEARCH_DEPTH: usize = 8;
303
304pub fn locate_capability(
312 repo: &Path,
313 name: &str,
314 capability_type: CapabilityType,
315) -> Result<LocatedCapability> {
316 let dir_plural = capability_type.plural_dir(); let dir_singular = capability_type.as_str(); let mut matches = Vec::new();
320
321 let direct = repo.join(name);
324 if direct.is_dir() {
325 matches.push(direct);
326 }
327
328 let p1 = repo.join(dir_plural).join(name);
330 if p1.is_dir() {
331 matches.push(p1);
332 }
333
334 let p2 = repo.join(dir_singular).join(name);
336 if p2.is_dir() {
337 matches.push(p2);
338 }
339
340 let p3 = repo.join(name);
342 if p3.is_dir() {
343 matches.push(p3);
344 }
345
346 let plural_dir = repo.join(dir_plural);
348 if plural_dir.is_dir() {
349 for entry in std::fs::read_dir(&plural_dir)? {
350 let entry = entry?;
351 if entry.file_type()?.is_dir() {
352 let candidate = entry.path().join(name);
353 if candidate.is_dir() {
354 matches.push(candidate);
355 }
356 }
357 }
358 }
359
360 matches.sort();
361 matches.dedup();
362 match matches.len() {
363 0 => {}
364 1 => {
365 return Ok(LocatedCapability {
366 dir: matches.remove(0),
367 searched: false,
368 });
369 }
370 _ => return Err(ambiguous(repo, name, &matches)),
371 }
372
373 let found = find_capabilities(repo, capability_type)?;
374 let searched: Vec<PathBuf> = found
375 .iter()
376 .filter(|capability| {
377 capability.name == name || capability.path.rsplit('/').next() == Some(name)
378 })
379 .map(|capability| repo.join(&capability.path))
380 .collect();
381 match searched.len() {
382 0 => Err(not_found(name, capability_type, &found)),
383 1 => Ok(LocatedCapability {
384 dir: searched.into_iter().next().expect("one match"),
385 searched: true,
386 }),
387 _ => Err(ambiguous(repo, name, &searched)),
388 }
389}
390
391pub fn find_capabilities(
395 repo: &Path,
396 capability_type: CapabilityType,
397) -> Result<Vec<FoundCapability>> {
398 let marker = if capability_type == CapabilityType::Skill {
399 "SKILL.md"
400 } else {
401 "tuff.toml"
402 };
403 let mut found = Vec::new();
404 let mut pending = vec![(repo.to_path_buf(), 0usize)];
405 while let Some((dir, depth)) = pending.pop() {
406 if dir != repo && dir.join(marker).is_file() {
407 let path = dir
408 .strip_prefix(repo)
409 .unwrap_or(&dir)
410 .components()
411 .map(|component| component.as_os_str().to_string_lossy().to_string())
412 .collect::<Vec<_>>()
413 .join("/");
414 let dir_name = dir
415 .file_name()
416 .map(|name| name.to_string_lossy().to_string())
417 .unwrap_or_default();
418 let name = if capability_type == CapabilityType::Skill {
419 std::fs::read_to_string(dir.join(marker))
420 .ok()
421 .and_then(|skill| crate::manifest::frontmatter_name(&skill))
422 .unwrap_or(dir_name)
423 } else {
424 dir_name
425 };
426 found.push(FoundCapability { name, path });
427 continue;
430 }
431 if depth >= MAX_SEARCH_DEPTH {
432 continue;
433 }
434 for entry in std::fs::read_dir(&dir)? {
435 let entry = entry?;
436 if !entry.file_type()?.is_dir() {
439 continue;
440 }
441 let file_name = entry.file_name();
442 if SKIPPED_SEARCH_DIRS
443 .iter()
444 .any(|skipped| file_name == std::ffi::OsStr::new(skipped))
445 {
446 continue;
447 }
448 pending.push((entry.path(), depth + 1));
449 }
450 }
451 found.sort_by(|a, b| a.path.cmp(&b.path));
452 Ok(found)
453}
454
455fn ambiguous(repo: &Path, name: &str, matches: &[PathBuf]) -> TuffError {
456 let paths: Vec<_> = matches
457 .iter()
458 .map(|p| p.strip_prefix(repo).unwrap_or(p).display().to_string())
459 .collect();
460 TuffError::usage(format!(
461 "ambiguous capability name '{}' matches multiple paths: {}",
462 name,
463 paths.join(", ")
464 ))
465 .with_hint("name the folder in the URL instead, e.g. <repo>/tree/<branch>/<path>")
466}
467
468fn not_found(name: &str, capability_type: CapabilityType, found: &[FoundCapability]) -> TuffError {
469 let mut message = format!("{capability_type} '{name}' not found in repository");
470 if !found.is_empty() {
471 message.push_str(&format!("\n{}", describe_found(capability_type, found)));
472 }
473 TuffError::not_found(message).with_hint(
474 "pass one of the names above, or name the folder in the URL, e.g. <repo>/tree/<branch>/<path>",
475 )
476}
477
478pub fn describe_found(capability_type: CapabilityType, found: &[FoundCapability]) -> String {
481 let width = found.iter().map(|c| c.name.len()).max().unwrap_or(0);
482 let mut lines = vec![format!("Available {}:", capability_type.plural_dir())];
483 for capability in found {
484 lines.push(format!(
485 " {:width$} {}",
486 capability.name,
487 capability.path,
488 width = width
489 ));
490 }
491 lines.join("\n")
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497
498 fn write_skill(repo: &Path, path: &str, name: &str) {
499 let dir = repo.join(path);
500 std::fs::create_dir_all(&dir).unwrap();
501 std::fs::write(
502 dir.join("SKILL.md"),
503 format!("---\nname: {name}\ndescription: d\n---\nbody\n"),
504 )
505 .unwrap();
506 }
507
508 #[test]
509 fn find_capabilities_searches_the_repository_and_skips_dependency_trees() {
510 let repo = tempfile::tempdir().unwrap();
511 write_skill(repo.path(), "skills/alpha", "alpha");
512 write_skill(repo.path(), ".claude/skills/beta", "beta");
513 write_skill(repo.path(), "skills/zeta-skill", "zeta");
514 write_skill(repo.path(), "node_modules/dep/skills/beta", "beta");
515 write_skill(repo.path(), "skills/alpha/examples/inner", "inner");
517
518 let found = find_capabilities(repo.path(), CapabilityType::Skill).unwrap();
519 let pairs: Vec<_> = found
520 .iter()
521 .map(|c| (c.name.as_str(), c.path.as_str()))
522 .collect();
523 assert_eq!(
524 pairs,
525 [
526 ("beta", ".claude/skills/beta"),
527 ("alpha", "skills/alpha"),
528 ("zeta", "skills/zeta-skill"),
529 ]
530 );
531 }
532
533 #[test]
534 fn locate_capability_prefers_conventional_layouts_then_searches() {
535 let repo = tempfile::tempdir().unwrap();
536 write_skill(repo.path(), "skills/alpha", "alpha");
537 write_skill(repo.path(), "plugins/p/skills/gamma", "gamma");
538 write_skill(repo.path(), "skills/zeta-skill", "zeta");
539
540 let alpha = locate_capability(repo.path(), "alpha", CapabilityType::Skill).unwrap();
541 assert!(!alpha.searched);
542 assert_eq!(alpha.dir, repo.path().join("skills/alpha"));
543
544 let gamma = locate_capability(repo.path(), "gamma", CapabilityType::Skill).unwrap();
545 assert!(gamma.searched);
546 assert_eq!(gamma.dir, repo.path().join("plugins/p/skills/gamma"));
547
548 let zeta = locate_capability(repo.path(), "zeta", CapabilityType::Skill).unwrap();
550 assert_eq!(zeta.dir, repo.path().join("skills/zeta-skill"));
551
552 let missing = locate_capability(repo.path(), "nope", CapabilityType::Skill)
553 .unwrap_err()
554 .to_string();
555 assert!(missing.contains("plugins/p/skills/gamma"), "{missing}");
556 }
557
558 #[test]
559 fn locate_capability_reports_a_name_found_twice_by_search() {
560 let repo = tempfile::tempdir().unwrap();
561 write_skill(repo.path(), "a/skills/dup", "dup");
562 write_skill(repo.path(), "b/skills/dup", "dup");
563 let err = locate_capability(repo.path(), "dup", CapabilityType::Skill)
564 .unwrap_err()
565 .to_string();
566 assert!(err.contains("ambiguous"), "{err}");
567 assert!(
568 err.contains("a/skills/dup") && err.contains("b/skills/dup"),
569 "{err}"
570 );
571 }
572
573 #[test]
574 fn ls_remote_tags_peel_annotated_tags_to_their_commit() {
575 let output = "aaaa\trefs/tags/v1.0.0\n\
576 bbbb\trefs/tags/v1.2.0\n\
577 cccc\trefs/tags/v1.2.0^{}\n\
578 dddd\trefs/heads/main\n";
579 let tags = parse_ls_remote_tags(output);
580 assert_eq!(
581 tags,
582 vec![
583 RemoteTag {
584 name: "v1.0.0".into(),
585 commit: "aaaa".into()
586 },
587 RemoteTag {
588 name: "v1.2.0".into(),
589 commit: "cccc".into()
590 },
591 ]
592 );
593 }
594
595 #[test]
596 fn detect_github_clean_url() {
597 assert!(is_git_url("https://github.com/owner/repo"));
598 assert!(is_git_url("http://github.com/owner/repo"));
599 }
600
601 #[test]
602 fn detect_github_tree_url() {
603 assert!(is_git_url("https://github.com/owner/repo/tree/main/skills"));
604 }
605
606 #[test]
607 fn detect_ssh_url() {
608 assert!(is_git_url("git@github.com:owner/repo.git"));
609 }
610
611 #[test]
612 fn detect_file_url() {
613 assert!(is_git_url("file:///path/to/repo"));
614 }
615
616 #[test]
617 fn reject_local_path() {
618 assert!(!is_git_url("./my-skill"));
619 assert!(!is_git_url("/absolute/path"));
620 }
621
622 #[test]
623 fn clean_github_tree_extracts_repo_and_branch() {
624 let (url, branch) = clean_git_url("https://github.com/owner/repo/tree/main/skills");
625 assert_eq!(url, "https://github.com/owner/repo");
626 assert_eq!(branch, Some("main".to_string()));
627 }
628
629 #[test]
630 fn clean_github_blob_extracts_repo_and_branch() {
631 let (url, branch) = clean_git_url("https://github.com/owner/repo/blob/main/README.md");
632 assert_eq!(url, "https://github.com/owner/repo");
633 assert_eq!(branch, Some("main".to_string()));
634 }
635
636 #[test]
637 fn clean_plain_url_passes_through() {
638 let (url, branch) = clean_git_url("https://github.com/vercel-labs/skills");
639 assert_eq!(url, "https://github.com/vercel-labs/skills");
640 assert_eq!(branch, None);
641 }
642
643 #[test]
644 fn github_folder_url_is_normalized_and_preserves_subdirectory() {
645 let (url, branch) = clean_git_url(
646 "https://github.com/am-will/codex-skills/hooks/aitmpl-codex/automation/change-logger",
647 );
648 assert_eq!(url, "https://github.com/am-will/codex-skills");
649 assert_eq!(branch, None);
650 assert_eq!(
651 source_subdirectory(
652 "https://github.com/am-will/codex-skills/hooks/aitmpl-codex/automation/change-logger"
653 ),
654 Some("hooks/aitmpl-codex/automation/change-logger".to_string())
655 );
656 }
657
658 #[test]
659 fn github_tree_url_preserves_branch_and_subdirectory() {
660 assert_eq!(
661 source_subdirectory(
662 "https://github.com/am-will/codex-skills/tree/main/hooks/aitmpl-codex/automation/change-logger"
663 ),
664 Some("hooks/aitmpl-codex/automation/change-logger".to_string())
665 );
666 }
667
668 #[test]
669 fn clean_gitlab_tree_extracts_repo_and_branch() {
670 let (url, branch) = clean_git_url("https://gitlab.com/owner/repo/-/tree/main/src");
671 assert_eq!(url, "https://gitlab.com/owner/repo");
672 assert_eq!(branch, Some("main".to_string()));
673 }
674
675 #[test]
676 fn clean_file_url_passes_through() {
677 let (url, branch) = clean_git_url("file:///path/to/repo");
678 assert_eq!(url, "file:///path/to/repo");
679 assert_eq!(branch, None);
680 }
681}