Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.configuration.user_location

Requirements index · View definition

evidence Valid

Requirement

Habeas MUST locate its per-user configuration at $XDG_CONFIG_HOME/habeas/config.toml on Unix when XDG_CONFIG_HOME is an absolute, nonempty path, otherwise at $HOME/.config/habeas/config.toml. On Windows it MUST use %APPDATA%/habeas/config.toml. HOME and APPDATA MUST likewise be absolute, nonempty paths to be used. If no usable base directory can be determined, an operation requiring user configuration MUST fail with an explanatory diagnostic naming the variable.

The same user configuration MUST be usable across projects. Its location MUST NOT be selected relative to the current project or changed by project settings. User-local preferences for a project MAY remain in the user configuration; workspace settings MUST use habeas.toml under cite requirements.configuration.workspace_location.

Rationale

I found no gaps against requirements.configuration.user_location.

Obligations and the code that carries them out

  • Unix path from XDG_CONFIG_HOME or HOME. src/config.rs#fn[user_config_path_from] handles this. It takes XDG_CONFIG_HOME when absolute_directory accepts it. Otherwise it uses required_directory(HOME).join(".config"), then appends habeas/config.toml.
  • Windows path. The same function uses required_directory(&lookup, "APPDATA") and appends habeas/config.toml. ConfigPlatform::current in src/config.rs#impl[ConfigPlatform]/fn[current] selects the platform.
  • Absolute, nonempty XDG_CONFIG_HOME, HOME and APPDATA. src/config.rs#fn[absolute_directory] keeps a value only if PathBuf::is_absolute holds. An empty string is not absolute, so it is rejected too.
  • Failure with a diagnostic naming the variable. src/config.rs#fn[required_directory] returns an io::Error whose message contains the variable name. src/config.rs#fn[resolve_authoring] propagates it with user_config_path()?, so an operation that needs user configuration fails.
  • Location independent of project and project settings. user_config_path and user_config_path_from take no project or workspace input. They read only platform and environment values, so the location cannot be set relative to a project or by project settings. Nothing in src/config.rs or src/redaction.rs that uses user_config_path reads a location from a project setting.
  • Workspace settings in habeas.toml. This is a citation of requirements.configuration.workspace_location, which I did not reassess.

Tests

  • tests/configuration.rs#fn[locations_use_absolute_xdg_values_and_platform_fallbacks] checks four cases: an absolute XDG_CONFIG_HOME, fallback to HOME when XDG_CONFIG_HOME is empty or relative, the Windows APPDATA path, and an error when nothing is set.
  • tests/configuration.rs#fn[base_directories_must_be_absolute_and_nonempty] checks that empty or relative HOME and APPDATA are rejected, and that the error message contains the variable name. It also checks that a relative XDG_CONFIG_HOME falls back to an absolute HOME.
  • Both tests carry {test} references to requirements.configuration.user_location.
  • The “not project-relative” obligation has no dedicated test. It holds structurally, because the function has no project input, so it has no conditional or transformation to exercise.

Unspecified behavior: I found none.

Inputs

Implementation

Input 3: outline src/config.rs enum[ConfigPlatform]
// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
#[derive(Clone, Copy, Debug)]
pub enum ConfigPlatform {
    Unix,
    Windows,
}
Input 4: outline src/config.rs impl[ConfigPlatform]/fn[current]
    // {impl}`requirements.configuration.user_location`
    // {impl}`requirements.configuration.state_location`
    pub fn current() -> Self {
        if cfg!(windows) {
            Self::Windows
        } else {
            Self::Unix
        }
    }
Input 5: outline src/config.rs fn[user_config_path]
// {impl}`requirements.configuration.user_location`
pub fn user_config_path() -> io::Result<PathBuf> {
    user_config_path_from(ConfigPlatform::current(), |name| std::env::var_os(name))
}
Input 6: outline src/config.rs fn[user_config_path_from]
// {impl}`requirements.configuration.user_location`
pub fn user_config_path_from(
    platform: ConfigPlatform,
    lookup: impl Fn(&str) -> Option<OsString>,
) -> io::Result<PathBuf> {
    let base = match platform {
        ConfigPlatform::Windows => required_directory(&lookup, "APPDATA")?,
        ConfigPlatform::Unix => match absolute_directory(&lookup, "XDG_CONFIG_HOME") {
            Some(path) => path,
            None => required_directory(&lookup, "HOME")?.join(".config"),
        },
    };
    Ok(base.join("habeas/config.toml"))
}
Input 7: outline src/config.rs fn[absolute_directory]
// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
fn absolute_directory(lookup: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<PathBuf> {
    lookup(name)
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
}
Input 8: outline src/config.rs fn[required_directory]
// {impl}`requirements.configuration.user_location`
// {impl}`requirements.configuration.state_location`
fn required_directory(
    lookup: &impl Fn(&str) -> Option<OsString>,
    name: &str,
) -> io::Result<PathBuf> {
    absolute_directory(lookup, name).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::NotFound,
            format!("cannot determine Habeas directory: {name} must be an absolute, nonempty path"),
        )
    })
}

