1
//! The local TUI's log file: the alternate screen has no room for log lines.
2

            
3
use std::fs::{self, File, OpenOptions};
4
use std::path::{Path, PathBuf};
5

            
6
const STATE_SUFFIX: &str = "nomisync/tui.log";
7

            
8
10
fn non_empty(value: Option<&str>) -> Option<&str> {
9
10
    value.filter(|value| !value.is_empty())
10
10
}
11

            
12
/// `$XDG_STATE_HOME/nomisync/tui.log`, else `$HOME/.local/state/nomisync/tui.log`.
13
5
pub fn log_path(xdg_state_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
14
5
    match (non_empty(xdg_state_home), non_empty(home)) {
15
1
        (Some(state), _) => Some(Path::new(state).join(STATE_SUFFIX)),
16
2
        (None, Some(home)) => Some(Path::new(home).join(".local/state").join(STATE_SUFFIX)),
17
2
        (None, None) => None,
18
    }
19
5
}
20

            
21
/// Opens `path` for appending, creating its directory.
22
3
pub fn open(path: &Path) -> Result<File, String> {
23
3
    let created = match path.parent() {
24
3
        Some(dir) => fs::create_dir_all(dir),
25
        None => Ok(()),
26
    };
27
3
    created
28
2
        .and_then(|()| OpenOptions::new().create(true).append(true).open(path))
29
1
        .map_err(|err| format!("cannot open the log file {}: {err}", path.display()))
30
3
}
31

            
32
/// The log file named by the environment.
33
pub fn open_from_env() -> Result<File, String> {
34
    let state = std::env::var("XDG_STATE_HOME").ok();
35
    let home = std::env::var("HOME").ok();
36
    let path = log_path(state.as_deref(), home.as_deref())
37
        .ok_or("neither XDG_STATE_HOME nor HOME is set, so there is no place for the log file")?;
38
    open(&path)
39
}
40

            
41
#[cfg(test)]
42
mod tests;