1pub(crate) mod desktop_app;
20pub use desktop_app::launch as launch_desktop;
21pub mod desktop_commands;
22mod detached;
23pub mod environment;
24mod executable;
25pub use executable::current_executable;
26mod hidden_input;
27pub(crate) mod install;
28pub(crate) mod net;
29pub(crate) mod path_serde;
30pub(crate) mod paths;
31pub(crate) mod program;
32#[cfg(unix)]
33mod unix;
34#[cfg(windows)]
35mod windows;
36
37#[cfg(unix)]
38use unix as os;
39#[cfg(windows)]
40use windows as os;
41
42pub(crate) use detached::{DetachedChild, spawn_detached, spawn_run, spawn_watched};
43pub use hidden_input::{SecretInput, secret_input, stdin_is_terminal};
44pub use os::HiddenInput;
45pub use os::stop_requested;
46pub(crate) use os::{
47 CRLF_LINE_ENDINGS, Child, ENV_NAMES_IGNORE_CASE, PrivateTempDir, TEMP_VARIABLES,
48 USER_VARIABLES, create_private_dir, create_private_dir_all, file_identity, hide_console_window,
49 home_directory, host_name, ipc, is_owner_only, is_private_dir, is_private_file,
50 kill_saved_group, kill_saved_session, path_from_bytes, private_named_dir, private_options,
51 private_tempdir_in, process_start_time, release_free_memory, remove_tree,
52 resolve_system_aliases, restrict_file, running_process_start_time, spawn_gated, spawn_now,
53 spawn_windowless, sync_dir, transient_file_access,
54};
55pub(crate) use os::{PRIVATE_DIRECTORY, PRIVATE_FILE};
56
57#[derive(Debug, Clone)]
62pub struct Footprint {
63 _release: std::sync::Arc<Release>,
64}
65
66impl Footprint {
67 pub(crate) fn new() -> Self {
68 Self {
69 _release: std::sync::Arc::new(Release),
70 }
71 }
72}
73
74#[derive(Debug)]
75struct Release;
76
77impl Drop for Release {
78 fn drop(&mut self) {
79 release_free_memory();
80 }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
86pub(crate) struct FileIdentity {
87 volume: u64,
88 index: u64,
89}
90
91pub use artifactize_tools::launch::{ProcessEnd, ProcessOutcome};
92
93pub(crate) const FILE_LOCK_RETRY_INTERVAL: std::time::Duration =
96 std::time::Duration::from_millis(25);
97
98pub(crate) use artifactize_tools::files::{
99 EntryName, FileKind, canonicalize, entry_kind, link_target, open_directory, open_entry,
100 open_no_follow, read_dir,
101};
102pub use artifactize_tools::files::{current_directory, open_nonblocking, path_text};
103
104pub fn file_uri_path(uri: &str) -> Option<std::path::PathBuf> {
107 url::Url::parse(uri)
108 .ok()?
109 .to_file_path()
110 .ok()
111 .filter(|path| path.is_absolute())
112}
113
114pub fn absolute_folder(text: &str) -> Option<std::path::PathBuf> {
117 artifactize_tools::files::path_from_text(text)
118 .ok()
119 .filter(|path| path.is_absolute())
120}
121
122pub fn is_directory(path: &std::path::Path) -> bool {
124 path.is_dir()
125}
126
127pub fn target_exists(path: &std::path::Path) -> std::io::Result<bool> {
129 paths::target_exists(path)
130}
131
132pub fn is_regular_file(path: &std::path::Path) -> bool {
135 path.is_file()
136}
137
138pub fn open_regular_input(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
141 let file = open_nonblocking(path)?;
142 Ok(file.metadata()?.is_file().then_some(file))
143}
144
145pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
148 let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
149 if file.metadata()?.is_file() {
150 Ok(file)
151 } else {
152 Err(std::io::Error::new(
153 std::io::ErrorKind::InvalidInput,
154 "not a regular file",
155 ))
156 }
157}
158
159pub(crate) fn local_day(instant: time::OffsetDateTime) -> time::Date {
162 let offset = chrono::DateTime::from_timestamp(instant.unix_timestamp(), instant.nanosecond())
163 .map(|utc| utc.with_timezone(&chrono::Local).offset().local_minus_utc())
164 .and_then(|seconds| time::UtcOffset::from_whole_seconds(seconds).ok())
165 .unwrap_or(time::UtcOffset::UTC);
166 instant.to_offset(offset).date()
167}
168
169pub(crate) fn clean_program_text(bytes: &[u8]) -> String {
171 String::from_utf8(crate::runtime::clean_output(bytes)).expect("clean output is UTF-8")
172}
173
174pub fn output_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
176 String::from_utf8_lossy(bytes)
177}
178
179pub fn output_lines(bytes: &[u8]) -> String {
181 output_text(bytes).replace("\r\n", "\n")
182}
183
184pub fn os_text(value: &std::ffi::OsStr) -> Option<&str> {
187 value.to_str()
188}
189
190pub(crate) fn display_name(value: &std::ffi::OsStr) -> String {
192 value.to_string_lossy().into_owned()
193}
194
195pub(crate) fn output_line(bytes: &[u8]) -> &[u8] {
198 bytes
199 .strip_suffix(b"\r\n")
200 .or_else(|| bytes.strip_suffix(b"\n"))
201 .unwrap_or(bytes)
202}
203
204pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
207 let path = if CRLF_LINE_ENDINGS {
208 bytes
209 .strip_suffix(b"\r\n")
210 .or_else(|| bytes.strip_suffix(b"\n"))
211 .unwrap_or(bytes)
212 } else {
213 bytes.strip_suffix(b"\n").unwrap_or(bytes)
214 };
215 path_from_bytes(path)
216}
217
218pub(crate) fn temporary_directory() -> std::path::PathBuf {
220 std::env::temp_dir()
221}
222
223const STATE_HOME_OVERRIDE: &str = "ARTIFACTIZE_STATE_HOME";
224
225pub(crate) fn state_home_variables() -> impl Iterator<Item = &'static str> {
227 std::iter::once(STATE_HOME_OVERRIDE)
228 .chain(os::STATE_VARIABLES.iter().copied())
229 .chain(os::HOME_VARIABLES.iter().copied())
230}
231
232pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
234 resolve_state_directory(
235 environment::var(STATE_HOME_OVERRIDE).map(Into::into),
236 os::STATE_VARIABLES
237 .iter()
238 .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
239 .map(Into::into),
240 home_directory(),
241 )
242}
243
244fn resolve_state_directory(
245 artifactize: Option<std::path::PathBuf>,
246 state: Option<std::path::PathBuf>,
247 home: Option<std::path::PathBuf>,
248) -> Option<std::path::PathBuf> {
249 artifactize
250 .filter(|p| !p.as_os_str().is_empty())
251 .or_else(|| {
252 state
253 .filter(|p| !p.as_os_str().is_empty())
254 .map(|p| p.join("artifactize"))
255 })
256 .or_else(|| {
257 home.filter(|p| !p.as_os_str().is_empty())
258 .map(|p| p.join(".local/state/artifactize"))
259 })
260}
261
262pub(crate) fn user_name() -> Option<String> {
264 USER_VARIABLES
265 .iter()
266 .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
267}
268
269pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
271 if CRLF_LINE_ENDINGS {
272 (
273 stdout
274 .strip_suffix(b"\r\n")
275 .or_else(|| stdout.strip_suffix(b"\n"))
276 .unwrap_or(stdout),
277 "LF or CRLF",
278 )
279 } else {
280 (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
281 }
282}
283
284pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
286 match (path.parent(), path.file_name()) {
287 (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
288 _ => open_directory(path).map(|_| FileKind::Directory),
289 }
290}
291
292pub(crate) fn program_path(command: &str) -> std::io::Result<std::path::PathBuf> {
295 #[cfg(windows)]
296 if command.starts_with(r"\\?\") {
297 return Ok(command.into());
298 }
299 artifactize_tools::files::path_from_text(command)
300}
301
302pub(crate) fn program_text(command: &str) -> String {
304 program_path(command).map_or_else(|_| command.to_owned(), |path| path_text(&path))
305}
306
307pub(crate) fn serialize_program<S: serde::Serializer>(
309 command: &str,
310 serializer: S,
311) -> Result<S::Ok, S::Error> {
312 serializer.serialize_str(&program_text(command))
313}
314
315pub(crate) fn serialize_paths<S: serde::Serializer>(
317 paths: &[std::path::PathBuf],
318 serializer: S,
319) -> Result<S::Ok, S::Error> {
320 use serde::Serialize;
321 paths
322 .iter()
323 .map(path_text)
324 .collect::<Vec<_>>()
325 .serialize(serializer)
326}
327
328#[cfg(test)]
329mod process_tests;
330#[cfg(test)]
331pub(crate) use process_tests::pipe_grace_armed;
332
333#[cfg(test)]
334mod program_tests {
335 #[test]
336 fn a_declared_program_is_written_with_forward_slashes() {
337 assert_eq!(super::program_text("pnpm"), "pnpm");
338 assert_eq!(super::program_text("tools/run.sh"), "tools/run.sh");
339 #[cfg(windows)]
341 assert_eq!(super::program_text(r"tools\run.cmd"), "tools/run.cmd");
342 }
343}
344
345#[cfg(test)]
346mod private_directory_tests {
347 use super::*;
348
349 #[test]
350 fn kept_temporary_directory_transfers_cleanup_responsibility() {
351 let parent = crate::test_os::tempdir();
352 let directory = private_tempdir_in("kept-", parent.path()).unwrap();
353 let path = directory.keep();
354 assert!(path.is_dir());
355 assert!(is_private_dir(&path).unwrap());
356 remove_tree(&path).unwrap();
357 assert!(!path.exists());
358 }
359}
360
361#[cfg(test)]
362mod state_directory_tests {
363 use super::*;
364 use std::path::PathBuf;
365
366 #[test]
367 fn state_home_precedence_and_empty_values() {
368 let artifactize = PathBuf::from("custom/state");
369 let state = PathBuf::from("state");
370 let home = PathBuf::from("reviewer");
371 assert_eq!(
372 resolve_state_directory(
373 Some(artifactize.clone()),
374 Some(state.clone()),
375 Some(home.clone())
376 ),
377 Some(artifactize)
378 );
379 assert_eq!(
380 resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
381 Some(state.join("artifactize"))
382 );
383 assert_eq!(
384 resolve_state_directory(None, None, Some(home.clone())),
385 Some(home.join(".local/state/artifactize"))
386 );
387 let empty = Some(PathBuf::new());
388 assert_eq!(
389 resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
390 Some(home.join(".local/state/artifactize"))
391 );
392 assert_eq!(
393 resolve_state_directory(empty.clone(), empty.clone(), empty),
394 None
395 );
396 assert_eq!(resolve_state_directory(None, None, None), None);
397 }
398}
399
400mod console;
401pub use console::pause_after_help;
402
403mod interaction;
404pub use interaction::paths_equal;
405pub(crate) use interaction::{is_within, label, private_anonymous_file};
406
407pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
409 let Some(parent) = path.parent() else {
410 return Ok(false);
411 };
412 let directory = match open_directory(parent) {
413 Ok(directory) => directory,
414 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
415 Err(error) => return Err(error),
416 };
417 let Some(name) = path.file_name() else {
418 return Ok(false);
419 };
420 match entry_kind(&directory, name) {
421 Ok(_) => Ok(true),
422 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
423 Err(error) => Err(error),
424 }
425}
426
427pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
432 path.symlink_metadata()
433}
434
435#[cfg(test)]
436pub(crate) fn successful_outcome() -> ProcessOutcome {
437 ProcessOutcome::from_native(std::process::ExitStatus::default())
438}
439
440#[cfg(test)]
441mod stop_tests {
442 use super::*;
443 use std::{path::PathBuf, time::Duration};
444
445 const READY: &str = "ARTIFACTIZE_TEST_STOP_PROBE_READY";
446 const WATCHDOG: Duration = Duration::from_secs(15);
447
448 #[tokio::test]
449 async fn a_terminal_interrupt_completes_stop_requested() {
450 let root = crate::test_os::tempdir();
451 let ready = root.path().join("ready");
452 let mut child = crate::test_os::test_command(
453 "platform::stop_tests::terminal_interrupt_probe",
454 &[(READY, ready.clone().into_os_string())],
455 );
456 crate::test_os::new_group(&mut child);
457 let mut child = crate::test_os::spawn_test(&mut tokio::process::Command::from(child));
458 crate::test_os::wait_until(WATCHDOG, || ready.is_file());
459 crate::test_os::interrupt(child.id());
460 assert!(child.wait().await.success());
461 }
462
463 #[tokio::test]
464 async fn terminal_interrupt_probe() {
465 let Some(ready) = crate::test_os::environment_variable(READY) else {
466 return;
467 };
468 let stop = stop_requested().unwrap();
469 std::fs::write(PathBuf::from(ready), "subscribed").unwrap();
470 stop.await;
471 }
472}