whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
Documentation
//! XDG on Unix and known-folder paths on Windows.
//!
//! Every on-disk location is resolved from `--config-dir` / `--cache-dir`
//! or from the directories crate. Product environment variables are ignored.

use std::path::{Path, PathBuf};

use crate::error::Error;

/// Resolved jail for config, cache, and the optional active-target marker.
#[derive(Debug, Clone)]
pub struct AppPaths {
    /// Directory that holds `config.toml`.
    pub config_dir: PathBuf,
    /// Directory that holds models and the catalog.
    pub cache_dir: PathBuf,
    /// Directory that holds the opt-in active target marker.
    pub state_dir: PathBuf,
}

impl AppPaths {
    /// Build paths from explicit flags or the platform project dirs.
    pub fn resolve(config_dir: Option<&Path>, cache_dir: Option<&Path>) -> Result<Self, Error> {
        let dirs = directories::ProjectDirs::from("dev", "aguiar", "whisper-nvidia-cli");
        let config_dir = match config_dir {
            Some(p) => p.to_path_buf(),
            None => dirs
                .as_ref()
                .map(|d| d.config_dir().to_path_buf())
                .ok_or_else(|| Error::Config("cannot resolve config directory".into()))?,
        };
        let cache_dir = match cache_dir {
            Some(p) => p.to_path_buf(),
            None => dirs
                .as_ref()
                .map(|d| d.data_local_dir().to_path_buf())
                .ok_or_else(|| Error::Config("cannot resolve cache directory".into()))?,
        };
        let state_dir = cache_dir.join("state");
        Ok(Self {
            config_dir,
            cache_dir,
            state_dir,
        })
    }

    /// `config.toml` path.
    pub fn config_file(&self) -> PathBuf {
        self.config_dir.join("config.toml")
    }

    /// Persisted catalog of official model seeds.
    pub fn catalog_file(&self) -> PathBuf {
        self.cache_dir.join("catalog.toml")
    }

    /// Directory of downloaded `ggml-*.bin` files.
    pub fn models_dir(&self) -> PathBuf {
        self.cache_dir.join("models")
    }

    /// Scratch space for helper extraction, inside the cache jail.
    ///
    /// Keeping it under `--cache-dir` means a test can assert "no residue"
    /// without scanning the whole system temp directory.
    pub fn work_dir(&self) -> PathBuf {
        self.cache_dir.join("work")
    }

    /// Opt-in active target. Never read unless `--use-active` is set.
    pub fn active_target_file(&self) -> PathBuf {
        self.state_dir.join("active-target")
    }

    /// Ensure config, cache, models, and state directories exist.
    pub fn ensure(&self) -> Result<(), Error> {
        std::fs::create_dir_all(&self.config_dir)?;
        std::fs::create_dir_all(&self.cache_dir)?;
        std::fs::create_dir_all(self.models_dir())?;
        std::fs::create_dir_all(self.work_dir())?;
        std::fs::create_dir_all(&self.state_dir)?;
        Ok(())
    }
}

/// Write `body` to `path` through a tracked temporary and a rename.
///
/// Two call sites persist TOML this way — the config store and the model
/// catalog — and only one of them tracked its temporary. A forced exit skips
/// destructors, so the untracked one left `catalog.toml.tmp` in the cache and
/// broke the "no half-written file" invariant FR-039 promises. Keeping the
/// sequence in one place is what stops the third copy from being written
/// wrong: `register_temp` before the file exists, rename, `release_temp`.
pub fn write_atomic(path: &Path, body: &str) -> Result<(), Error> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp = path.with_extension("toml.tmp");
    crate::signal::register_temp(&tmp);
    std::fs::write(&tmp, body)?;
    std::fs::rename(&tmp, path)?;
    crate::signal::release_temp(&tmp);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The temporary must not survive a successful write, and the destination
    /// must hold exactly what was handed in.
    #[test]
    fn write_atomic_leaves_no_temporary() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let target = dir.path().join("nested").join("thing.toml");
        write_atomic(&target, "key = 1\n").expect("write");

        assert_eq!(
            std::fs::read_to_string(&target).expect("read back"),
            "key = 1\n"
        );
        assert!(
            !target.with_extension("toml.tmp").exists(),
            "the temporary outlived a successful write"
        );
    }

    #[test]
    fn explicit_flags_win() {
        let p = AppPaths::resolve(Some(Path::new("/tmp/cfg")), Some(Path::new("/tmp/cache")))
            .expect("resolve");
        assert_eq!(p.config_file(), PathBuf::from("/tmp/cfg/config.toml"));
        assert_eq!(p.models_dir(), PathBuf::from("/tmp/cache/models"));
    }

    /// Exercise the branch that `explicit_flags_win` never reaches: the
    /// platform project directories used when both flags are absent.
    #[test]
    fn default_resolve_is_absolute_platform_dir() {
        let p = AppPaths::resolve(None, None).expect("resolve platform dirs");

        assert!(
            p.config_dir.is_absolute(),
            "config_dir must be absolute: {}",
            p.config_dir.display()
        );
        assert!(
            p.cache_dir.is_absolute(),
            "cache_dir must be absolute: {}",
            p.cache_dir.display()
        );
        assert!(
            p.state_dir.is_absolute(),
            "state_dir must be absolute: {}",
            p.state_dir.display()
        );

        assert!(p.config_file().ends_with("config.toml"));
        assert!(p.catalog_file().ends_with("catalog.toml"));
        assert!(p.models_dir().ends_with("models"));
        assert!(p.active_target_file().ends_with("active-target"));

        // The state directory always hangs off the cache directory.
        assert!(p.state_dir.starts_with(&p.cache_dir));

        // FR-050: XDG layout on Linux. The user name is never assumed.
        #[cfg(target_os = "linux")]
        {
            let config = p.config_dir.to_string_lossy();
            let cache = p.cache_dir.to_string_lossy();
            assert!(
                config.contains(".config") || cache.contains(".local"),
                "expected an XDG layout, got config={config} cache={cache}"
            );
        }
    }
}