Radish alpha
r
rad:z39mP9rQAaGmERfUMPULfPUi473tY
Radicle terminal user interface
Radicle
Git
bin: Write append-only log to XDG state directory
Erik Kundt committed 3 months ago
commit 79864c7421283714109122b5c26b6a08ae817cc6
parent 96f49a8
2 files changed +40 -19
modified bin/log.rs
@@ -1,32 +1,23 @@
use std::fs;
-
use std::time::SystemTime;
-

-
use anyhow::bail;
-

-
use homedir::my_home;

use log::LevelFilter;

-
const PATH: &str = ".radicle-tui/logs";
-
const PREFIX: &str = "rad-tui-";
+
use crate::settings;

-
/// Enables logging to `$HOME/.radicle-tui/logs/`. Creates folder if it does not
-
/// exist.
-
pub fn enable() -> Result<(), anyhow::Error> {
-
    match my_home()? {
-
        Some(home) => {
-
            let path = format!("{}/{}", home.to_string_lossy(), PATH);
-
            let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
+
const FILE_PREFIX: &str = "rad-tui";

+
pub fn enable() -> Result<(), anyhow::Error> {
+
    match settings::get_state_path() {
+
        Ok(path) => {
            fs::create_dir_all(path.clone())?;

-
            simple_logging::log_to_file(
-
                format!("{path}/{PREFIX}{}.log", now.as_millis()),
-
                LevelFilter::Info,
-
            )?;
+
            let file = fs::OpenOptions::new()
+
                .append(true)
+
                .open(format!("{}/{FILE_PREFIX}.log", path.to_string_lossy()))?;
+
            simple_logging::log_to(file, LevelFilter::Info);

            Ok(())
        }
-
        None => bail!("Failed to read home directory"),
+
        Err(err) => Err(anyhow::Error::from(err)),
    }
}
modified bin/settings.rs
@@ -1,4 +1,10 @@
use std::collections::HashMap;
+
use std::env;
+
use std::path::PathBuf;
+

+
use thiserror::Error;
+

+
use homedir::my_home;

use radicle_tui as tui;
use tui::ui::theme::Theme;
@@ -7,6 +13,14 @@ static THEME_RADICLE: &str = "Radicle";

pub type ThemeBundleId = String;

+
#[derive(Error, Debug)]
+
pub enum Error {
+
    #[error(
+
        "could not resolve home directory ($HOME is not set and `/etc/passwd` does not resolve)"
+
    )]
+
    Home,
+
}
+

/// `ThemeMode` defines which theme is selected from a `ThemeBundle`. It can
/// be either `light``, `dark`` or `auto``, which sets the mode depending on
/// the terminal background luma.
@@ -72,3 +86,19 @@ impl Default for Settings {
        }
    }
}
+

+
pub fn get_state_path() -> Result<PathBuf, Error> {
+
    let base = match env::var("XDG_STATE_HOME") {
+
        Ok(path) => PathBuf::from(path),
+
        Err(err) => {
+
            log::debug!("Could not read `XDG_STATE_HOME`: {err}");
+
            my_home()
+
                .ok()
+
                .flatten()
+
                .ok_or(Error::Home)?
+
                .join(".local/state")
+
        }
+
    };
+

+
    Ok(base.join("radicle-tui"))
+
}