use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
static VERBOSE_LOG: OnceLock<Mutex<Option<VerboseLog>>> = OnceLock::new();
struct VerboseLog {
path: PathBuf,
file: File,
}
pub(crate) fn init() {
let mutex = VERBOSE_LOG.get_or_init(|| Mutex::new(None));
let Ok(mut guard) = mutex.lock() else { return };
if let Some((path, file)) = try_create_log_file() {
*guard = Some(VerboseLog { path, file });
}
}
pub(crate) fn write_line(line: &str) {
if let Some(mutex) = VERBOSE_LOG.get()
&& let Ok(mut guard) = mutex.lock()
&& let Some(log) = guard.as_mut()
{
let _ = writeln!(log.file, "{}", line);
let _ = log.file.flush();
}
}
pub(crate) fn log_file_path() -> Option<PathBuf> {
VERBOSE_LOG.get().and_then(|mutex| {
mutex
.lock()
.ok()
.and_then(|guard| guard.as_ref().map(|log| log.path.clone()))
})
}
fn try_create_log_file() -> Option<(PathBuf, File)> {
let repo = worktrunk::git::Repository::current().ok()?;
let log_dir = repo.wt_logs_dir();
std::fs::create_dir_all(&log_dir).ok()?;
let path = log_dir.join("verbose.log");
let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&path)
.ok()?;
Some((path, file))
}