1pub mod date;
6pub mod defaults;
7#[cfg(feature = "http")]
8pub mod http;
9
10pub use defaults::parse_with_defaults;
11
12use std::process::{Command, Stdio};
13
14use url::{Host, Url};
15
16pub fn init() {
29 install_crypto_provider();
30}
31
32pub fn install_crypto_provider() {
50 let _ = rustls::crypto::ring::default_provider().install_default();
51}
52
53pub const ALLOW_INSECURE_URL_ENV: &str = "SANDOGASA_ALLOW_INSECURE_URL";
58
59pub fn ensure_secure_url(base_url: &str) -> Result<(), String> {
72 let allow_insecure = std::env::var_os(ALLOW_INSECURE_URL_ENV).is_some_and(|v| !v.is_empty());
73 check_secure_url(base_url, allow_insecure)
74}
75
76fn check_secure_url(base_url: &str, allow_insecure: bool) -> Result<(), String> {
79 let parsed = Url::parse(base_url).map_err(|e| format!("invalid URL '{base_url}': {e}"))?;
80 if parsed.scheme() == "https" || host_is_loopback(&parsed) {
81 return Ok(());
82 }
83 if allow_insecure {
84 return Ok(());
85 }
86 Err(format!(
87 "refusing to send credentials to '{base_url}' over plaintext \
88 {}: use an https URL, or set {ALLOW_INSECURE_URL_ENV}=1 to \
89 override (e.g. for local testing against a mock server).",
90 parsed.scheme()
91 ))
92}
93
94fn host_is_loopback(u: &Url) -> bool {
96 match u.host() {
97 Some(Host::Domain(d)) => d == "localhost" || d.ends_with(".localhost"),
98 Some(Host::Ipv4(ip)) => ip.is_loopback(),
99 Some(Host::Ipv6(ip)) => ip.is_loopback(),
100 None => false,
101 }
102}
103
104pub fn tool_exists(name: &str) -> bool {
107 std::env::var_os("PATH")
108 .map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(name).is_file()))
109 .unwrap_or(false)
110}
111
112fn tool_available(exe: &str, probe: Option<&str>) -> bool {
116 match probe {
117 Some(arg) => Command::new(exe)
118 .arg(arg)
119 .stdout(Stdio::null())
120 .stderr(Stdio::null())
121 .status()
122 .is_ok_and(|s| s.success()),
123 None => tool_exists(exe),
124 }
125}
126
127pub fn require_tools(tools: &[(&str, &str, Option<&str>)]) -> Result<(), String> {
151 let missing: Vec<String> = tools
152 .iter()
153 .filter(|(exe, _, probe)| !tool_available(exe, *probe))
154 .map(|(exe, hint, _)| format!("{exe} (install: {hint})"))
155 .collect();
156 if missing.is_empty() {
157 Ok(())
158 } else {
159 Err(format!("missing required tool(s): {}", missing.join(", ")))
160 }
161}
162
163pub fn wrap_prefixed(text: &str, prefix: &str, width: usize) -> String {
172 let mut out = String::new();
173 let mut line = String::new();
174 for word in text.split_whitespace() {
175 if !line.is_empty()
176 && prefix.len() + line.len() + 1 + word.len() > width
177 && prefix.len() + word.len() <= width
178 {
179 out.push_str(prefix);
180 out.push_str(&line);
181 out.push('\n');
182 line.clear();
183 }
184 if !line.is_empty() {
185 line.push(' ');
186 }
187 line.push_str(word);
188 }
189 if !line.is_empty() {
190 out.push_str(prefix);
191 out.push_str(&line);
192 }
193 out
194}
195
196pub fn confirm(question: &str, default_yes: bool) -> std::io::Result<bool> {
205 use std::io::{BufRead, Write};
206 let hint = if default_yes { "[Y/n]" } else { "[y/N]" };
207 eprint!("{question} {hint}: ");
208 std::io::stderr().flush()?;
209 let mut line = String::new();
210 std::io::stdin().lock().read_line(&mut line)?;
211 Ok(parse_confirm(&line, default_yes))
212}
213
214fn parse_confirm(answer: &str, default_yes: bool) -> bool {
216 let answer = answer.trim();
217 if answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes") {
218 true
219 } else if answer.eq_ignore_ascii_case("n") || answer.eq_ignore_ascii_case("no") {
220 false
221 } else {
222 default_yes
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn tool_exists_detects_present_and_absent() {
232 assert!(tool_exists("sh"));
233 assert!(!tool_exists("nonexistent_tool_xyz_123"));
234 }
235
236 #[test]
237 fn require_tools_path_and_probe_modes() {
238 assert!(require_tools(&[("sh", "present", None)]).is_ok());
240 assert!(require_tools(&[("nonexistent_zzz", "install zzz", None)]).is_err());
241
242 assert!(require_tools(&[("true", "ok", Some("--version"))]).is_ok());
246 let err = require_tools(&[
247 ("true", "ok", Some("--version")),
248 ("nonexistent_aaa_111", "install aaa", Some("--version")),
249 ("nonexistent_bbb_222", "install bbb", None),
250 ])
251 .unwrap_err();
252 assert!(err.contains("nonexistent_aaa_111"));
253 assert!(err.contains("install aaa"));
254 assert!(err.contains("nonexistent_bbb_222"));
255 assert!(err.contains("install bbb"));
256 assert!(!err.contains("true ("));
257 }
258
259 #[test]
260 fn wrap_prefixed_wraps_and_prefixes() {
261 let text = "alpha beta gamma delta epsilon zeta eta theta iota";
262 let wrapped = wrap_prefixed(text, "> ", 20);
263 assert!(wrapped.lines().all(|l| l.starts_with("> ")));
265 assert!(wrapped.lines().all(|l| l.chars().count() <= 20));
266 assert!(wrapped.lines().count() > 1);
268 assert_eq!(
269 wrapped.split_whitespace().count(),
270 9 + wrapped.lines().count()
271 );
272 }
273
274 #[test]
275 fn wrap_prefixed_keeps_a_long_word_whole_and_in_place() {
276 let url = "https://example.com/a/very/long/path/that/exceeds/the/width";
279 let wrapped = wrap_prefixed(&format!("LINK: {url} please"), " ", 20);
280 assert!(wrapped.contains(url), "{wrapped}");
281 assert_eq!(wrapped.lines().next().unwrap(), format!(" LINK: {url}"));
282 assert_eq!(wrapped.lines().nth(1).unwrap(), " please");
284 }
285
286 #[test]
287 fn parse_confirm_answers_and_defaults() {
288 for yes in ["y", "Y", "yes", "YES", " y "] {
289 assert!(parse_confirm(yes, false));
290 }
291 for no in ["n", "N", "no", "NO"] {
292 assert!(!parse_confirm(no, true));
293 }
294 for other in ["", "\n", "maybe"] {
296 assert!(parse_confirm(other, true));
297 assert!(!parse_confirm(other, false));
298 }
299 }
300
301 #[test]
302 fn secure_url_allows_https() {
303 assert!(check_secure_url("https://bugzilla.redhat.com", false).is_ok());
304 assert!(check_secure_url("https://gitlab.com/api/v4", false).is_ok());
305 }
306
307 #[test]
308 fn secure_url_allows_loopback_over_http() {
309 assert!(check_secure_url("http://127.0.0.1:8080", false).is_ok());
311 assert!(check_secure_url("http://localhost:3000/api", false).is_ok());
312 assert!(check_secure_url("http://[::1]:9999", false).is_ok());
313 }
314
315 #[test]
316 fn secure_url_rejects_plaintext_remote() {
317 let err = check_secure_url("http://gitlab.example.com", false).unwrap_err();
318 assert!(err.contains("gitlab.example.com"));
319 assert!(err.contains(ALLOW_INSECURE_URL_ENV));
320 }
321
322 #[test]
323 fn secure_url_override_allows_plaintext_remote() {
324 assert!(check_secure_url("http://gitlab.example.com", true).is_ok());
326 }
327
328 #[test]
329 fn secure_url_rejects_invalid() {
330 assert!(check_secure_url("not a url", false).is_err());
331 }
332}