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
191pub fn remote_branch_head(raw_url: &str, branch: &str) -> Result<Option<String>> {
194 let (clean_url, _) = clean_git_url(raw_url);
195 let head_ref = format!("refs/heads/{branch}");
196 let listing = ls_remote(&clean_url, &[], &[&head_ref])?;
197 Ok(listing.lines().find_map(|line| {
198 let (sha, reference) = line.split_once('\t')?;
199 (reference == head_ref).then(|| sha.to_string())
200 }))
201}
202
203pub fn current_branch(repo: &Path) -> Option<String> {
205 let output = Command::new("git")
206 .args(["symbolic-ref", "--quiet", "--short", "HEAD"])
207 .current_dir(repo)
208 .output()
209 .ok()?;
210 if !output.status.success() {
211 return None;
212 }
213 let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
214 (!branch.is_empty()).then_some(branch)
215}
216
217fn ls_remote(clean_url: &str, flags: &[&str], patterns: &[&str]) -> Result<String> {
219 let output = Command::new("git")
220 .arg("ls-remote")
221 .args(flags)
222 .arg(clean_url)
223 .args(patterns)
224 .output()?;
225 if !output.status.success() {
226 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
227 let context = format!("git ls-remote failed for {clean_url}; is the repo accessible?");
228 return Err(TuffError::source_failed(if stderr.is_empty() {
229 context
230 } else {
231 format!("{context}: {stderr}")
232 }));
233 }
234 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
235}
236
237fn parse_ls_remote_tags(output: &str) -> Vec<RemoteTag> {
241 let mut tags: Vec<RemoteTag> = Vec::new();
242 for line in output.lines() {
243 let Some((sha, reference)) = line.split_once('\t') else {
244 continue;
245 };
246 let Some(name) = reference.strip_prefix("refs/tags/") else {
247 continue;
248 };
249 match name.strip_suffix("^{}") {
250 Some(peeled) => {
251 if let Some(tag) = tags.iter_mut().find(|tag| tag.name == peeled) {
252 tag.commit = sha.to_string();
253 }
254 }
255 None => tags.push(RemoteTag {
256 name: name.to_string(),
257 commit: sha.to_string(),
258 }),
259 }
260 }
261 tags
262}
263
264fn run_git(cmd: &mut Command, context: &str) -> Result<()> {
265 let output = cmd.output()?;
266 if output.status.success() {
267 return Ok(());
268 }
269
270 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
271 if stderr.is_empty() {
272 Err(TuffError::source_failed(context.to_string()))
273 } else {
274 Err(TuffError::source_failed(format!("{context}: {stderr}")))
275 }
276}
277
278pub fn resolve_ref(repo: &Path) -> Result<String> {
279 let output = Command::new("git")
280 .args(["rev-parse", "HEAD"])
281 .current_dir(repo)
282 .output()?;
283
284 if !output.status.success() {
285 return Err(TuffError::source_failed("failed to resolve git ref"));
286 }
287
288 let sha = String::from_utf8_lossy(&output.stdout).trim().to_string();
289 if sha.is_empty() {
290 return Err(TuffError::source_failed("empty git ref"));
291 }
292 Ok(sha)
293}
294
295pub fn discover_capability(
296 repo: &Path,
297 name: &str,
298 capability_type: CapabilityType,
299) -> Result<PathBuf> {
300 locate_capability(repo, name, capability_type).map(|found| found.dir)
301}
302
303#[derive(Debug, Clone, PartialEq, Eq)]
305pub struct LocatedCapability {
306 pub dir: PathBuf,
307 pub searched: bool,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct FoundCapability {
316 pub name: String,
319 pub path: String,
321}
322
323const SKIPPED_SEARCH_DIRS: &[&str] = &[".git", "node_modules", "target", ".venv", "vendor"];
326
327const MAX_SEARCH_DEPTH: usize = 8;
329
330pub fn locate_capability(
338 repo: &Path,
339 name: &str,
340 capability_type: CapabilityType,
341) -> Result<LocatedCapability> {
342 let dir_plural = capability_type.plural_dir(); let dir_singular = capability_type.as_str(); let mut matches = Vec::new();
346
347 let direct = repo.join(name);
350 if direct.is_dir() {
351 matches.push(direct);
352 }
353
354 let p1 = repo.join(dir_plural).join(name);
356 if p1.is_dir() {
357 matches.push(p1);
358 }
359
360 let p2 = repo.join(dir_singular).join(name);
362 if p2.is_dir() {
363 matches.push(p2);
364 }
365
366 let p3 = repo.join(name);
368 if p3.is_dir() {
369 matches.push(p3);
370 }
371
372 let plural_dir = repo.join(dir_plural);
374 if plural_dir.is_dir() {
375 for entry in std::fs::read_dir(&plural_dir)? {
376 let entry = entry?;
377 if entry.file_type()?.is_dir() {
378 let candidate = entry.path().join(name);
379 if candidate.is_dir() {
380 matches.push(candidate);
381 }
382 }
383 }
384 }
385
386 matches.sort();
387 matches.dedup();
388 match matches.len() {
389 0 => {}
390 1 => {
391 return Ok(LocatedCapability {
392 dir: matches.remove(0),
393 searched: false,
394 });
395 }
396 _ => return Err(ambiguous(repo, name, &matches)),
397 }
398
399 let found = find_capabilities(repo, capability_type)?;
400 let searched: Vec<PathBuf> = found
401 .iter()
402 .filter(|capability| {
403 capability.name == name || capability.path.rsplit('/').next() == Some(name)
404 })
405 .map(|capability| repo.join(&capability.path))
406 .collect();
407 match searched.len() {
408 0 => Err(not_found(name, capability_type, &found)),
409 1 => Ok(LocatedCapability {
410 dir: searched.into_iter().next().expect("one match"),
411 searched: true,
412 }),
413 _ => Err(ambiguous(repo, name, &searched)),
414 }
415}
416
417pub fn find_capabilities(
421 repo: &Path,
422 capability_type: CapabilityType,
423) -> Result<Vec<FoundCapability>> {
424 let marker = if capability_type == CapabilityType::Skill {
425 "SKILL.md"
426 } else {
427 "tuff.toml"
428 };
429 let mut found = Vec::new();
430 let mut pending = vec![(repo.to_path_buf(), 0usize)];
431 while let Some((dir, depth)) = pending.pop() {
432 if dir != repo && dir.join(marker).is_file() {
433 let path = dir
434 .strip_prefix(repo)
435 .unwrap_or(&dir)
436 .components()
437 .map(|component| component.as_os_str().to_string_lossy().to_string())
438 .collect::<Vec<_>>()
439 .join("/");
440 let dir_name = dir
441 .file_name()
442 .map(|name| name.to_string_lossy().to_string())
443 .unwrap_or_default();
444 let name = if capability_type == CapabilityType::Skill {
445 std::fs::read_to_string(dir.join(marker))
446 .ok()
447 .and_then(|skill| crate::manifest::frontmatter_name(&skill))
448 .unwrap_or(dir_name)
449 } else {
450 dir_name
451 };
452 found.push(FoundCapability { name, path });
453 continue;
456 }
457 if depth >= MAX_SEARCH_DEPTH {
458 continue;
459 }
460 for entry in std::fs::read_dir(&dir)? {
461 let entry = entry?;
462 if !entry.file_type()?.is_dir() {
465 continue;
466 }
467 let file_name = entry.file_name();
468 if SKIPPED_SEARCH_DIRS
469 .iter()
470 .any(|skipped| file_name == std::ffi::OsStr::new(skipped))
471 {
472 continue;
473 }
474 pending.push((entry.path(), depth + 1));
475 }
476 }
477 found.sort_by(|a, b| a.path.cmp(&b.path));
478 Ok(found)
479}
480
481fn ambiguous(repo: &Path, name: &str, matches: &[PathBuf]) -> TuffError {
482 let paths: Vec<_> = matches
483 .iter()
484 .map(|p| p.strip_prefix(repo).unwrap_or(p).display().to_string())
485 .collect();
486 TuffError::usage(format!(
487 "ambiguous capability name '{}' matches multiple paths: {}",
488 name,
489 paths.join(", ")
490 ))
491 .with_hint("name the folder in the URL instead, e.g. <repo>/tree/<branch>/<path>")
492}
493
494fn not_found(name: &str, capability_type: CapabilityType, found: &[FoundCapability]) -> TuffError {
495 let mut message = format!("{capability_type} '{name}' not found in repository");
496 if !found.is_empty() {
497 message.push_str(&format!("\n{}", describe_found(capability_type, found)));
498 }
499 TuffError::not_found(message).with_hint(
500 "pass one of the names above, or name the folder in the URL, e.g. <repo>/tree/<branch>/<path>",
501 )
502}
503
504pub fn describe_found(capability_type: CapabilityType, found: &[FoundCapability]) -> String {
507 let width = found.iter().map(|c| c.name.len()).max().unwrap_or(0);
508 let mut lines = vec![format!("Available {}:", capability_type.plural_dir())];
509 for capability in found {
510 lines.push(format!(
511 " {:width$} {}",
512 capability.name,
513 capability.path,
514 width = width
515 ));
516 }
517 lines.join("\n")
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523
524 fn write_skill(repo: &Path, path: &str, name: &str) {
525 let dir = repo.join(path);
526 std::fs::create_dir_all(&dir).unwrap();
527 std::fs::write(
528 dir.join("SKILL.md"),
529 format!("---\nname: {name}\ndescription: d\n---\nbody\n"),
530 )
531 .unwrap();
532 }
533
534 #[test]
535 fn find_capabilities_searches_the_repository_and_skips_dependency_trees() {
536 let repo = tempfile::tempdir().unwrap();
537 write_skill(repo.path(), "skills/alpha", "alpha");
538 write_skill(repo.path(), ".claude/skills/beta", "beta");
539 write_skill(repo.path(), "skills/zeta-skill", "zeta");
540 write_skill(repo.path(), "node_modules/dep/skills/beta", "beta");
541 write_skill(repo.path(), "skills/alpha/examples/inner", "inner");
543
544 let found = find_capabilities(repo.path(), CapabilityType::Skill).unwrap();
545 let pairs: Vec<_> = found
546 .iter()
547 .map(|c| (c.name.as_str(), c.path.as_str()))
548 .collect();
549 assert_eq!(
550 pairs,
551 [
552 ("beta", ".claude/skills/beta"),
553 ("alpha", "skills/alpha"),
554 ("zeta", "skills/zeta-skill"),
555 ]
556 );
557 }
558
559 #[test]
560 fn locate_capability_prefers_conventional_layouts_then_searches() {
561 let repo = tempfile::tempdir().unwrap();
562 write_skill(repo.path(), "skills/alpha", "alpha");
563 write_skill(repo.path(), "plugins/p/skills/gamma", "gamma");
564 write_skill(repo.path(), "skills/zeta-skill", "zeta");
565
566 let alpha = locate_capability(repo.path(), "alpha", CapabilityType::Skill).unwrap();
567 assert!(!alpha.searched);
568 assert_eq!(alpha.dir, repo.path().join("skills/alpha"));
569
570 let gamma = locate_capability(repo.path(), "gamma", CapabilityType::Skill).unwrap();
571 assert!(gamma.searched);
572 assert_eq!(gamma.dir, repo.path().join("plugins/p/skills/gamma"));
573
574 let zeta = locate_capability(repo.path(), "zeta", CapabilityType::Skill).unwrap();
576 assert_eq!(zeta.dir, repo.path().join("skills/zeta-skill"));
577
578 let missing = locate_capability(repo.path(), "nope", CapabilityType::Skill)
579 .unwrap_err()
580 .to_string();
581 assert!(missing.contains("plugins/p/skills/gamma"), "{missing}");
582 }
583
584 #[test]
585 fn locate_capability_reports_a_name_found_twice_by_search() {
586 let repo = tempfile::tempdir().unwrap();
587 write_skill(repo.path(), "a/skills/dup", "dup");
588 write_skill(repo.path(), "b/skills/dup", "dup");
589 let err = locate_capability(repo.path(), "dup", CapabilityType::Skill)
590 .unwrap_err()
591 .to_string();
592 assert!(err.contains("ambiguous"), "{err}");
593 assert!(
594 err.contains("a/skills/dup") && err.contains("b/skills/dup"),
595 "{err}"
596 );
597 }
598
599 #[test]
600 fn ls_remote_tags_peel_annotated_tags_to_their_commit() {
601 let output = "aaaa\trefs/tags/v1.0.0\n\
602 bbbb\trefs/tags/v1.2.0\n\
603 cccc\trefs/tags/v1.2.0^{}\n\
604 dddd\trefs/heads/main\n";
605 let tags = parse_ls_remote_tags(output);
606 assert_eq!(
607 tags,
608 vec![
609 RemoteTag {
610 name: "v1.0.0".into(),
611 commit: "aaaa".into()
612 },
613 RemoteTag {
614 name: "v1.2.0".into(),
615 commit: "cccc".into()
616 },
617 ]
618 );
619 }
620
621 #[test]
622 fn detect_github_clean_url() {
623 assert!(is_git_url("https://github.com/owner/repo"));
624 assert!(is_git_url("http://github.com/owner/repo"));
625 }
626
627 #[test]
628 fn detect_github_tree_url() {
629 assert!(is_git_url("https://github.com/owner/repo/tree/main/skills"));
630 }
631
632 #[test]
633 fn detect_ssh_url() {
634 assert!(is_git_url("git@github.com:owner/repo.git"));
635 }
636
637 #[test]
638 fn detect_file_url() {
639 assert!(is_git_url("file:///path/to/repo"));
640 }
641
642 #[test]
643 fn reject_local_path() {
644 assert!(!is_git_url("./my-skill"));
645 assert!(!is_git_url("/absolute/path"));
646 }
647
648 #[test]
649 fn clean_github_tree_extracts_repo_and_branch() {
650 let (url, branch) = clean_git_url("https://github.com/owner/repo/tree/main/skills");
651 assert_eq!(url, "https://github.com/owner/repo");
652 assert_eq!(branch, Some("main".to_string()));
653 }
654
655 #[test]
656 fn clean_github_blob_extracts_repo_and_branch() {
657 let (url, branch) = clean_git_url("https://github.com/owner/repo/blob/main/README.md");
658 assert_eq!(url, "https://github.com/owner/repo");
659 assert_eq!(branch, Some("main".to_string()));
660 }
661
662 #[test]
663 fn clean_plain_url_passes_through() {
664 let (url, branch) = clean_git_url("https://github.com/vercel-labs/skills");
665 assert_eq!(url, "https://github.com/vercel-labs/skills");
666 assert_eq!(branch, None);
667 }
668
669 #[test]
670 fn github_folder_url_is_normalized_and_preserves_subdirectory() {
671 let (url, branch) = clean_git_url(
672 "https://github.com/am-will/codex-skills/hooks/aitmpl-codex/automation/change-logger",
673 );
674 assert_eq!(url, "https://github.com/am-will/codex-skills");
675 assert_eq!(branch, None);
676 assert_eq!(
677 source_subdirectory(
678 "https://github.com/am-will/codex-skills/hooks/aitmpl-codex/automation/change-logger"
679 ),
680 Some("hooks/aitmpl-codex/automation/change-logger".to_string())
681 );
682 }
683
684 #[test]
685 fn github_tree_url_preserves_branch_and_subdirectory() {
686 assert_eq!(
687 source_subdirectory(
688 "https://github.com/am-will/codex-skills/tree/main/hooks/aitmpl-codex/automation/change-logger"
689 ),
690 Some("hooks/aitmpl-codex/automation/change-logger".to_string())
691 );
692 }
693
694 #[test]
695 fn clean_gitlab_tree_extracts_repo_and_branch() {
696 let (url, branch) = clean_git_url("https://gitlab.com/owner/repo/-/tree/main/src");
697 assert_eq!(url, "https://gitlab.com/owner/repo");
698 assert_eq!(branch, Some("main".to_string()));
699 }
700
701 #[test]
702 fn clean_file_url_passes_through() {
703 let (url, branch) = clean_git_url("file:///path/to/repo");
704 assert_eq!(url, "file:///path/to/repo");
705 assert_eq!(branch, None);
706 }
707}