Lines
66.67 %
Functions
85.71 %
Branches
100 %
//! The local TUI's log file: the alternate screen has no room for log lines.
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
const STATE_SUFFIX: &str = "nomisync/tui.log";
fn non_empty(value: Option<&str>) -> Option<&str> {
value.filter(|value| !value.is_empty())
}
/// `$XDG_STATE_HOME/nomisync/tui.log`, else `$HOME/.local/state/nomisync/tui.log`.
pub fn log_path(xdg_state_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
match (non_empty(xdg_state_home), non_empty(home)) {
(Some(state), _) => Some(Path::new(state).join(STATE_SUFFIX)),
(None, Some(home)) => Some(Path::new(home).join(".local/state").join(STATE_SUFFIX)),
(None, None) => None,
/// Opens `path` for appending, creating its directory.
pub fn open(path: &Path) -> Result<File, String> {
let created = match path.parent() {
Some(dir) => fs::create_dir_all(dir),
None => Ok(()),
};
created
.and_then(|()| OpenOptions::new().create(true).append(true).open(path))
.map_err(|err| format!("cannot open the log file {}: {err}", path.display()))
/// The log file named by the environment.
pub fn open_from_env() -> Result<File, String> {
let state = std::env::var("XDG_STATE_HOME").ok();
let home = std::env::var("HOME").ok();
let path = log_path(state.as_deref(), home.as_deref())
.ok_or("neither XDG_STATE_HOME nor HOME is set, so there is no place for the log file")?;
open(&path)
#[cfg(test)]
mod tests;