1pub mod environment;
20mod hidden_input;
21pub(crate) mod path_serde;
22pub(crate) mod paths;
23pub(crate) mod program;
24#[cfg(unix)]
25mod unix;
26#[cfg(windows)]
27mod windows;
28
29#[cfg(unix)]
30use unix as os;
31#[cfg(windows)]
32use windows as os;
33
34pub(crate) use os::{
35 CRLF_LINE_ENDINGS, Child, DEFAULT_EDITOR, ENV_NAMES_IGNORE_CASE, HOME_VARIABLE, HiddenInput,
36 PrivateTempDir, STATE_VARIABLES, TEMP_VARIABLES, USER_VARIABLES, VISIBLE_INPUT_FALLBACK,
37 create_private_dir, create_private_dir_all, editor, exit_signal, file_identity, home_directory,
38 host_name, ipc, is_owner_only, is_private_dir, is_private_file, kill_saved_group,
39 kill_saved_session, path_from_bytes, private_options, private_tempdir_in, process_start_time,
40 remove_abandoned_directory, resolve_system_aliases, restrict_file, running_process_start_time,
41 spawn_detached, spawn_gated, spawn_run, stop_requested, sync_dir, transient_file_access,
42};
43pub(crate) use os::{PRIVATE_DIRECTORY, PRIVATE_FILE};
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub(crate) struct FileIdentity {
49 volume: u64,
50 index: u64,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum ProcessEnd {
56 Exited(i32),
58 Signaled(Option<i32>),
60}
61
62pub(crate) fn process_end(status: &std::process::ExitStatus) -> ProcessEnd {
64 match status.code() {
65 Some(code) => ProcessEnd::Exited(code),
66 None => ProcessEnd::Signaled(exit_signal(status)),
67 }
68}
69
70pub(crate) fn exit_description(status: &std::process::ExitStatus) -> String {
73 status.to_string()
74}
75
76pub(crate) const FILE_LOCK_RETRY_INTERVAL: std::time::Duration =
79 std::time::Duration::from_millis(25);
80
81pub use artifactize_tools::files::path_text;
82pub(crate) use artifactize_tools::files::{
83 EntryName, FileKind, canonicalize, entry_kind, link_target, open_directory, open_entry,
84 open_no_follow, open_nonblocking, read_dir,
85};
86
87pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
90 let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
91 if file.metadata()?.is_file() {
92 Ok(file)
93 } else {
94 Err(std::io::Error::new(
95 std::io::ErrorKind::InvalidInput,
96 "not a regular file",
97 ))
98 }
99}
100
101pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
104 let path = if CRLF_LINE_ENDINGS {
105 bytes
106 .strip_suffix(b"\r\n")
107 .or_else(|| bytes.strip_suffix(b"\n"))
108 .unwrap_or(bytes)
109 } else {
110 bytes.strip_suffix(b"\n").unwrap_or(bytes)
111 };
112 path_from_bytes(path)
113}
114
115pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
117 resolve_state_directory(
118 environment::var("ARTIFACTIZE_STATE_HOME").map(Into::into),
119 STATE_VARIABLES
120 .iter()
121 .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
122 .map(Into::into),
123 home_directory(),
124 )
125}
126
127fn resolve_state_directory(
128 artifactize: Option<std::path::PathBuf>,
129 state: Option<std::path::PathBuf>,
130 home: Option<std::path::PathBuf>,
131) -> Option<std::path::PathBuf> {
132 artifactize
133 .filter(|p| !p.as_os_str().is_empty())
134 .or_else(|| {
135 state
136 .filter(|p| !p.as_os_str().is_empty())
137 .map(|p| p.join("artifactize"))
138 })
139 .or_else(|| {
140 home.filter(|p| !p.as_os_str().is_empty())
141 .map(|p| p.join(".local/state/artifactize"))
142 })
143}
144
145pub(crate) fn user_name() -> Option<String> {
147 USER_VARIABLES
148 .iter()
149 .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
150}
151
152pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
154 if CRLF_LINE_ENDINGS {
155 (
156 stdout
157 .strip_suffix(b"\r\n")
158 .or_else(|| stdout.strip_suffix(b"\n"))
159 .unwrap_or(stdout),
160 "LF or CRLF",
161 )
162 } else {
163 (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
164 }
165}
166
167pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
169 match (path.parent(), path.file_name()) {
170 (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
171 _ => open_directory(path).map(|_| FileKind::Directory),
172 }
173}
174
175pub(crate) fn serialize_paths<S: serde::Serializer>(
177 paths: &[std::path::PathBuf],
178 serializer: S,
179) -> Result<S::Ok, S::Error> {
180 use serde::Serialize;
181 paths
182 .iter()
183 .map(|path| path_text(path))
184 .collect::<Vec<_>>()
185 .serialize(serializer)
186}
187
188#[cfg(test)]
189mod state_directory_tests {
190 use super::*;
191 use std::path::PathBuf;
192
193 #[test]
194 fn state_home_precedence_and_empty_values() {
195 let artifactize = PathBuf::from("custom/state");
196 let state = PathBuf::from("state");
197 let home = PathBuf::from("reviewer");
198 assert_eq!(
199 resolve_state_directory(
200 Some(artifactize.clone()),
201 Some(state.clone()),
202 Some(home.clone())
203 ),
204 Some(artifactize)
205 );
206 assert_eq!(
207 resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
208 Some(state.join("artifactize"))
209 );
210 assert_eq!(
211 resolve_state_directory(None, None, Some(home.clone())),
212 Some(home.join(".local/state/artifactize"))
213 );
214 let empty = Some(PathBuf::new());
215 assert_eq!(
216 resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
217 Some(home.join(".local/state/artifactize"))
218 );
219 assert_eq!(
220 resolve_state_directory(empty.clone(), empty.clone(), empty),
221 None
222 );
223 assert_eq!(resolve_state_directory(None, None, None), None);
224 }
225}
226
227mod console;
228pub(crate) use console::pause_after_help;
229
230mod interaction;
231pub use interaction::{PrivateTempFile, private_temp_file, run_editor, selected_editor};
232pub(crate) use interaction::{is_within, label, paths_equal, private_anonymous_file};
233
234pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
236 let Some(parent) = path.parent() else {
237 return Ok(false);
238 };
239 let directory = match open_directory(parent) {
240 Ok(directory) => directory,
241 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
242 Err(error) => return Err(error),
243 };
244 let Some(name) = path.file_name() else {
245 return Ok(false);
246 };
247 match entry_kind(&directory, name) {
248 Ok(_) => Ok(true),
249 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
250 Err(error) => Err(error),
251 }
252}
253
254pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
259 path.symlink_metadata()
260}