1use std::collections::BTreeSet;
11use std::fs;
12use std::path::{Component, Path, PathBuf};
13
14use crate::error::{Result, TuffError};
15use crate::manifest::CapabilityType;
16use crate::pack::{self, PackManifest, PackMember, PackUnsupported};
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct BundleFile {
21 pub path: String,
22 pub bytes: Vec<u8>,
23}
24
25#[derive(Debug, Clone)]
27pub struct ImportedMember {
28 pub id: String,
29 pub capability_type: CapabilityType,
30 pub manifest: toml::Table,
32 pub files: Vec<BundleFile>,
34}
35
36#[derive(Debug, Clone)]
38pub struct ImportedPack {
39 pub manifest: PackManifest,
41 pub members: Vec<ImportedMember>,
42 pub extra: Vec<BundleFile>,
45 pub notes: Vec<String>,
48}
49
50impl ImportedPack {
51 pub fn unsupported(&self) -> &[PackUnsupported] {
53 self.manifest
54 .import
55 .as_ref()
56 .map(|import| import.unsupported.as_slice())
57 .unwrap_or_default()
58 }
59}
60
61#[derive(Debug, Clone)]
64pub enum BundleLocation {
65 Local(LocalBundle),
66 Remote(RemoteBundle),
67}
68
69#[derive(Debug, Clone)]
71pub struct LocalBundle {
72 pub root: PathBuf,
73 pub name: Option<String>,
75 pub entry: Option<serde_json::Value>,
77}
78
79#[derive(Debug, Clone)]
81pub struct RemoteBundle {
82 pub name: String,
83 pub url: String,
84 pub path: Option<String>,
86 pub git_ref: Option<String>,
88 pub commit: Option<String>,
90 pub entry: serde_json::Value,
91}
92
93pub trait BundleReader {
95 fn id(&self) -> &'static str;
97 fn detect(&self, root: &Path) -> bool;
99 fn locate(&self, root: &Path, entry: Option<&str>) -> Result<BundleLocation>;
106 fn read(&self, bundle: &LocalBundle, version_hint: Option<&str>) -> Result<ImportedPack>;
114}
115
116#[derive(Debug, Clone, Default)]
118pub struct BundleOutput {
119 pub files: Vec<BundleFile>,
121 pub members: Vec<BundleMemberOutput>,
123 pub skipped: Vec<PackUnsupported>,
125 pub warnings: Vec<String>,
128}
129
130#[derive(Debug, Clone)]
132pub struct BundleMemberOutput {
133 pub id: String,
134 pub path: String,
136 pub files: Vec<String>,
138 pub content: Vec<u8>,
141}
142
143pub trait BundleWriter {
145 fn id(&self) -> &'static str;
147 fn write(
155 &self,
156 manifest: &PackManifest,
157 members: &[crate::adapter::ResolvedCapability],
158 ) -> Result<BundleOutput>;
159}
160
161pub fn read_tree(root: &Path, relative: &Path) -> Result<(Vec<BundleFile>, Vec<String>)> {
169 let mut files = Vec::new();
170 let mut links = Vec::new();
171 walk(root, &root.join(relative), &mut files, &mut links)?;
172 files.sort_by(|a, b| a.path.cmp(&b.path));
173 links.sort();
174 Ok((files, links))
175}
176
177fn walk(
178 root: &Path,
179 current: &Path,
180 files: &mut Vec<BundleFile>,
181 links: &mut Vec<String>,
182) -> Result<()> {
183 let mut entries = fs::read_dir(current)?.collect::<std::io::Result<Vec<_>>>()?;
184 entries.sort_by_key(fs::DirEntry::file_name);
185 for entry in entries {
186 let path = entry.path();
187 if entry.file_name() == ".git" {
188 continue;
189 }
190 let relative = relative_name(root, &path)?;
191 let metadata = fs::symlink_metadata(&path)?;
192 if metadata.file_type().is_symlink() {
193 links.push(relative);
194 } else if metadata.is_dir() {
195 walk(root, &path, files, links)?;
196 } else if metadata.is_file() {
197 files.push(BundleFile {
198 path: relative,
199 bytes: fs::read(&path)?,
200 });
201 }
202 }
203 Ok(())
204}
205
206fn relative_name(root: &Path, path: &Path) -> Result<String> {
207 let relative = path
208 .strip_prefix(root)
209 .map_err(|_| TuffError::refused("bundle file escaped its root"))?;
210 Ok(relative.to_string_lossy().replace('\\', "/"))
211}
212
213pub fn bundle_path(declared: &str) -> Result<PathBuf> {
220 let trimmed = declared.trim_start_matches("./");
221 if trimmed.is_empty() || trimmed == "." {
222 return Ok(PathBuf::new());
223 }
224 let path = Path::new(trimmed);
225 if path.is_absolute()
226 || path
227 .components()
228 .any(|component| !matches!(component, Component::Normal(_)))
229 {
230 return Err(TuffError::refused(format!(
231 "bundle path '{declared}' leaves the bundle"
232 )));
233 }
234 Ok(path.to_path_buf())
235}
236
237pub fn write_source_pack(output: &Path, imported: &ImportedPack) -> Result<()> {
247 if output.exists() && (!output.is_dir() || fs::read_dir(output)?.next().is_some()) {
248 return Err(TuffError::refused(format!(
249 "import output must be missing or empty: {}",
250 output.display()
251 )));
252 }
253 let parent = output
254 .parent()
255 .filter(|parent| !parent.as_os_str().is_empty())
256 .unwrap_or_else(|| Path::new("."));
257 fs::create_dir_all(parent)?;
258 let staging = tempfile::Builder::new()
259 .prefix("tuff-import-")
260 .tempdir_in(parent)?;
261
262 let mut manifest = imported.manifest.clone();
263 manifest.capabilities.clear();
264 let mut ids = BTreeSet::new();
265 for member in &imported.members {
266 crate::manifest::validate_capability_id(&member.id)?;
267 if !ids.insert(member.id.clone()) {
268 return Err(TuffError::usage(format!(
269 "two imported members are both named '{}'",
270 member.id
271 )));
272 }
273 let folder = PathBuf::from("capabilities").join(&member.id);
274 write_file(
275 staging.path(),
276 &folder.join("tuff.toml"),
277 toml::to_string_pretty(&member.manifest)?.as_bytes(),
278 )?;
279 for file in &member.files {
280 if file.path == "tuff.toml" {
281 return Err(TuffError::refused(format!(
282 "imported member '{}' has its own tuff.toml, which Tuff writes",
283 member.id
284 )));
285 }
286 write_file(
287 staging.path(),
288 &folder.join(pack::validate_relative_path(Path::new(&file.path))?),
289 &file.bytes,
290 )?;
291 }
292 manifest.capabilities.push(PackMember {
293 path: format!("capabilities/{}", member.id),
294 });
295 }
296 for file in &imported.extra {
297 write_file(
298 staging.path(),
299 &Path::new("extra").join(pack::validate_relative_path(Path::new(&file.path))?),
300 &file.bytes,
301 )?;
302 }
303 pack::write_manifest(&staging.path().join(pack::PACK_MANIFEST_FILE), &manifest)?;
304 pack::load_pack(staging.path())?;
306
307 if output.exists() {
308 fs::remove_dir(output)?;
309 }
310 fs::rename(staging.keep(), output)?;
311 Ok(())
312}
313
314fn write_file(root: &Path, relative: &Path, bytes: &[u8]) -> Result<()> {
315 let destination = root.join(relative);
316 if destination.exists() {
317 return Err(TuffError::usage(format!(
318 "imported pack writes {} twice",
319 relative.display()
320 )));
321 }
322 if let Some(parent) = destination.parent() {
323 fs::create_dir_all(parent)?;
324 }
325 fs::write(destination, bytes)?;
326 Ok(())
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn a_declared_path_stays_inside_the_bundle() {
335 assert_eq!(
336 bundle_path("./skills/review").unwrap(),
337 PathBuf::from("skills/review")
338 );
339 assert_eq!(bundle_path(".").unwrap(), PathBuf::new());
340 assert_eq!(bundle_path("./").unwrap(), PathBuf::new());
341 for escape in ["../outside", "./a/../../b", "/etc"] {
342 assert!(bundle_path(escape).is_err(), "{escape}");
343 }
344 }
345
346 #[cfg(unix)]
347 #[test]
348 fn read_tree_reports_links_without_following_them() {
349 let temp = tempfile::tempdir().unwrap();
350 fs::create_dir_all(temp.path().join("skills/a")).unwrap();
351 fs::write(temp.path().join("skills/a/SKILL.md"), "# A\n").unwrap();
352 std::os::unix::fs::symlink("/etc/hosts", temp.path().join("skills/a/hosts")).unwrap();
353 fs::create_dir_all(temp.path().join(".git")).unwrap();
354 fs::write(temp.path().join(".git/HEAD"), "ref").unwrap();
355 let (files, links) = read_tree(temp.path(), Path::new("")).unwrap();
356 assert_eq!(
357 files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
358 ["skills/a/SKILL.md"]
359 );
360 assert_eq!(links, ["skills/a/hosts"]);
361 }
362}