| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | | use oxy_core::cbor::{self, Value}; |
| 14 | | use oxy_core::hash::ObjectRef; |
| 15 | | use oxy_core::repo::Repo; |
| 16 | | use std::collections::BTreeMap; |
| 17 | | use std::path::{Path, PathBuf}; |
| 18 | |
|
| 19 | |
|
| 20 | | pub const VERSION: u64 = 1; |
| 21 | |
|
| 22 | | #[derive(Debug, thiserror::Error)] |
| 23 | | pub enum Error { |
| 24 | | #[error(transparent)] |
| 25 | | Repo(#[from] oxy_core::repo::RepoError), |
| 26 | | #[error("io: {0}")] |
| 27 | | Io(#[from] std::io::Error), |
| 28 | | #[error("not a canonical artifact encoding: {0}")] |
| 29 | | Cbor(#[from] oxy_core::cbor::CborError), |
| 30 | | #[error("{0}")] |
| 31 | | Bad(String), |
| 32 | | } |
| 33 | |
|
| 34 | | pub type Result<T> = std::result::Result<T, Error>; |
| 35 | |
|
| 36 | 8× | fn bad<T>(msg: impl Into<String>) -> Result<T> { |
| 37 | 8× | Err(Error::Bad(msg.into())) |
| 38 | 8× | } |
| 39 | |
|
| 40 | |
|
| 41 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 42 | | pub enum Kind { |
| 43 | | Container, |
| 44 | | RunnerImage, |
| 45 | | Package, |
| 46 | | Archive, |
| 47 | | Report, |
| 48 | | } |
| 49 | |
|
| 50 | | impl Kind { |
| 51 | | pub const ALL: [Kind; 5] = [ |
| 52 | | Kind::Container, |
| 53 | | Kind::RunnerImage, |
| 54 | | Kind::Package, |
| 55 | | Kind::Archive, |
| 56 | | Kind::Report, |
| 57 | | ]; |
| 58 | |
|
| 59 | 57× | pub fn as_str(self) -> &'static str { |
| 60 | 57× | match self { |
| 61 | 13× | Kind::Container => "container", |
| 62 | 15× | Kind::RunnerImage => "runner-image", |
| 63 | 15× | Kind::Package => "package", |
| 64 | 10× | Kind::Archive => "archive", |
| 65 | 4× | Kind::Report => "report", |
| 66 | | } |
| 67 | 57× | } |
| 68 | |
|
| 69 | 11× | pub fn parse(s: &str) -> Result<Kind> { |
| 70 | 39× | Kind::ALL.into_iter().find(|k| k.as_str() == s).map_or_else( |
| 71 | 2× | || { |
| 72 | 2× | bad(format!( |
| 73 | | "{s:?} is not a kind of artifact: {}", |
| 74 | 10× | Kind::ALL.map(|k| k.as_str()).join(", ") |
| 75 | | )) |
| 76 | 2× | }, |
| 77 | | Ok, |
| 78 | | ) |
| 79 | 11× | } |
| 80 | | } |
| 81 | |
|
| 82 | |
|
| 83 | |
|
| 84 | | pub const MODE_FILE: u32 = 0o100644; |
| 85 | | pub const MODE_EXEC: u32 = 0o100755; |
| 86 | | pub const MODE_LINK: u32 = 0o120000; |
| 87 | |
|
| 88 | |
|
| 89 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 90 | | pub struct Entry { |
| 91 | | |
| 92 | | pub path: String, |
| 93 | | pub mode: u32, |
| 94 | | pub blob: ObjectRef, |
| 95 | | pub size: u64, |
| 96 | | } |
| 97 | |
|
| 98 | |
|
| 99 | | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 100 | | pub struct DirTree { |
| 101 | | pub entries: Vec<Entry>, |
| 102 | | } |
| 103 | |
|
| 104 | 30× | fn path_ok(p: &str) -> bool { |
| 105 | 30× | !p.is_empty() |
| 106 | 30× | && !p.starts_with('/') |
| 107 | 40× | && p.split('/').all(|s| !s.is_empty() && s != "." && s != "..") |
| 108 | 30× | } |
| 109 | |
|
| 110 | 17× | fn obj(r: &ObjectRef) -> Value { |
| 111 | 17× | Value::Bytes(r.0.to_vec()) |
| 112 | 17× | } |
| 113 | |
|
| 114 | 36× | fn get_obj(v: &Value, what: &str) -> Result<ObjectRef> { |
| 115 | 36× | match v.as_bytes() { |
| 116 | 36× | Some(b) if b.len() == 32 => { |
| 117 | 36× | let mut a = [0u8; 32]; |
| 118 | 36× | a.copy_from_slice(b); |
| 119 | 36× | Ok(ObjectRef(a)) |
| 120 | | } |
| 121 | 0× | _ => bad(format!("{what} is not an object reference")), |
| 122 | | } |
| 123 | 36× | } |
| 124 | |
|
| 125 | 64× | fn get_text(v: &Value, what: &str) -> Result<String> { |
| 126 | 64× | v.as_text() |
| 127 | 64× | .map(str::to_string) |
| 128 | 64× | .map_or_else(|| bad(format!("{what} is not text")), Ok) |
| 129 | 64× | } |
| 130 | |
|
| 131 | 65× | fn get_uint(v: &Value, what: &str) -> Result<u64> { |
| 132 | 65× | v.as_uint() |
| 133 | 65× | .map_or_else(|| bad(format!("{what} is not a number")), Ok) |
| 134 | 65× | } |
| 135 | |
|
| 136 | | impl DirTree { |
| 137 | 4× | pub fn encode(&self) -> Vec<u8> { |
| 138 | 4× | let entries = self |
| 139 | 4× | .entries |
| 140 | 4× | .iter() |
| 141 | 9× | .map(|e| { |
| 142 | 9× | Value::Array(vec![ |
| 143 | 9× | Value::Text(e.path.clone()), |
| 144 | 9× | Value::Uint(e.mode as u64), |
| 145 | 9× | obj(&e.blob), |
| 146 | 9× | Value::Uint(e.size), |
| 147 | 9× | ]) |
| 148 | 9× | }) |
| 149 | 4× | .collect(); |
| 150 | 4× | cbor::encode(&Value::map([ |
| 151 | 4× | (0, Value::Uint(VERSION)), |
| 152 | 4× | (1, Value::Array(entries)), |
| 153 | 4× | ])) |
| 154 | 4× | } |
| 155 | |
|
| 156 | | |
| 157 | | |
| 158 | 14× | pub fn decode(bytes: &[u8]) -> Result<DirTree> { |
| 159 | 14× | let v = cbor::decode(bytes)?; |
| 160 | 14× | let m = v.as_map().map_or_else(|| bad("a tree is a map"), Ok)?; |
| 161 | 14× | if m.get(&0).and_then(Value::as_uint) != Some(VERSION) { |
| 162 | 0× | return bad(format!( |
| 163 | | "tree version {:?} is not known; this reads {VERSION}", |
| 164 | 0× | m.get(&0) |
| 165 | | )); |
| 166 | 14× | } |
| 167 | 14× | let mut entries = Vec::new(); |
| 168 | 30× | for item in m.get(&1).and_then(Value::as_array).unwrap_or_default() { |
| 169 | 30× | let [p, mode, blob, size] = item.as_array().unwrap_or_default() else { |
| 170 | 0× | return bad("a tree entry is [path, mode, blob, size]"); |
| 171 | | }; |
| 172 | 30× | let path = get_text(p, "a path")?; |
| 173 | 30× | let mode = get_uint(mode, "a mode")? as u32; |
| 174 | 30× | if !path_ok(&path) { |
| 175 | 1× | return bad(format!("{path:?} is not a clean relative path")); |
| 176 | 29× | } |
| 177 | 29× | if ![MODE_FILE, MODE_EXEC, MODE_LINK].contains(&mode) { |
| 178 | 1× | return bad(format!( |
| 179 | | "{path}: mode {mode:o} is not a file, an executable or a link" |
| 180 | | )); |
| 181 | 28× | } |
| 182 | 28× | if entries.last().is_some_and(|l: &Entry| l.path >= path) { |
| 183 | 1× | return bad(format!( |
| 184 | | "{path}: entries are not in path order, or one is there twice" |
| 185 | | )); |
| 186 | 27× | } |
| 187 | 27× | entries.push(Entry { |
| 188 | 27× | path, |
| 189 | 27× | mode, |
| 190 | 27× | blob: get_obj(blob, "a blob")?, |
| 191 | 27× | size: get_uint(size, "a size")?, |
| 192 | | }); |
| 193 | | } |
| 194 | 11× | Ok(DirTree { entries }) |
| 195 | 14× | } |
| 196 | | } |
| 197 | |
|
| 198 | |
|
| 199 | | #[derive(Clone, Debug, PartialEq, Eq)] |
| 200 | | pub struct Artifact { |
| 201 | | pub kind: Kind, |
| 202 | | |
| 203 | | pub arch: Option<String>, |
| 204 | | |
| 205 | | pub os: Option<String>, |
| 206 | | |
| 207 | | pub tree: ObjectRef, |
| 208 | | |
| 209 | | pub entrypoint: Option<Vec<String>>, |
| 210 | | pub env: BTreeMap<String, String>, |
| 211 | | pub labels: BTreeMap<String, String>, |
| 212 | | |
| 213 | | pub total_size: u64, |
| 214 | | |
| 215 | | pub receipt: Option<ObjectRef>, |
| 216 | | } |
| 217 | |
|
| 218 | 12× | fn pairs(m: &BTreeMap<String, String>) -> Value { |
| 219 | 12× | if m.is_empty() { |
| 220 | 6× | return Value::Null; |
| 221 | 6× | } |
| 222 | | Value::Array( |
| 223 | 6× | m.iter() |
| 224 | 6× | .map(|(k, v)| Value::Array(vec![Value::Text(k.clone()), Value::Text(v.clone())])) |
| 225 | 6× | .collect(), |
| 226 | | ) |
| 227 | 12× | } |
| 228 | |
|
| 229 | 16× | fn get_pairs(v: Option<&Value>, what: &str) -> Result<BTreeMap<String, String>> { |
| 230 | 16× | let mut out = BTreeMap::new(); |
| 231 | 16× | let Some(v) = v.filter(|v| !v.is_null()) else { |
| 232 | 8× | return Ok(out); |
| 233 | | }; |
| 234 | 8× | for p in v |
| 235 | 8× | .as_array() |
| 236 | 8× | .map_or_else(|| bad(format!("{what} is a list of pairs")), Ok)? |
| 237 | | { |
| 238 | 8× | let [k, val] = p.as_array().unwrap_or_default() else { |
| 239 | 0× | return bad(format!("{what}: a pair is [key, value]")); |
| 240 | | }; |
| 241 | 8× | let k = get_text(k, what)?; |
| 242 | 8× | if out.insert(k.clone(), get_text(val, what)?).is_some() { |
| 243 | 0× | return bad(format!("{what}: {k} is there twice")); |
| 244 | 8× | } |
| 245 | | } |
| 246 | 8× | Ok(out) |
| 247 | 16× | } |
| 248 | |
|
| 249 | 12× | fn opt_text(v: &Option<String>) -> Value { |
| 250 | 12× | v.as_ref().map_or(Value::Null, |s| Value::Text(s.clone())) |
| 251 | 12× | } |
| 252 | |
|
| 253 | | impl Artifact { |
| 254 | | |
| 255 | 6× | pub fn encode(&self) -> Vec<u8> { |
| 256 | 6× | let entry = self.entrypoint.as_ref().map_or(Value::Null, |a| { |
| 257 | 2× | Value::Array(a.iter().cloned().map(Value::Text).collect()) |
| 258 | 2× | }); |
| 259 | 6× | cbor::encode(&Value::map([ |
| 260 | 6× | (0, Value::Uint(VERSION)), |
| 261 | 6× | (1, Value::Text(self.kind.as_str().into())), |
| 262 | 6× | (2, opt_text(&self.arch)), |
| 263 | 6× | (3, opt_text(&self.os)), |
| 264 | 6× | (4, obj(&self.tree)), |
| 265 | 6× | (5, entry), |
| 266 | 6× | (6, pairs(&self.env)), |
| 267 | 6× | (7, pairs(&self.labels)), |
| 268 | 6× | (8, Value::Uint(self.total_size)), |
| 269 | 6× | (9, self.receipt.as_ref().map_or(Value::Null, obj)), |
| 270 | 6× | ])) |
| 271 | 6× | } |
| 272 | |
|
| 273 | 10× | pub fn decode(bytes: &[u8]) -> Result<Artifact> { |
| 274 | 10× | let v = cbor::decode(bytes)?; |
| 275 | 10× | let m = v.as_map().map_or_else(|| bad("an artifact is a map"), Ok)?; |
| 276 | 10× | if m.get(&0).and_then(Value::as_uint) != Some(VERSION) { |
| 277 | 1× | return bad(format!( |
| 278 | | "artifact version {:?} is not known; this reads {VERSION}", |
| 279 | 1× | m.get(&0) |
| 280 | | )); |
| 281 | 9× | } |
| 282 | 82× | if let Some(k) = m.keys().find(|k| **k > 9) { |
| 283 | 1× | return bad(format!("key {k} is not part of an artifact")); |
| 284 | 8× | } |
| 285 | 24× | let text = |k: u64, what: &str| -> Result<Option<String>> { |
| 286 | 24× | match m.get(&k) { |
| 287 | 7× | None | Some(Value::Null) => Ok(None), |
| 288 | 17× | Some(v) => get_text(v, what).map(Some), |
| 289 | | } |
| 290 | 24× | }; |
| 291 | 8× | let entrypoint = match m.get(&5) { |
| 292 | 7× | None | Some(Value::Null) => None, |
| 293 | 1× | Some(v) => Some( |
| 294 | 1× | v.as_array() |
| 295 | 1× | .unwrap_or_default() |
| 296 | 1× | .iter() |
| 297 | 1× | .map(|a| get_text(a, "the entrypoint")) |
| 298 | 1× | .collect::<Result<_>>()?, |
| 299 | | ), |
| 300 | | }; |
| 301 | 8× | let receipt = match m.get(&9) { |
| 302 | 7× | None | Some(Value::Null) => None, |
| 303 | 1× | Some(v) => Some(get_obj(v, "the receipt")?), |
| 304 | | }; |
| 305 | | Ok(Artifact { |
| 306 | 8× | kind: Kind::parse(&text(1, "the kind")?.unwrap_or_default())?, |
| 307 | 8× | arch: text(2, "the architecture")?, |
| 308 | 8× | os: text(3, "the system")?, |
| 309 | 8× | tree: get_obj(m.get(&4).unwrap_or(&Value::Null), "the tree")?, |
| 310 | 8× | entrypoint, |
| 311 | 8× | env: get_pairs(m.get(&6), "env")?, |
| 312 | 8× | labels: get_pairs(m.get(&7), "labels")?, |
| 313 | 8× | total_size: get_uint(m.get(&8).unwrap_or(&Value::Null), "the size")?, |
| 314 | 8× | receipt, |
| 315 | | }) |
| 316 | 10× | } |
| 317 | |
|
| 318 | | |
| 319 | 2× | pub fn name(&self) -> String { |
| 320 | 2× | blake3::hash(&self.encode()).to_hex().to_string() |
| 321 | 2× | } |
| 322 | | } |
| 323 | |
|
| 324 | |
|
| 325 | | #[derive(Clone, Debug)] |
| 326 | | pub struct Spec { |
| 327 | | pub kind: Kind, |
| 328 | | pub arch: Option<String>, |
| 329 | | pub os: Option<String>, |
| 330 | | pub entrypoint: Option<Vec<String>>, |
| 331 | | pub env: BTreeMap<String, String>, |
| 332 | | pub labels: BTreeMap<String, String>, |
| 333 | | } |
| 334 | |
|
| 335 | | impl Spec { |
| 336 | 2× | pub fn new(kind: Kind) -> Spec { |
| 337 | 2× | Spec { |
| 338 | 2× | kind, |
| 339 | 2× | arch: None, |
| 340 | 2× | os: None, |
| 341 | 2× | entrypoint: None, |
| 342 | 2× | env: BTreeMap::new(), |
| 343 | 2× | labels: BTreeMap::new(), |
| 344 | 2× | } |
| 345 | 2× | } |
| 346 | | } |
| 347 | |
|
| 348 | |
|
| 349 | | #[derive(Clone, Debug)] |
| 350 | | pub struct Kept { |
| 351 | | pub name: String, |
| 352 | | pub artifact: Artifact, |
| 353 | | |
| 354 | | pub blob: ObjectRef, |
| 355 | | } |
| 356 | |
|
| 357 | 24× | fn kept_dir(repo: &Repo) -> PathBuf { |
| 358 | 24× | repo.oxy_dir().join("artifacts") |
| 359 | 24× | } |
| 360 | |
|
| 361 | |
|
| 362 | |
|
| 363 | 3× | fn walk(dir: &Path) -> Result<Vec<(String, PathBuf, std::fs::Metadata)>> { |
| 364 | 3× | let mut out = Vec::new(); |
| 365 | 3× | let mut stack = vec![(dir.to_path_buf(), String::new())]; |
| 366 | 9× | while let Some((d, rel)) = stack.pop() { |
| 367 | 11× | for e in std::fs::read_dir(&d)? { |
| 368 | 11× | let e = e?; |
| 369 | 11× | let name = e |
| 370 | 11× | .file_name() |
| 371 | 11× | .into_string() |
| 372 | 11× | .map_err(|n| Error::Bad(format!("{n:?} is not UTF-8")))?; |
| 373 | 11× | let path = if rel.is_empty() { |
| 374 | 8× | name.clone() |
| 375 | | } else { |
| 376 | 3× | format!("{rel}/{name}") |
| 377 | | }; |
| 378 | 11× | let md = std::fs::symlink_metadata(e.path())?; |
| 379 | 11× | if md.is_dir() { |
| 380 | 3× | if name != ".oxy" && name != ".git" { |
| 381 | 3× | stack.push((e.path(), path)); |
| 382 | 3× | } |
| 383 | 8× | } else if md.is_file() || md.file_type().is_symlink() { |
| 384 | 8× | out.push((path, e.path(), md)); |
| 385 | 8× | } |
| 386 | | } |
| 387 | | } |
| 388 | 7× | out.sort_by(|a, b| a.0.cmp(&b.0)); |
| 389 | 3× | Ok(out) |
| 390 | 3× | } |
| 391 | |
|
| 392 | | #[cfg(unix)] |
| 393 | 8× | fn mode_of(md: &std::fs::Metadata) -> u32 { |
| 394 | | use std::os::unix::fs::PermissionsExt; |
| 395 | 8× | if md.file_type().is_symlink() { |
| 396 | 2× | MODE_LINK |
| 397 | 6× | } else if md.permissions().mode() & 0o111 != 0 { |
| 398 | 2× | MODE_EXEC |
| 399 | | } else { |
| 400 | 4× | MODE_FILE |
| 401 | | } |
| 402 | 8× | } |
| 403 | |
|
| 404 | | #[cfg(not(unix))] |
| 405 | | fn mode_of(md: &std::fs::Metadata) -> u32 { |
| 406 | | if md.file_type().is_symlink() { |
| 407 | | MODE_LINK |
| 408 | | } else { |
| 409 | | MODE_FILE |
| 410 | | } |
| 411 | | } |
| 412 | |
|
| 413 | |
|
| 414 | |
|
| 415 | |
|
| 416 | |
|
| 417 | 3× | pub fn pack(repo: &Repo, dir: &Path, spec: &Spec) -> Result<Kept> { |
| 418 | 3× | if !dir.is_dir() { |
| 419 | 0× | return bad(format!("{} is not a directory", dir.display())); |
| 420 | 3× | } |
| 421 | 3× | let mut tree = DirTree::default(); |
| 422 | 8× | for (path, full, md) in walk(dir)? { |
| 423 | 8× | let mode = mode_of(&md); |
| 424 | 8× | let bytes = if mode == MODE_LINK { |
| 425 | 2× | std::fs::read_link(&full)? |
| 426 | 2× | .to_string_lossy() |
| 427 | 2× | .into_owned() |
| 428 | 2× | .into_bytes() |
| 429 | | } else { |
| 430 | 6× | std::fs::read(&full)? |
| 431 | | }; |
| 432 | 8× | let blob = repo.store_blob(&bytes)?; |
| 433 | 8× | tree.entries.push(Entry { |
| 434 | 8× | path, |
| 435 | 8× | mode, |
| 436 | 8× | blob, |
| 437 | 8× | size: bytes.len() as u64, |
| 438 | 8× | }); |
| 439 | | } |
| 440 | 3× | let artifact = Artifact { |
| 441 | 3× | kind: spec.kind, |
| 442 | 3× | arch: spec.arch.clone(), |
| 443 | 3× | os: spec.os.clone(), |
| 444 | 3× | tree: repo.store_blob(&tree.encode())?, |
| 445 | 3× | entrypoint: spec.entrypoint.clone(), |
| 446 | 3× | env: spec.env.clone(), |
| 447 | 3× | labels: spec.labels.clone(), |
| 448 | 3× | total_size: tree.entries.iter().map(|e| e.size).sum(), |
| 449 | 3× | receipt: None, |
| 450 | | }; |
| 451 | 3× | let bytes = artifact.encode(); |
| 452 | 3× | let blob = repo.store_blob(&bytes)?; |
| 453 | 3× | let name = blake3::hash(&bytes).to_hex().to_string(); |
| 454 | 3× | std::fs::create_dir_all(kept_dir(repo))?; |
| 455 | 3× | std::fs::write(kept_dir(repo).join(&name), blob.to_hex())?; |
| 456 | 3× | Ok(Kept { |
| 457 | 3× | name, |
| 458 | 3× | artifact, |
| 459 | 3× | blob, |
| 460 | 3× | }) |
| 461 | 3× | } |
| 462 | |
|
| 463 | |
|
| 464 | 11× | pub fn list(repo: &Repo) -> Result<Vec<String>> { |
| 465 | 11× | let mut out = Vec::new(); |
| 466 | 11× | match std::fs::read_dir(kept_dir(repo)) { |
| 467 | 11× | Ok(rd) => { |
| 468 | 11× | for e in rd { |
| 469 | 11× | let n = e?.file_name().to_string_lossy().into_owned(); |
| 470 | 704× | if n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 471 | 11× | out.push(n); |
| 472 | 11× | } |
| 473 | | } |
| 474 | | } |
| 475 | 0× | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 476 | 0× | Err(e) => return Err(e.into()), |
| 477 | | } |
| 478 | 11× | out.sort(); |
| 479 | 11× | Ok(out) |
| 480 | 11× | } |
| 481 | |
|
| 482 | |
|
| 483 | |
|
| 484 | 7× | pub fn open(repo: &Repo, name: &str) -> Result<Kept> { |
| 485 | 7× | let name = name.to_ascii_lowercase(); |
| 486 | 7× | if name.len() < 6 { |
| 487 | 0× | return bad("name an artifact by at least six characters of its name"); |
| 488 | 7× | } |
| 489 | 7× | let found: Vec<String> = list(repo)? |
| 490 | 7× | .into_iter() |
| 491 | 7× | .filter(|n| n.starts_with(&name)) |
| 492 | 7× | .collect(); |
| 493 | 7× | let full = match found.as_slice() { |
| 494 | 7× | [one] => one.clone(), |
| 495 | 0× | [] => { |
| 496 | 0× | return bad(format!( |
| 497 | | "no artifact {name} here; `oxy artifact list` shows them" |
| 498 | | )) |
| 499 | | } |
| 500 | | _ => { |
| 501 | 0× | return bad(format!( |
| 502 | | "{name} names {} artifacts: give more of the name", |
| 503 | 0× | found.len() |
| 504 | | )) |
| 505 | | } |
| 506 | | }; |
| 507 | 7× | let hex = std::fs::read_to_string(kept_dir(repo).join(&full))?; |
| 508 | 7× | let blob = ObjectRef::from_hex(hex.trim()).map_or_else( |
| 509 | 0× | || bad(format!("artifact {full}: its record is damaged")), |
| 510 | | Ok, |
| 511 | 0× | )?; |
| 512 | 7× | let bytes = repo.read_blob(&blob)?; |
| 513 | 7× | if blake3::hash(&bytes).to_hex().as_str() != full { |
| 514 | 0× | return bad(format!( |
| 515 | | "artifact {full}: its encoding no longer hashes to its name" |
| 516 | | )); |
| 517 | 7× | } |
| 518 | | Ok(Kept { |
| 519 | 7× | name: full, |
| 520 | 7× | artifact: Artifact::decode(&bytes)?, |
| 521 | 7× | blob, |
| 522 | | }) |
| 523 | 7× | } |
| 524 | |
|
| 525 | |
|
| 526 | 10× | pub fn tree(repo: &Repo, a: &Artifact) -> Result<DirTree> { |
| 527 | 10× | DirTree::decode(&repo.read_blob(&a.tree)?) |
| 528 | 10× | } |
| 529 | |
|
| 530 | |
|
| 531 | |
|
| 532 | 3× | pub fn verify(repo: &Repo, k: &Kept) -> Result<usize> { |
| 533 | 3× | let t = tree(repo, &k.artifact)?; |
| 534 | 3× | let mut total = 0; |
| 535 | 8× | for e in &t.entries { |
| 536 | 8× | let n = repo.read_blob(&e.blob)?.len() as u64; |
| 537 | 8× | if n != e.size { |
| 538 | 0× | return bad(format!( |
| 539 | | "{}: {n} bytes, but the tree says {}", |
| 540 | | e.path, e.size |
| 541 | | )); |
| 542 | 8× | } |
| 543 | 8× | total += n; |
| 544 | | } |
| 545 | 3× | if total != k.artifact.total_size { |
| 546 | 0× | return bad(format!( |
| 547 | | "the files are {total} bytes together, but the artifact says {}", |
| 548 | | k.artifact.total_size |
| 549 | | )); |
| 550 | 3× | } |
| 551 | 3× | Ok(t.entries.len()) |
| 552 | 3× | } |
| 553 | |
|
| 554 | |
|
| 555 | 3× | pub fn unpack(repo: &Repo, k: &Kept, dest: &Path) -> Result<usize> { |
| 556 | 3× | if dest.exists() && std::fs::read_dir(dest)?.next().is_some() { |
| 557 | 1× | return bad(format!("{} is not empty", dest.display())); |
| 558 | 2× | } |
| 559 | 2× | let t = tree(repo, &k.artifact)?; |
| 560 | 5× | for e in &t.entries { |
| 561 | 5× | let out = dest.join(&e.path); |
| 562 | 5× | if let Some(p) = out.parent() { |
| 563 | 5× | std::fs::create_dir_all(p)?; |
| 564 | 0× | } |
| 565 | 5× | let bytes = repo.read_blob(&e.blob)?; |
| 566 | 5× | if e.mode == MODE_LINK { |
| 567 | | #[cfg(unix)] |
| 568 | 1× | std::os::unix::fs::symlink(String::from_utf8_lossy(&bytes).as_ref(), &out)?; |
| 569 | | #[cfg(not(unix))] |
| 570 | | std::fs::write(&out, &bytes)?; |
| 571 | 1× | continue; |
| 572 | 4× | } |
| 573 | 4× | std::fs::write(&out, &bytes)?; |
| 574 | | #[cfg(unix)] |
| 575 | 4× | if e.mode == MODE_EXEC { |
| 576 | | use std::os::unix::fs::PermissionsExt; |
| 577 | 1× | std::fs::set_permissions(&out, std::fs::Permissions::from_mode(0o755))?; |
| 578 | 3× | } |
| 579 | | } |
| 580 | 2× | Ok(t.entries.len()) |
| 581 | 3× | } |
| 582 | |
|
| 583 | |
|
| 584 | |
|
| 585 | 2× | pub fn roots(repo: &Repo) -> Result<Vec<ObjectRef>> { |
| 586 | 2× | let mut out = Vec::new(); |
| 587 | 2× | for name in list(repo)? { |
| 588 | 2× | let k = open(repo, &name)?; |
| 589 | 2× | out.push(k.blob); |
| 590 | 2× | out.push(k.artifact.tree); |
| 591 | 2× | out.extend(tree(repo, &k.artifact)?.entries.iter().map(|e| e.blob)); |
| 592 | | } |
| 593 | 2× | Ok(out) |
| 594 | 2× | } |
| 595 | |
|
| 596 | | #[cfg(test)] |
| 597 | | mod tests { |
| 598 | | use super::*; |
| 599 | |
|
| 600 | 1× | fn repo(dir: &Path) -> Repo { |
| 601 | 1× | Repo::init(&dir.join("repo")).unwrap() |
| 602 | 1× | } |
| 603 | |
|
| 604 | | #[test] |
| 605 | 1× | fn a_directory_packs_into_an_artifact_and_back() { |
| 606 | 1× | let t = tempfile::tempdir().unwrap(); |
| 607 | 1× | let r = repo(t.path()); |
| 608 | 1× | let src = t.path().join("out"); |
| 609 | 1× | std::fs::create_dir_all(src.join("bin")).unwrap(); |
| 610 | 1× | std::fs::write(src.join("README"), b"hello\n").unwrap(); |
| 611 | 1× | std::fs::write(src.join("bin/tool"), vec![7u8; 300_000]).unwrap(); |
| 612 | | #[cfg(unix)] |
| 613 | | { |
| 614 | | use std::os::unix::fs::PermissionsExt; |
| 615 | 1× | std::fs::set_permissions(src.join("bin/tool"), std::fs::Permissions::from_mode(0o755)) |
| 616 | 1× | .unwrap(); |
| 617 | 1× | std::os::unix::fs::symlink("bin/tool", src.join("tool")).unwrap(); |
| 618 | | } |
| 619 | 1× | let mut spec = Spec::new(Kind::Archive); |
| 620 | 1× | spec.arch = Some("x86_64".into()); |
| 621 | 1× | spec.labels.insert("version".into(), "0.1.0".into()); |
| 622 | 1× | let k = pack(&r, &src, &spec).unwrap(); |
| 623 | 1× | assert_eq!(k.name, k.artifact.name()); |
| 624 | 1× | assert_eq!( |
| 625 | | k.artifact.total_size, |
| 626 | 1× | 300_006 + if cfg!(unix) { 8 } else { 0 } |
| 627 | | ); |
| 628 | 1× | assert_eq!(list(&r).unwrap(), vec![k.name.clone()]); |
| 629 | |
|
| 630 | 1× | let again = open(&r, &k.name[..10]).unwrap(); |
| 631 | 1× | assert_eq!(again.artifact, k.artifact); |
| 632 | 1× | let paths: Vec<(String, u32)> = tree(&r, &again.artifact) |
| 633 | 1× | .unwrap() |
| 634 | 1× | .entries |
| 635 | 1× | .into_iter() |
| 636 | 3× | .map(|e| (e.path, e.mode)) |
| 637 | 1× | .collect(); |
| 638 | 1× | assert_eq!(paths[0], ("README".into(), MODE_FILE)); |
| 639 | 1× | assert_eq!( |
| 640 | 1× | paths[1], |
| 641 | | ( |
| 642 | 1× | "bin/tool".into(), |
| 643 | 1× | if cfg!(unix) { MODE_EXEC } else { MODE_FILE } |
| 644 | | ) |
| 645 | | ); |
| 646 | 1× | assert_eq!(verify(&r, &again).unwrap(), paths.len()); |
| 647 | |
|
| 648 | 1× | let dest = t.path().join("back"); |
| 649 | 1× | unpack(&r, &again, &dest).unwrap(); |
| 650 | 1× | assert_eq!( |
| 651 | 1× | std::fs::read(dest.join("bin/tool")).unwrap(), |
| 652 | 1× | vec![7u8; 300_000] |
| 653 | | ); |
| 654 | | #[cfg(unix)] |
| 655 | 1× | assert_eq!( |
| 656 | 1× | std::fs::read_link(dest.join("tool")).unwrap(), |
| 657 | 1× | Path::new("bin/tool") |
| 658 | | ); |
| 659 | 1× | assert!(unpack(&r, &again, &dest) |
| 660 | 1× | .unwrap_err() |
| 661 | 1× | .to_string() |
| 662 | 1× | .contains("not empty")); |
| 663 | |
|
| 664 | | |
| 665 | 1× | assert_eq!(pack(&r, &src, &spec).unwrap().name, k.name); |
| 666 | 1× | let keep = roots(&r).unwrap(); |
| 667 | 1× | assert!(keep.contains(&k.blob) && keep.contains(&k.artifact.tree)); |
| 668 | 5× | r.gc_keeping(true, &keep, &mut |_| {}).unwrap(); |
| 669 | 1× | assert_eq!( |
| 670 | 1× | verify(&r, &open(&r, &k.name).unwrap()).unwrap(), |
| 671 | 1× | paths.len() |
| 672 | | ); |
| 673 | 1× | } |
| 674 | |
|
| 675 | | #[test] |
| 676 | 1× | fn encodings_are_canonical_and_checked() { |
| 677 | 1× | let a = Artifact { |
| 678 | 1× | kind: Kind::RunnerImage, |
| 679 | 1× | arch: Some("riscv64".into()), |
| 680 | 1× | os: Some("linux".into()), |
| 681 | 1× | tree: ObjectRef([1; 32]), |
| 682 | 1× | entrypoint: Some(vec!["/sbin/init".into()]), |
| 683 | 1× | env: [("PATH".to_string(), "/bin".to_string())].into(), |
| 684 | 1× | labels: BTreeMap::new(), |
| 685 | 1× | total_size: 42, |
| 686 | 1× | receipt: Some(ObjectRef([2; 32])), |
| 687 | 1× | }; |
| 688 | 1× | let bytes = a.encode(); |
| 689 | 1× | assert_eq!(Artifact::decode(&bytes).unwrap(), a); |
| 690 | 1× | assert_eq!(a.name(), blake3::hash(&bytes).to_hex().to_string()); |
| 691 | 1× | assert!(Kind::parse("tarball") |
| 692 | 1× | .unwrap_err() |
| 693 | 1× | .to_string() |
| 694 | 1× | .contains("runner-image")); |
| 695 | |
|
| 696 | 2× | let wrong = |v: Value| Artifact::decode(&cbor::encode(&v)).unwrap_err().to_string(); |
| 697 | 1× | assert!(wrong(Value::map([(0, Value::Uint(2))])).contains("version")); |
| 698 | 1× | assert!(wrong(Value::map([(0, Value::Uint(1)), (10, Value::Null)])).contains("key 10")); |
| 699 | |
|
| 700 | 1× | let t = DirTree { |
| 701 | 1× | entries: vec![Entry { |
| 702 | 1× | path: "a".into(), |
| 703 | 1× | mode: MODE_FILE, |
| 704 | 1× | blob: ObjectRef([3; 32]), |
| 705 | 1× | size: 1, |
| 706 | 1× | }], |
| 707 | 1× | }; |
| 708 | 1× | assert_eq!(DirTree::decode(&t.encode()).unwrap(), t); |
| 709 | 4× | let entry = |p: &str, mode: u32| { |
| 710 | 4× | Value::Array(vec![ |
| 711 | 4× | Value::Text(p.into()), |
| 712 | 4× | Value::Uint(mode as u64), |
| 713 | 4× | Value::Bytes(vec![0; 32]), |
| 714 | 4× | Value::Uint(0), |
| 715 | 4× | ]) |
| 716 | 4× | }; |
| 717 | 3× | let tree = |items: Vec<Value>| { |
| 718 | 3× | DirTree::decode(&cbor::encode(&Value::map([ |
| 719 | 3× | (0, Value::Uint(1)), |
| 720 | 3× | (1, Value::Array(items)), |
| 721 | 3× | ]))) |
| 722 | 3× | .unwrap_err() |
| 723 | 3× | .to_string() |
| 724 | 3× | }; |
| 725 | 1× | assert!(tree(vec![entry("../x", MODE_FILE)]).contains("clean")); |
| 726 | 1× | assert!(tree(vec![entry("b", MODE_FILE), entry("a", MODE_FILE)]).contains("order")); |
| 727 | 1× | assert!(tree(vec![entry("a", 0o040000)]).contains("mode")); |
| 728 | 1× | } |
| 729 | | } |