1use anyhow::{bail, ensure, Context, Result};
2use std::io::Read;
3use std::path::{Path, PathBuf};
4use walkdir::WalkDir;
5
6use super::central_repo;
7use super::content_hash;
8use super::skill_metadata::{self, sanitize_skill_name};
9use super::sync_engine;
10
11#[cfg(test)]
12mod import_tests;
13mod source;
14pub use source::install_from_skill_source_to_destination;
15pub(crate) use source::prepare_skill_from_source;
16
17#[derive(Clone, Copy)]
18struct ArchiveLimits {
19 entries: usize,
20 extracted_bytes: u64,
21}
22
23pub struct InstallResult {
24 pub name: String,
25 pub description: Option<String>,
26 pub central_path: PathBuf,
27 pub content_hash: String,
28}
29
30enum PreparedSource {
31 Directory(PathBuf),
32 Archive {
33 _temp_dir: tempfile::TempDir,
34 skill_dir: PathBuf,
35 },
36}
37
38impl PreparedSource {
39 fn open(source: &Path) -> Result<Self> {
40 if source.is_dir() {
41 validate_skill_source(source)?;
42 Ok(PreparedSource::Directory(source.to_path_buf()))
43 } else {
44 Self::from_archive(source, None)
45 }
46 }
47
48 fn from_archive(source: &Path, limits: Option<ArchiveLimits>) -> Result<Self> {
49 let ext = source
50 .extension()
51 .map(|e| e.to_string_lossy().to_string())
52 .unwrap_or_default();
53 if ext != "zip" && ext != "skill" {
54 bail!("Unsupported archive format: {}", ext);
55 }
56
57 let temp_dir = tempfile::tempdir()?;
58 let file = std::fs::File::open(source)?;
59 let mut archive = zip::ZipArchive::new(file)?;
60 safe_extract(&mut archive, temp_dir.path(), limits)?;
61
62 let mut found = Vec::new();
64 for entry in WalkDir::new(temp_dir.path()).max_depth(4) {
65 let entry = entry?;
66 let name = entry.file_name().to_string_lossy();
67 if entry.file_type().is_file()
68 && skill_metadata::SKILL_DIR_MARKERS.contains(&name.as_ref())
69 {
70 if let Some(parent) = entry.path().parent() {
71 found.push(parent.to_path_buf());
72 }
73 }
74 }
75
76 found.sort();
77 found.dedup();
78
79 let skill_dir = match found.len() {
80 0 => bail!("INVALID_SKILL_SOURCE: Archive contains no SKILL.md or skill.md file"),
81 1 => found.into_iter().next().unwrap(),
82 _ => bail!("Multiple skill directories found in archive"),
83 };
84
85 Ok(PreparedSource::Archive {
86 _temp_dir: temp_dir,
87 skill_dir,
88 })
89 }
90
91 fn skill_dir(&self) -> &Path {
92 match self {
93 PreparedSource::Directory(p) => p,
94 PreparedSource::Archive { skill_dir, .. } => skill_dir,
95 }
96 }
97}
98
99fn validate_skill_source(source: &Path) -> Result<()> {
100 if !skill_metadata::is_valid_skill_dir(source) {
101 bail!("INVALID_SKILL_SOURCE: Select a skill folder containing a SKILL.md or skill.md file");
102 }
103 Ok(())
104}
105
106pub fn install_from_local(source: &Path, name: Option<&str>) -> Result<InstallResult> {
107 let prepared = PreparedSource::open(source)?;
108 let skill_dir = prepared.skill_dir();
109
110 let sanitized_name = match name {
111 Some(n) if !n.is_empty() => {
112 sanitize_skill_name(n).ok_or_else(|| anyhow::anyhow!("Invalid skill name: '{}'", n))?
113 }
114 _ => skill_metadata::infer_skill_name(skill_dir),
115 };
116
117 let skills_dir = central_repo::skills_dir();
118 let dest = unique_skill_dest(&skills_dir, &sanitized_name, skill_dir, true, |_| Ok(false))?;
119 let final_name = dest
120 .file_name()
121 .map(|n| n.to_string_lossy().to_string())
122 .unwrap_or_else(|| sanitized_name.clone());
123
124 install_skill_dir_to_destination(skill_dir, &final_name, &dest)
125}
126
127pub fn install_from_local_to_destination(
128 source: &Path,
129 name: Option<&str>,
130 destination: &Path,
131) -> Result<InstallResult> {
132 let prepared = PreparedSource::open(source)?;
133 install_prepared_to_destination(&prepared, name, destination)
134}
135
136fn install_prepared_to_destination(
137 prepared: &PreparedSource,
138 name: Option<&str>,
139 destination: &Path,
140) -> Result<InstallResult> {
141 let skill_dir = prepared.skill_dir();
142 let skill_name = match name {
143 Some(n) if !n.is_empty() => {
144 sanitize_skill_name(n).ok_or_else(|| anyhow::anyhow!("Invalid skill name: '{}'", n))?
145 }
146 _ => skill_metadata::infer_skill_name(skill_dir),
147 };
148 install_skill_dir_to_destination(skill_dir, &skill_name, destination)
149}
150
151pub fn resolve_local_skill_name(source: &Path, name: Option<&str>) -> Result<String> {
152 let prepared = PreparedSource::open(source)?;
153 let skill_dir = prepared.skill_dir();
154
155 Ok(match name {
156 Some(n) if !n.is_empty() => {
157 sanitize_skill_name(n).ok_or_else(|| anyhow::anyhow!("Invalid skill name: '{}'", n))?
158 }
159 _ => skill_metadata::infer_skill_name(skill_dir),
160 })
161}
162
163pub fn hash_local_source(source: &Path) -> Result<String> {
164 let prepared = PreparedSource::open(source)?;
165 content_hash::hash_directory(prepared.skill_dir())
166}
167
168pub fn hash_local_source_eol_insensitive(source: &Path) -> Result<String> {
173 let prepared = PreparedSource::open(source)?;
174 content_hash::hash_directory_eol_insensitive(prepared.skill_dir())
175}
176
177pub fn install_from_git_dir(source: &Path, name: Option<&str>) -> Result<InstallResult> {
178 install_from_local(source, name)
179}
180
181pub fn install_skill_dir_to_destination(
182 source: &Path,
183 name: &str,
184 destination: &Path,
185) -> Result<InstallResult> {
186 validate_skill_source(source)?;
189 let meta = skill_metadata::parse_skill_md(source);
190
191 if sync_engine::is_library_entry(destination)
192 && source.canonicalize()? == destination.canonicalize().unwrap_or_default()
193 {
194 return Ok(InstallResult {
195 name: name.to_string(),
196 description: meta.description,
197 central_path: destination.to_path_buf(),
198 content_hash: content_hash::hash_directory(destination)?,
199 });
200 }
201 sync_engine::ensure_dst_not_inside_src(source, destination)?;
202
203 if destination.exists() {
204 std::fs::remove_dir_all(destination)
205 .with_context(|| format!("Failed to remove existing {:?}", destination))?;
206 }
207
208 copy_skill_dir(source, destination)?;
209
210 let hash = content_hash::hash_directory(destination)?;
211
212 Ok(InstallResult {
213 name: name.to_string(),
214 description: meta.description,
215 central_path: destination.to_path_buf(),
216 content_hash: hash,
217 })
218}
219
220fn safe_extract(
222 archive: &mut zip::ZipArchive<std::fs::File>,
223 dest: &Path,
224 limits: Option<ArchiveLimits>,
225) -> Result<()> {
226 let mut remaining = limits.map(|limit| limit.extracted_bytes);
227 if let Some(limit) = limits {
228 ensure!(
229 archive.len() <= limit.entries,
230 "Skill archive has too many entries"
231 );
232 }
233 for i in 0..archive.len() {
234 let mut entry = archive.by_index(i)?;
235
236 let Some(entry_path) = entry
237 .enclosed_name()
238 .map(|name| dest.join(name))
239 .filter(|path| path.starts_with(dest))
240 else {
241 ensure!(limits.is_none(), "Skill archive contains an invalid path");
242 continue;
243 };
244 if limits.is_some() {
245 ensure!(
246 entry.is_file() || entry.is_dir(),
247 "Skill archive contains an unsupported entry"
248 );
249 }
250
251 if entry.is_dir() {
252 std::fs::create_dir_all(&entry_path)?;
253 } else {
254 if let Some(parent) = entry_path.parent() {
255 std::fs::create_dir_all(parent)?;
256 }
257 let mut outfile = std::fs::File::create(&entry_path)?;
258 if let Some(bytes) = remaining.as_mut() {
259 ensure!(
260 entry.size() <= *bytes,
261 "Extracted skill archive exceeds size limit"
262 );
263 let written = std::io::copy(&mut (&mut entry).take(*bytes + 1), &mut outfile)?;
264 ensure!(
265 written <= *bytes,
266 "Extracted skill archive exceeds size limit"
267 );
268 *bytes -= written;
269 } else {
270 std::io::copy(&mut entry, &mut outfile)?;
271 }
272
273 #[cfg(unix)]
276 {
277 if let Some(mode) = entry.unix_mode() {
278 use std::os::unix::fs::PermissionsExt;
279 let mode = if limits.is_some() { mode & 0o777 } else { mode };
280 let _ = std::fs::set_permissions(
281 &entry_path,
282 std::fs::Permissions::from_mode(mode),
283 );
284 }
285 }
286 }
287 }
288 Ok(())
289}
290
291fn unique_skill_dest(
299 parent: &Path,
300 sanitized_name: &str,
301 source: &Path,
302 reuse_identical: bool,
303 is_reserved: impl Fn(&Path) -> Result<bool>,
304) -> Result<PathBuf> {
305 let source_hash = reuse_identical
306 .then(|| content_hash::hash_directory(source))
307 .transpose()?;
308
309 for i in 1u32.. {
310 let candidate = if i == 1 {
311 parent.join(sanitized_name)
312 } else {
313 parent.join(format!("{}-{}", sanitized_name, i))
314 };
315
316 if is_reserved(&candidate)? {
317 continue;
318 }
319
320 if !candidate.exists() && !candidate.is_symlink() {
321 return Ok(candidate);
322 }
323
324 if source_hash.as_deref().is_some_and(|hash| {
325 content_hash::hash_directory(&candidate).ok().as_deref() == Some(hash)
326 }) {
327 return Ok(candidate);
328 }
329 }
330
331 Ok(parent.join(sanitized_name))
332}
333
334fn copy_skill_dir(src: &Path, dst: &Path) -> Result<()> {
335 std::fs::create_dir_all(dst)?;
336 for entry in std::fs::read_dir(src)? {
337 let entry = entry?;
338 let ft = entry.file_type()?;
339 let name = entry.file_name();
340 let name_str = name.to_string_lossy();
341
342 if name_str == ".git" || name_str == ".DS_Store" {
343 continue;
344 }
345
346 if ft.is_symlink() {
348 continue;
349 }
350
351 let dest_path = dst.join(&name);
352 if ft.is_dir() {
353 copy_skill_dir(&entry.path(), &dest_path)?;
354 } else {
355 std::fs::copy(entry.path(), &dest_path)?;
356 }
357 }
358 Ok(())
359}
360
361#[cfg(test)]
362mod tests;