1#![expect(
2 clippy::string_slice,
3 reason = "Cargo manifest offsets come from ASCII markers and are therefore UTF-8 boundaries."
4)]
5
6use anyhow::{Context, Result};
9use regex::Regex;
10use sha2::{Digest, Sha256};
11use std::time::{SystemTime, UNIX_EPOCH};
12
13#[inline]
15pub fn current_timestamp() -> u64 {
16 current_timestamp_result().unwrap_or(0)
17}
18
19#[inline]
21fn current_timestamp_result() -> Result<u64> {
22 Ok(SystemTime::now()
23 .duration_since(UNIX_EPOCH)
24 .context("System clock is before UNIX_EPOCH while generating timestamp")?
25 .as_secs())
26}
27
28pub fn calculate_sha256(content: &[u8]) -> String {
35 let mut hasher = Sha256::new();
36 hasher.update(content);
37 let digest = hasher.finalize();
38 let mut output = String::with_capacity(digest.len() * 2);
39
40 for byte in digest {
41 output.push(nibble_to_hex(byte >> 4));
42 output.push(nibble_to_hex(byte & 0x0f));
43 }
44
45 output
46}
47
48fn nibble_to_hex(nibble: u8) -> char {
55 debug_assert!(nibble <= 0x0f, "hex nibble outside 0..=15: {nibble}");
56 const DIGITS: &[u8; 16] = b"0123456789abcdef";
57 char::from(DIGITS.get(usize::from(nibble & 0x0f)).copied().unwrap_or(b'?'))
58}
59
60pub fn extract_toml_str(content: &str, key: &str) -> Option<String> {
62 let pkg_section = if let Some(start) = content.find("[package]") {
64 let rest = &content[start + "[package]".len()..];
65 if let Some(_next) = rest.find('\n') {
67 &content[start..]
68 } else {
69 &content[start..]
70 }
71 } else {
72 content
73 };
74
75 let pattern = format!(r#"(?m)^\s*{}\s*=\s*"([^"]+)"\s*$"#, regex::escape(key));
77 let re = Regex::new(&pattern).ok()?;
78 re.captures(pkg_section)
79 .and_then(|caps| caps.get(1).map(|m| m.as_str().to_owned()))
80}
81
82pub fn extract_readme_excerpt(md: &str, max_len: usize) -> String {
84 let mut excerpt = String::with_capacity(max_len.min(md.len()));
86 for line in md.lines() {
87 if excerpt.len() > max_len {
89 break;
90 }
91 excerpt.push_str(line);
92 excerpt.push('\n');
93 if line.trim().starts_with("## ") && excerpt.len() > (max_len / 2) {
95 break;
96 }
97 }
98 crate::formatting::truncate_byte_budget(&excerpt, max_len, "...\n")
99}
100
101#[must_use]
113pub fn env_flag_enabled(var_name: &str) -> bool {
114 env_flag_value_enabled(std::env::var(var_name).ok().as_deref())
115}
116
117#[must_use]
131pub fn env_flag_value_enabled(value: Option<&str>) -> bool {
132 value.is_some_and(|value| {
133 matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on" | "debug")
134 })
135}
136
137#[must_use]
144pub fn parse_bool_env_value(value: &str) -> Option<bool> {
145 match value.trim().to_ascii_lowercase().as_str() {
146 "1" | "true" | "yes" | "on" => Some(true),
147 "0" | "false" | "no" | "off" => Some(false),
148 _ => None,
149 }
150}
151
152#[must_use]
162pub fn parse_env_bool(name: &str, default: bool) -> bool {
163 std::env::var(name)
164 .ok()
165 .and_then(|value| parse_bool_env_value(&value))
166 .unwrap_or(default)
167}
168
169pub fn safe_replace_text(content: &str, old_str: &str, new_str: &str) -> Result<String> {
171 if old_str.is_empty() {
172 return Err(anyhow::anyhow!("old_string cannot be empty"));
173 }
174
175 if !content.contains(old_str) {
176 return Err(anyhow::anyhow!("Text '{old_str}' not found in content"));
177 }
178
179 Ok(content.replace(old_str, new_str))
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn nibble_to_hex_covers_the_full_four_bit_domain() {
188 let mapped: String = (0u8..=15).map(nibble_to_hex).collect();
189 assert_eq!(mapped, "0123456789abcdef");
190
191 assert_eq!(calculate_sha256(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
194 }
195
196 #[test]
197 #[should_panic(expected = "hex nibble outside 0..=15")]
198 fn nibble_to_hex_fails_loud_when_its_contract_is_violated() {
199 let _ = nibble_to_hex(16);
200 }
201
202 #[test]
203 fn readme_excerpt_does_not_split_utf8() {
204 let markdown = "你".repeat(700);
205
206 assert_eq!(extract_readme_excerpt(&markdown, 1201), format!("{}...\n", "你".repeat(400)));
207 }
208
209 #[test]
210 fn parse_bool_env_value_accepts_canonical_sets() {
211 for truthy in ["1", "true", "YES", " On ", "on"] {
212 assert_eq!(parse_bool_env_value(truthy), Some(true), "{truthy}");
213 }
214 for falsy in ["0", "false", "NO", " Off ", "off"] {
215 assert_eq!(parse_bool_env_value(falsy), Some(false), "{falsy}");
216 }
217 for unrecognized in ["", "debug", "2", "maybe"] {
218 assert_eq!(parse_bool_env_value(unrecognized), None, "{unrecognized}");
219 }
220 }
221
222 #[test]
223 fn parse_env_bool_falls_back_to_default_when_unset_or_unrecognized() {
224 assert!(!parse_env_bool("VTCODE_ENV_BOOL_TEST_DEFINITELY_UNSET", false));
225 assert!(parse_env_bool("VTCODE_ENV_BOOL_TEST_DEFINITELY_UNSET", true));
226
227 let guard = crate::env_lock::lock();
228 guard.set_var("VTCODE_ENV_BOOL_TEST_VALUE", "yes");
229 assert!(parse_env_bool("VTCODE_ENV_BOOL_TEST_VALUE", false));
230 guard.set_var("VTCODE_ENV_BOOL_TEST_VALUE", "bogus");
231 assert!(!parse_env_bool("VTCODE_ENV_BOOL_TEST_VALUE", false));
232 }
233}