kcode_k1_rust_bootstrap_archive/
lib.rs1#![doc = include_str!("../Documentation.md")]
2#![forbid(unsafe_code)]
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fs::File;
6use std::io::{Read, Write};
7use std::path::Path;
8use zip::write::SimpleFileOptions;
9use zip::{ZipArchive, ZipWriter};
10
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct Package {
13 pub directory: String,
14 pub cargo_toml: String,
15 pub documentation: String,
16 pub lib_rs: String,
17}
18
19#[derive(Clone, Debug, Default, Eq, PartialEq)]
20pub struct Archive {
21 pub packages: Vec<Package>,
22}
23
24pub fn write(path: &Path, archive: &Archive) -> Result<(), String> {
25 let mut directories = BTreeSet::new();
26 for package in &archive.packages {
27 validate_directory(&package.directory)?;
28 if !directories.insert(package.directory.clone()) {
29 return Err(format!(
30 "duplicate archive package directory {:?}",
31 package.directory
32 ));
33 }
34 }
35
36 let file = File::create(path).map_err(|error| format!("create archive: {error}"))?;
37 let mut zip = ZipWriter::new(file);
38 let options = SimpleFileOptions::default();
39 for package in &archive.packages {
40 let root = format!("packages/{}/", package.directory);
41 for (relative, bytes) in [
42 ("Cargo.toml", package.cargo_toml.as_bytes()),
43 ("Documentation.md", package.documentation.as_bytes()),
44 ("src/lib.rs", package.lib_rs.as_bytes()),
45 ] {
46 write_entry(&mut zip, &format!("{root}{relative}"), bytes, options)?;
47 }
48 }
49 zip.finish()
50 .map_err(|error| format!("finish archive: {error}"))?
51 .sync_all()
52 .map_err(|error| format!("sync archive: {error}"))
53}
54
55pub fn read(path: &Path) -> Result<Archive, String> {
56 let file = File::open(path).map_err(|error| format!("open archive: {error}"))?;
57 let mut zip = ZipArchive::new(file).map_err(|error| format!("open ZIP: {error}"))?;
58 let mut packages = BTreeMap::<String, BTreeMap<String, Vec<u8>>>::new();
59 for index in 0..zip.len() {
60 let mut entry = zip
61 .by_index(index)
62 .map_err(|error| format!("read ZIP entry {index}: {error}"))?;
63 let name = entry.name().to_owned();
64 if entry.is_dir() {
65 return Err(format!("archive contains directory entry {name:?}"));
66 }
67 let (directory, relative) = parse_path(&name)?;
68 let mut bytes = Vec::new();
69 entry
70 .read_to_end(&mut bytes)
71 .map_err(|error| format!("read archive entry {name:?}: {error}"))?;
72 let files = packages.entry(directory.to_owned()).or_default();
73 if files.insert(relative.to_owned(), bytes).is_some() {
74 return Err(format!("archive contains duplicate entry {name:?}"));
75 }
76 }
77
78 let mut output = Vec::with_capacity(packages.len());
79 for (directory, mut files) in packages {
80 let cargo_toml = take_utf8(&mut files, &directory, "Cargo.toml")?;
81 let documentation = take_utf8(&mut files, &directory, "Documentation.md")?;
82 let lib_rs = take_utf8(&mut files, &directory, "src/lib.rs")?;
83 if let Some(extra) = files.keys().next() {
84 return Err(format!(
85 "package {directory:?} contains unexpected file {extra:?}"
86 ));
87 }
88 output.push(Package {
89 directory,
90 cargo_toml,
91 documentation,
92 lib_rs,
93 });
94 }
95 Ok(Archive { packages: output })
96}
97
98fn parse_path(name: &str) -> Result<(&str, &str), String> {
99 let remainder = name
100 .strip_prefix("packages/")
101 .ok_or_else(|| format!("archive entry is outside packages/: {name:?}"))?;
102 let (directory, relative) = remainder
103 .split_once('/')
104 .ok_or_else(|| format!("archive entry has no package file: {name:?}"))?;
105 validate_directory(directory)?;
106 if matches!(relative, "Cargo.toml" | "Documentation.md" | "src/lib.rs") {
107 Ok((directory, relative))
108 } else {
109 Err(format!("archive contains unexpected package file {name:?}"))
110 }
111}
112
113fn validate_directory(name: &str) -> Result<(), String> {
114 let valid = !name.is_empty()
115 && name.len() <= 250
116 && name.split('-').all(|part| {
117 !part.is_empty()
118 && part
119 .bytes()
120 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
121 });
122 if valid {
123 Ok(())
124 } else {
125 Err(format!("invalid package directory {name:?}"))
126 }
127}
128
129fn take_utf8(
130 files: &mut BTreeMap<String, Vec<u8>>,
131 directory: &str,
132 relative: &str,
133) -> Result<String, String> {
134 let bytes = files
135 .remove(relative)
136 .ok_or_else(|| format!("package {directory:?} is missing {relative}"))?;
137 String::from_utf8(bytes)
138 .map_err(|_| format!("package {directory:?} file {relative} is not UTF-8"))
139}
140
141fn write_entry(
142 zip: &mut ZipWriter<File>,
143 path: &str,
144 bytes: &[u8],
145 options: SimpleFileOptions,
146) -> Result<(), String> {
147 zip.start_file(path, options)
148 .map_err(|error| format!("start archive entry {path}: {error}"))?;
149 zip.write_all(bytes)
150 .map_err(|error| format!("write archive entry {path}: {error}"))
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 fn package() -> Package {
158 Package {
159 directory: "loom".to_owned(),
160 cargo_toml: "[package]\nname='loom'\nversion='0.1.0'\n".to_owned(),
161 documentation: "docs\n".to_owned(),
162 lib_rs: "fn main() {}\n".to_owned(),
163 }
164 }
165
166 fn raw_zip(path: &Path, entries: &[(&str, &[u8])]) {
167 let file = File::create(path).unwrap();
168 let mut zip = ZipWriter::new(file);
169 for (name, bytes) in entries {
170 zip.start_file(*name, SimpleFileOptions::default()).unwrap();
171 zip.write_all(bytes).unwrap();
172 }
173 zip.finish().unwrap();
174 }
175
176 #[test]
177 fn exact_three_file_archive_round_trips_without_metadata() {
178 let directory = tempfile::tempdir().unwrap();
179 let path = directory.path().join("bootstrap.zip");
180 let archive = Archive {
181 packages: vec![package()],
182 };
183 write(&path, &archive).unwrap();
184 assert_eq!(read(&path).unwrap(), archive);
185
186 let file = File::open(path).unwrap();
187 let mut zip = ZipArchive::new(file).unwrap();
188 assert_eq!(zip.len(), 3);
189 assert!(zip.by_name("manifest.json").is_err());
190 }
191
192 #[test]
193 fn reader_rejects_missing_and_extra_package_files() {
194 let directory = tempfile::tempdir().unwrap();
195 let missing = directory.path().join("missing.zip");
196 raw_zip(
197 &missing,
198 &[
199 ("packages/loom/Cargo.toml", b"manifest"),
200 ("packages/loom/Documentation.md", b"docs"),
201 ],
202 );
203 assert!(read(&missing).unwrap_err().contains("missing src/lib.rs"));
204
205 let extra = directory.path().join("extra.zip");
206 raw_zip(&extra, &[("packages/loom/README.md", b"extra")]);
207 assert!(
208 read(&extra)
209 .unwrap_err()
210 .contains("unexpected package file")
211 );
212 }
213
214 #[test]
215 fn empty_archive_is_structurally_readable() {
216 let directory = tempfile::tempdir().unwrap();
217 let path = directory.path().join("empty.zip");
218 write(&path, &Archive::default()).unwrap();
219 assert!(read(&path).unwrap().packages.is_empty());
220 }
221}