#![expect(
clippy::string_slice,
reason = "Cargo manifest offsets come from ASCII markers and are therefore UTF-8 boundaries."
)]
use anyhow::{Context, Result};
use regex::Regex;
use sha2::{Digest, Sha256};
use std::time::{SystemTime, UNIX_EPOCH};
#[inline]
pub fn current_timestamp() -> u64 {
current_timestamp_result().unwrap_or(0)
}
#[inline]
fn current_timestamp_result() -> Result<u64> {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("System clock is before UNIX_EPOCH while generating timestamp")?
.as_secs())
}
pub fn calculate_sha256(content: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(content);
let digest = hasher.finalize();
let mut output = String::with_capacity(digest.len() * 2);
for byte in digest {
output.push(nibble_to_hex(byte >> 4));
output.push(nibble_to_hex(byte & 0x0f));
}
output
}
#[allow(
clippy::unreachable,
reason = "Intentional compatibility, platform, or test-only suppression."
)]
fn nibble_to_hex(nibble: u8) -> char {
match nibble {
0..=9 => char::from(b'0' + nibble),
10..=15 => char::from(b'a' + (nibble - 10)),
_ => unreachable!("nibble must be in 0..=15"),
}
}
pub fn extract_toml_str(content: &str, key: &str) -> Option<String> {
let pkg_section = if let Some(start) = content.find("[package]") {
let rest = &content[start + "[package]".len()..];
if let Some(_next) = rest.find('\n') {
&content[start..]
} else {
&content[start..]
}
} else {
content
};
let pattern = format!(r#"(?m)^\s*{}\s*=\s*"([^"]+)"\s*$"#, regex::escape(key));
let re = Regex::new(&pattern).ok()?;
re.captures(pkg_section)
.and_then(|caps| caps.get(1).map(|m| m.as_str().to_owned()))
}
pub fn extract_readme_excerpt(md: &str, max_len: usize) -> String {
let mut excerpt = String::with_capacity(max_len.min(md.len()));
for line in md.lines() {
if excerpt.len() > max_len {
break;
}
excerpt.push_str(line);
excerpt.push('\n');
if line.trim().starts_with("## ") && excerpt.len() > (max_len / 2) {
break;
}
}
crate::formatting::truncate_byte_budget(&excerpt, max_len, "...\n")
}
#[must_use]
pub fn env_flag_enabled(var_name: &str) -> bool {
std::env::var(var_name).ok().is_some_and(|value| {
matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on" | "debug")
})
}
#[must_use]
pub fn parse_bool_env_value(value: &str) -> Option<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Some(true),
"0" | "false" | "no" | "off" => Some(false),
_ => None,
}
}
#[must_use]
pub fn parse_env_bool(name: &str, default: bool) -> bool {
std::env::var(name)
.ok()
.and_then(|value| parse_bool_env_value(&value))
.unwrap_or(default)
}
pub fn safe_replace_text(content: &str, old_str: &str, new_str: &str) -> Result<String> {
if old_str.is_empty() {
return Err(anyhow::anyhow!("old_string cannot be empty"));
}
if !content.contains(old_str) {
return Err(anyhow::anyhow!("Text '{old_str}' not found in content"));
}
Ok(content.replace(old_str, new_str))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn readme_excerpt_does_not_split_utf8() {
let markdown = "你".repeat(700);
assert_eq!(extract_readme_excerpt(&markdown, 1201), format!("{}...\n", "你".repeat(400)));
}
#[test]
fn parse_bool_env_value_accepts_canonical_sets() {
for truthy in ["1", "true", "YES", " On ", "on"] {
assert_eq!(parse_bool_env_value(truthy), Some(true), "{truthy}");
}
for falsy in ["0", "false", "NO", " Off ", "off"] {
assert_eq!(parse_bool_env_value(falsy), Some(false), "{falsy}");
}
for unrecognized in ["", "debug", "2", "maybe"] {
assert_eq!(parse_bool_env_value(unrecognized), None, "{unrecognized}");
}
}
#[test]
fn parse_env_bool_falls_back_to_default_when_unset_or_unrecognized() {
assert!(!parse_env_bool("VTCODE_ENV_BOOL_TEST_DEFINITELY_UNSET", false));
assert!(parse_env_bool("VTCODE_ENV_BOOL_TEST_DEFINITELY_UNSET", true));
let guard = crate::env_lock::lock();
guard.set_var("VTCODE_ENV_BOOL_TEST_VALUE", "yes");
assert!(parse_env_bool("VTCODE_ENV_BOOL_TEST_VALUE", false));
guard.set_var("VTCODE_ENV_BOOL_TEST_VALUE", "bogus");
assert!(!parse_env_bool("VTCODE_ENV_BOOL_TEST_VALUE", false));
}
}