1use std::path::{Path, PathBuf};
4
5use thiserror::Error;
6
7use super::layout;
8use super::libsystem::{self, LibsystemInstall, LibsystemOrigin};
9use super::registry;
10
11#[derive(Debug, Error)]
13pub enum BottleError {
14 #[error(
16 "a bottle already exists at {path}\n\
17 create a new one only after deleting the current bottle:\n\
18 kh bottle destroy"
19 )]
20 AlreadyExists {
21 path: PathBuf,
23 },
24
25 #[error("no bottle is registered (nothing to destroy)")]
27 NotRegistered,
28
29 #[error("path is not a kakehashi bottle (missing marker): {0}")]
31 NotABottle(PathBuf),
32
33 #[error("destroy cancelled (confirmation required)")]
35 NotConfirmed,
36
37 #[error("libSystem source not found: {0}")]
39 LibsystemNotFound(PathBuf),
40
41 #[error(transparent)]
43 Io(#[from] std::io::Error),
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48#[allow(clippy::struct_excessive_bools)] pub struct BottleStatus {
50 pub path: PathBuf,
52 pub exists: bool,
54 pub valid_marker: bool,
56 pub libsystem: bool,
58 pub libcxx_alias: bool,
60}
61
62#[derive(Debug, Clone, Default)]
64pub struct CreateOptions<'a> {
65 pub path: Option<&'a Path>,
67 pub libsystem: Option<&'a Path>,
69 pub skip_libsystem: bool,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct CreateResult {
76 pub path: PathBuf,
78 pub libsystem: Option<LibsystemInstall>,
80}
81
82pub fn create(path: Option<&Path>) -> Result<CreateResult, BottleError> {
93 create_with(&CreateOptions {
94 path,
95 ..CreateOptions::default()
96 })
97}
98
99pub fn create_with(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
101 if let Some(active) = registry::read_active()? {
102 if active.exists() {
103 return Err(BottleError::AlreadyExists { path: active });
104 }
105 registry::clear_active()?;
107 }
108
109 let target = match opts.path {
110 Some(p) => absolute(p)?,
111 None => registry::default_bottle_path()?,
112 };
113
114 if layout::is_bottle_root(&target) {
115 return Err(BottleError::AlreadyExists { path: target });
119 }
120
121 if target.exists() && target.read_dir()?.next().is_some() {
122 return Err(BottleError::Io(std::io::Error::new(
124 std::io::ErrorKind::AlreadyExists,
125 format!(
126 "refusing to create bottle in non-empty directory: {}",
127 target.display()
128 ),
129 )));
130 }
131
132 layout::materialize(&target)?;
133
134 let libsystem = match install_libsystem_for_create(&target, opts) {
135 Ok(v) => v,
136 Err(err) => {
137 drop(layout::remove_tree(&target));
138 return Err(err);
139 }
140 };
141
142 registry::write_active(&target)?;
143 Ok(CreateResult {
144 path: target,
145 libsystem,
146 })
147}
148
149fn install_libsystem_for_create(
150 target: &Path,
151 opts: &CreateOptions<'_>,
152) -> Result<Option<LibsystemInstall>, BottleError> {
153 if opts.skip_libsystem {
154 return Ok(None);
155 }
156 if let Some(explicit) = opts.libsystem {
157 if !explicit.is_file() {
158 return Err(BottleError::LibsystemNotFound(explicit.to_path_buf()));
159 }
160 return Ok(Some(libsystem::install(
161 target,
162 explicit,
163 LibsystemOrigin::Explicit,
164 )?));
165 }
166 if let Some((src, origin)) = libsystem::discover(None) {
167 return Ok(Some(libsystem::install(target, &src, origin)?));
168 }
169 Ok(None)
170}
171
172pub fn destroy(confirmed: bool) -> Result<PathBuf, BottleError> {
177 let Some(path) = registry::read_active()? else {
178 return Err(BottleError::NotRegistered);
179 };
180
181 if !confirmed {
182 return Err(BottleError::NotConfirmed);
183 }
184
185 if path.exists() {
186 if layout::is_bottle_root(&path) {
187 layout::remove_tree(&path)?;
188 } else if path.is_dir() {
189 return Err(BottleError::NotABottle(path));
191 }
192 }
194
195 registry::clear_active()?;
196 Ok(path)
197}
198
199pub fn status() -> Result<Option<BottleStatus>, BottleError> {
201 let Some(path) = registry::read_active()? else {
202 return Ok(None);
203 };
204 let exists = path.exists();
205 let valid_marker = exists && layout::is_bottle_root(&path);
206 let libsystem = exists && path.join(libsystem::GUEST_LIBSYSTEM_REL).is_file();
207 let libcxx_alias = exists && layout::has_libcxx_symlink(&path);
208 Ok(Some(BottleStatus {
209 path,
210 exists,
211 valid_marker,
212 libsystem,
213 libcxx_alias,
214 }))
215}
216
217pub fn active_root() -> Result<Option<PathBuf>, BottleError> {
221 match status()? {
222 Some(s) if s.exists && s.valid_marker => Ok(Some(s.path)),
223 _ => Ok(None),
224 }
225}
226
227pub fn ensure(opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
241 if let Some(path) = active_root()? {
242 return refresh_bottle(&path, opts);
243 }
244
245 if let Some(p) = opts.path {
248 let abs = absolute(p)?;
249 if layout::is_bottle_root(&abs) {
250 return refresh_bottle(&abs, opts);
251 }
252 } else if let Ok(def) = registry::default_bottle_path()
253 && layout::is_bottle_root(&def)
254 {
255 return refresh_bottle(&def, opts);
256 }
257
258 create_with(opts)
259}
260
261fn refresh_bottle(path: &Path, opts: &CreateOptions<'_>) -> Result<CreateResult, BottleError> {
262 layout::ensure_libcxx_symlink(path)?;
263 let libsystem = install_libsystem_for_create(path, opts)?;
264 registry::write_active(path)?;
265 Ok(CreateResult {
266 path: path.to_path_buf(),
267 libsystem,
268 })
269}
270
271fn absolute(path: &Path) -> Result<PathBuf, BottleError> {
272 if path.is_absolute() {
273 return Ok(path.to_path_buf());
274 }
275 let cwd = std::env::current_dir()?;
276 Ok(cwd.join(path))
277}
278
279#[cfg(test)]
280#[allow(clippy::expect_used, clippy::panic, unsafe_code)]
281mod tests {
282 use super::*;
283 use crate::bottle::registry::test_env_lock;
284 use std::sync::atomic::{AtomicU64, Ordering};
285
286 fn unique(prefix: &str) -> PathBuf {
287 static N: AtomicU64 = AtomicU64::new(0);
288 let n = N.fetch_add(1, Ordering::Relaxed);
289 std::env::temp_dir().join(format!("kh-manage-{}-{}-{n}", prefix, std::process::id()))
290 }
291
292 struct EnvGuard {
293 cfg: PathBuf,
294 data: PathBuf,
295 }
296
297 impl EnvGuard {
298 fn new() -> Self {
299 let cfg = unique("cfg");
300 let data = unique("data");
301 drop(std::fs::remove_dir_all(&cfg));
302 drop(std::fs::remove_dir_all(&data));
303 std::fs::create_dir_all(&cfg).expect("cfg");
304 std::fs::create_dir_all(&data).expect("data");
305 unsafe {
307 std::env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
308 std::env::set_var("KAKEHASHI_DATA_DIR", &data);
309 }
310 Self { cfg, data }
311 }
312 }
313
314 impl Drop for EnvGuard {
315 fn drop(&mut self) {
316 unsafe {
318 std::env::remove_var("KAKEHASHI_CONFIG_DIR");
319 std::env::remove_var("KAKEHASHI_DATA_DIR");
320 }
321 drop(std::fs::remove_dir_all(&self.cfg));
322 drop(std::fs::remove_dir_all(&self.data));
323 }
324 }
325
326 #[test]
327 fn create_default_then_second_fails() {
328 let _lock = test_env_lock();
329 let g = EnvGuard::new();
330
331 let created = create_with(&CreateOptions {
332 skip_libsystem: true,
333 ..CreateOptions::default()
334 })
335 .expect("create");
336 let path = created.path;
337 assert!(layout::is_bottle_root(&path));
338 assert_eq!(path, g.data.join("bottle"));
339 assert!(path.join("Volumes/linux").is_symlink());
340 assert!(created.libsystem.is_none());
341
342 let err = create(None).expect_err("second create");
343 assert!(matches!(err, BottleError::AlreadyExists { .. }));
344
345 let destroyed = destroy(true).expect("destroy");
346 assert_eq!(destroyed, path);
347 assert!(!path.exists());
348 assert!(status().expect("status").is_none());
349 }
350
351 #[test]
352 fn create_custom_path_and_rename_survives_registry_update() {
353 let _lock = test_env_lock();
354 let _g = EnvGuard::new();
355
356 let custom = unique("custom-bottle-name");
357 let created = create_with(&CreateOptions {
358 path: Some(&custom),
359 skip_libsystem: true,
360 ..CreateOptions::default()
361 })
362 .expect("create custom");
363 let path = created.path;
364 assert_eq!(path, custom);
365 assert!(layout::is_bottle_root(&path));
366
367 let renamed = unique("renamed-by-user");
369 std::fs::rename(&path, &renamed).expect("rename");
370 let st = status().expect("status").expect("some");
372 assert!(!st.exists);
373
374 let again = unique("after-rename");
376 let path2 = create_with(&CreateOptions {
377 path: Some(&again),
378 skip_libsystem: true,
379 ..CreateOptions::default()
380 })
381 .expect("create after stale");
382 assert!(layout::is_bottle_root(&path2.path));
383
384 destroy(true).expect("destroy");
385 drop(std::fs::remove_dir_all(&renamed));
386 }
387
388 #[test]
389 fn destroy_requires_confirmation() {
390 let _lock = test_env_lock();
391 let _g = EnvGuard::new();
392
393 let path = create_with(&CreateOptions {
394 skip_libsystem: true,
395 ..CreateOptions::default()
396 })
397 .expect("create")
398 .path;
399 let err = destroy(false).expect_err("need confirm");
400 assert!(matches!(err, BottleError::NotConfirmed));
401 assert!(path.exists());
402 destroy(true).expect("destroy");
403 }
404
405 #[test]
406 fn volumes_linux_rw_outside_bottle() {
407 let _lock = test_env_lock();
408 let _g = EnvGuard::new();
409
410 let root = create_with(&CreateOptions {
411 skip_libsystem: true,
412 ..CreateOptions::default()
413 })
414 .expect("create")
415 .path;
416 let token = format!("kh-manage-vol-{}", std::process::id());
417 let host_file = std::env::temp_dir().join(&token);
418 let payload = b"rw-outside\n";
419 std::fs::write(&host_file, payload).expect("host write");
420
421 let via = root
422 .join(layout::VOLUMES_LINUX)
423 .join(host_file.strip_prefix("/").expect("abs"));
424 assert_eq!(std::fs::read(&via).expect("via read"), payload);
425
426 let payload2 = b"from-bottle-side\n";
427 std::fs::write(&via, payload2).expect("via write");
428 assert_eq!(std::fs::read(&host_file).expect("host read"), payload2);
429
430 drop(std::fs::remove_file(&host_file));
431 destroy(true).expect("destroy");
432 }
433
434 #[test]
435 fn create_installs_explicit_libsystem() {
436 let _lock = test_env_lock();
437 let _g = EnvGuard::new();
438
439 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
441 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
442 assert!(fixture.is_file(), "missing fixture {}", fixture.display());
443
444 let created = create_with(&CreateOptions {
445 libsystem: Some(&fixture),
446 ..CreateOptions::default()
447 })
448 .expect("create with libsystem");
449 assert!(created.libsystem.is_some());
450 let dest = created.path.join(libsystem::GUEST_LIBSYSTEM_REL);
451 assert!(dest.is_file());
452 let st = status().expect("status").expect("registered");
453 assert!(st.libsystem);
454 assert!(st.libcxx_alias);
455 assert!(layout::has_libcxx_symlink(&created.path));
456
457 destroy(true).expect("destroy");
458 }
459
460 #[test]
461 fn ensure_creates_then_refreshes_libsystem() {
462 let _lock = test_env_lock();
463 let _g = EnvGuard::new();
464
465 let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
466 let fixture = repo.join("tests/fixtures/bottle/usr/lib/libSystem.B.dylib");
467 assert!(fixture.is_file());
468
469 let first = ensure(&CreateOptions {
470 libsystem: Some(&fixture),
471 ..CreateOptions::default()
472 })
473 .expect("ensure create");
474 assert!(first.libsystem.is_some());
475 let dest = first.path.join(libsystem::GUEST_LIBSYSTEM_REL);
476 let before = std::fs::metadata(&dest).expect("meta").len();
477
478 let second = ensure(&CreateOptions {
480 libsystem: Some(&fixture),
481 ..CreateOptions::default()
482 })
483 .expect("ensure refresh");
484 assert_eq!(second.path, first.path);
485 assert!(second.libsystem.is_some());
486 assert!(dest.is_file());
487 let after = std::fs::metadata(&dest).expect("meta2").len();
488 assert_eq!(before, after);
489
490 destroy(true).expect("destroy");
491 }
492}