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 Some(std::path::PathBuf::from(text)).filter(|path| path.is_absolute())
118}
119
120pub fn is_regular_file(path: &std::path::Path) -> bool {
123 path.is_file()
124}
125
126pub fn open_regular_input(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
129 let file = open_nonblocking(path)?;
130 Ok(file.metadata()?.is_file().then_some(file))
131}
132
133pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
136 let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
137 if file.metadata()?.is_file() {
138 Ok(file)
139 } else {
140 Err(std::io::Error::new(
141 std::io::ErrorKind::InvalidInput,
142 "not a regular file",
143 ))
144 }
145}
146
147pub fn output_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
149 String::from_utf8_lossy(bytes)
150}
151
152pub fn output_lines(bytes: &[u8]) -> String {
154 output_text(bytes).replace("\r\n", "\n")
155}
156
157pub fn os_text(value: &std::ffi::OsStr) -> Option<&str> {
160 value.to_str()
161}
162
163pub(crate) fn output_line(bytes: &[u8]) -> &[u8] {
166 bytes
167 .strip_suffix(b"\r\n")
168 .or_else(|| bytes.strip_suffix(b"\n"))
169 .unwrap_or(bytes)
170}
171
172pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
175 let path = if CRLF_LINE_ENDINGS {
176 bytes
177 .strip_suffix(b"\r\n")
178 .or_else(|| bytes.strip_suffix(b"\n"))
179 .unwrap_or(bytes)
180 } else {
181 bytes.strip_suffix(b"\n").unwrap_or(bytes)
182 };
183 path_from_bytes(path)
184}
185
186pub(crate) fn temporary_directory() -> std::path::PathBuf {
188 std::env::temp_dir()
189}
190
191const STATE_HOME_OVERRIDE: &str = "ARTIFACTIZE_STATE_HOME";
192
193pub(crate) fn state_home_variables() -> impl Iterator<Item = &'static str> {
195 std::iter::once(STATE_HOME_OVERRIDE)
196 .chain(os::STATE_VARIABLES.iter().copied())
197 .chain(os::HOME_VARIABLES.iter().copied())
198}
199
200pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
202 resolve_state_directory(
203 environment::var(STATE_HOME_OVERRIDE).map(Into::into),
204 os::STATE_VARIABLES
205 .iter()
206 .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
207 .map(Into::into),
208 home_directory(),
209 )
210}
211
212fn resolve_state_directory(
213 artifactize: Option<std::path::PathBuf>,
214 state: Option<std::path::PathBuf>,
215 home: Option<std::path::PathBuf>,
216) -> Option<std::path::PathBuf> {
217 artifactize
218 .filter(|p| !p.as_os_str().is_empty())
219 .or_else(|| {
220 state
221 .filter(|p| !p.as_os_str().is_empty())
222 .map(|p| p.join("artifactize"))
223 })
224 .or_else(|| {
225 home.filter(|p| !p.as_os_str().is_empty())
226 .map(|p| p.join(".local/state/artifactize"))
227 })
228}
229
230pub(crate) fn user_name() -> Option<String> {
232 USER_VARIABLES
233 .iter()
234 .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
235}
236
237pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
239 if CRLF_LINE_ENDINGS {
240 (
241 stdout
242 .strip_suffix(b"\r\n")
243 .or_else(|| stdout.strip_suffix(b"\n"))
244 .unwrap_or(stdout),
245 "LF or CRLF",
246 )
247 } else {
248 (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
249 }
250}
251
252pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
254 match (path.parent(), path.file_name()) {
255 (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
256 _ => open_directory(path).map(|_| FileKind::Directory),
257 }
258}
259
260pub(crate) fn program_text(command: &str) -> String {
262 path_text(std::path::Path::new(command))
263}
264
265pub(crate) fn serialize_program<S: serde::Serializer>(
267 command: &str,
268 serializer: S,
269) -> Result<S::Ok, S::Error> {
270 serializer.serialize_str(&program_text(command))
271}
272
273pub(crate) fn serialize_paths<S: serde::Serializer>(
275 paths: &[std::path::PathBuf],
276 serializer: S,
277) -> Result<S::Ok, S::Error> {
278 use serde::Serialize;
279 paths
280 .iter()
281 .map(path_text)
282 .collect::<Vec<_>>()
283 .serialize(serializer)
284}
285
286#[cfg(test)]
287mod process_tests;
288#[cfg(test)]
289pub(crate) use process_tests::pipe_grace_armed;
290
291#[cfg(test)]
292mod program_tests {
293 #[test]
294 fn a_declared_program_is_written_with_forward_slashes() {
295 assert_eq!(super::program_text("pnpm"), "pnpm");
296 assert_eq!(super::program_text("tools/run.sh"), "tools/run.sh");
297 #[cfg(windows)]
299 assert_eq!(super::program_text(r"tools\run.cmd"), "tools/run.cmd");
300 }
301}
302
303#[cfg(test)]
304mod private_directory_tests {
305 use super::*;
306
307 #[test]
308 fn kept_temporary_directory_transfers_cleanup_responsibility() {
309 let parent = crate::test_os::tempdir();
310 let directory = private_tempdir_in("kept-", parent.path()).unwrap();
311 let path = directory.keep();
312 assert!(path.is_dir());
313 assert!(is_private_dir(&path).unwrap());
314 remove_tree(&path).unwrap();
315 assert!(!path.exists());
316 }
317}
318
319#[cfg(test)]
320mod state_directory_tests {
321 use super::*;
322 use std::path::PathBuf;
323
324 #[test]
325 fn state_home_precedence_and_empty_values() {
326 let artifactize = PathBuf::from("custom/state");
327 let state = PathBuf::from("state");
328 let home = PathBuf::from("reviewer");
329 assert_eq!(
330 resolve_state_directory(
331 Some(artifactize.clone()),
332 Some(state.clone()),
333 Some(home.clone())
334 ),
335 Some(artifactize)
336 );
337 assert_eq!(
338 resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
339 Some(state.join("artifactize"))
340 );
341 assert_eq!(
342 resolve_state_directory(None, None, Some(home.clone())),
343 Some(home.join(".local/state/artifactize"))
344 );
345 let empty = Some(PathBuf::new());
346 assert_eq!(
347 resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
348 Some(home.join(".local/state/artifactize"))
349 );
350 assert_eq!(
351 resolve_state_directory(empty.clone(), empty.clone(), empty),
352 None
353 );
354 assert_eq!(resolve_state_directory(None, None, None), None);
355 }
356}
357
358mod console;
359pub use console::pause_after_help;
360
361mod interaction;
362pub use interaction::paths_equal;
363pub(crate) use interaction::{is_within, label, private_anonymous_file};
364
365pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
367 let Some(parent) = path.parent() else {
368 return Ok(false);
369 };
370 let directory = match open_directory(parent) {
371 Ok(directory) => directory,
372 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
373 Err(error) => return Err(error),
374 };
375 let Some(name) = path.file_name() else {
376 return Ok(false);
377 };
378 match entry_kind(&directory, name) {
379 Ok(_) => Ok(true),
380 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
381 Err(error) => Err(error),
382 }
383}
384
385pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
390 path.symlink_metadata()
391}
392
393#[cfg(test)]
394pub(crate) fn successful_outcome() -> ProcessOutcome {
395 ProcessOutcome::from_native(std::process::ExitStatus::default())
396}