use std::{
env, fs,
path::Path,
time::{SystemTime, UNIX_EPOCH},
};
pub fn dump_html(context: &str, html: &str) {
if env::var("STEAM_USER_DEBUG_HTML").is_err() {
return;
}
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let filename = format!("debug_html_{}_{}.html", context, timestamp);
let path = Path::new(&filename);
let dump_dir = Path::new("debug_dumps");
let final_path = match fs::create_dir_all(dump_dir) {
Ok(_) => dump_dir.join(&filename),
Err(_) => path.to_path_buf(),
};
if let Err(e) = fs::write(&final_path, html) {
tracing::error!("Failed to dump debug HTML to {:?}: {}", final_path, e);
} else {
tracing::debug!("Debug HTML dumped to {:?}", final_path);
}
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
#[test]
#[serial_test::serial]
fn test_dump_html_creates_file() {
unsafe {
env::set_var("STEAM_USER_DEBUG_HTML", "1");
}
let context = "test_context";
let html = "<html><body>Test</body></html>";
dump_html(context, html);
let dump_dir = Path::new("debug_dumps");
let exists = if dump_dir.exists() {
fs::read_dir(dump_dir).unwrap().any(|entry| {
let entry = entry.unwrap();
let name = entry.file_name().into_string().unwrap();
name.starts_with("debug_html_test_context")
})
} else {
fs::read_dir(".").unwrap().any(|entry| {
let entry = entry.unwrap();
let name = entry.file_name().into_string().unwrap();
name.starts_with("debug_html_test_context")
})
};
assert!(exists, "Debug HTML file was not created");
unsafe {
env::remove_var("STEAM_USER_DEBUG_HTML");
}
if dump_dir.exists() {
for entry in fs::read_dir(dump_dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
let name = entry.file_name().into_string().unwrap();
if name.starts_with("debug_html_test_context") {
let _ = fs::remove_file(path);
}
}
}
}
}