Tests

Input 9: outline tests/configuration.rs fn[locations_use_absolute_xdg_values_and_platform_fallbacks]
// {test}`requirements.configuration.user_location`
// {test}`requirements.configuration.state_location`
#[test]
fn locations_use_absolute_xdg_values_and_platform_fallbacks() {
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let config = dir.path().join("config");
    let state = dir.path().join("state");
    let vars = BTreeMap::from([
        ("HOME", home.as_os_str().to_owned()),
        ("XDG_CONFIG_HOME", config.as_os_str().to_owned()),
        ("XDG_STATE_HOME", state.as_os_str().to_owned()),
    ]);
    let lookup = |name: &str| vars.get(name).cloned();
    assert_eq!(
        user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
        config.join("habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
        state.join("habeas")
    );
    for invalid_xdg in ["", "relative"] {
        let lookup = |name: &str| {
            Some(if name == "HOME" {
                home.as_os_str().to_owned()
            } else {
                OsString::from(invalid_xdg)
            })
        };
        assert_eq!(
            user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
            home.join(".config/habeas/config.toml")
        );
        assert_eq!(
            state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
            home.join(".local/state/habeas")
        );
    }
    let windows = |name: &str| match name {
        "APPDATA" => Some(config.as_os_str().to_owned()),
        "LOCALAPPDATA" => Some(state.as_os_str().to_owned()),
        _ => None,
    };
    assert_eq!(
        user_config_path_from(ConfigPlatform::Windows, windows).unwrap(),
        config.join("habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Windows, windows).unwrap(),
        state.join("habeas/state")
    );
    assert!(user_config_path_from(ConfigPlatform::Unix, |_| None).is_err());
    assert!(state_root_from(ConfigPlatform::Windows, |_| None).is_err());
}
Input 10: outline tests/configuration.rs fn[base_directories_must_be_absolute_and_nonempty]
// {test}`requirements.configuration.user_location`
// {test}`requirements.configuration.state_location`
#[test]
fn base_directories_must_be_absolute_and_nonempty() {
    use std::ffi::OsString;
    let only = |name: &'static str, value: &'static str| {
        move |key: &str| (key == name).then(|| OsString::from(value))
    };
    for (platform, variable) in [
        (ConfigPlatform::Unix, "HOME"),
        (ConfigPlatform::Windows, "APPDATA"),
    ] {
        for value in ["", "relative/home"] {
            let error = user_config_path_from(platform, only(variable, value)).unwrap_err();
            assert!(error.to_string().contains(variable), "{error}");
        }
    }
    for (platform, variable) in [
        (ConfigPlatform::Unix, "HOME"),
        (ConfigPlatform::Windows, "LOCALAPPDATA"),
    ] {
        for value in ["", "relative/home"] {
            let error = state_root_from(platform, only(variable, value)).unwrap_err();
            assert!(error.to_string().contains(variable), "{error}");
        }
    }
    // A relative XDG value falls back to an absolute HOME.
    let lookup = |key: &str| match key {
        "XDG_CONFIG_HOME" | "XDG_STATE_HOME" => Some(OsString::from("relative")),
        "HOME" => Some(OsString::from("/home/user")),
        _ => None,
    };
    assert_eq!(
        user_config_path_from(ConfigPlatform::Unix, lookup).unwrap(),
        std::path::PathBuf::from("/home/user/.config/habeas/config.toml")
    );
    assert_eq!(
        state_root_from(ConfigPlatform::Unix, lookup).unwrap(),
        std::path::PathBuf::from("/home/user/.local/state/habeas")
    );
}

Referenced definitions

Input 2: requirements selection requirements.configuration.workspace_location
:::{req} workspace_location
Habeas MUST search from its invocation directory upward for the nearest enclosing
`habeas.toml`. It MUST use that file alone, without merging ancestor workspace
files. A library operation given a project root MUST search from that root unless
its current directory is inside the project, in which case it MUST start there.
The directory containing the selected file defines the base for its relative
paths; it does not replace the Cargo and mdBook project root. A missing file MUST
mean absent workspace settings. Discovery MUST report unreadable candidate files
rather than silently selecting an ancestor. Loading MUST NOT create the file.
:::

Other sources

Input 1: requirements selection requirements.configuration.user_location
:::{req} user_location
Habeas MUST locate its per-user configuration at
`$XDG_CONFIG_HOME/habeas/config.toml` on Unix when XDG_CONFIG_HOME is an absolute,
nonempty path, otherwise at `$HOME/.config/habeas/config.toml`. On Windows it MUST
use `%APPDATA%/habeas/config.toml`. `HOME` and `APPDATA` MUST likewise be
absolute, nonempty paths to be used. If no usable base directory can be
determined, an operation requiring user configuration MUST fail with an
explanatory diagnostic naming the variable.

The same user configuration MUST be usable across projects. Its location MUST
NOT be selected relative to the current project or changed by project settings.
User-local preferences for a project MAY remain in the user configuration;
workspace settings MUST use `habeas.toml` under
{cite}`requirements.configuration.workspace_location`.
:::