hh-core 0.1.0-beta.1

Halfhand core: storage, blob store, event model, config
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Configuration and path resolution (SRS §2.3, §4.2).
//!
//! Precedence is **default < config file < `HH_DATA_DIR` env**. Unknown config
//! keys emit a single-line warning on stderr but never prevent startup, per
//! SRS §4.2 ("All keys optional; unknown keys warn, never fail").

use crate::error::{ConfigError, Result};
use serde::Deserialize;
use std::fmt;
use std::path::{Path, PathBuf};

/// Byte-size parser for values like `4MiB`, `512KiB`, `100B`.
///
/// Accepts `B`, `KB`/`KiB`, `MB`/`MiB`, `GB`/`GiB` (case-insensitive). Binary
/// (`KiB`) and decimal (`KB`) suffixes are both treated as binary multiples
/// (1024-based) for simplicity, matching how the rest of the tool talks about
/// file sizes; a bare integer is interpreted as bytes.
pub fn parse_bytes(input: &str) -> std::result::Result<u64, String> {
    let s = input.trim();
    if s.is_empty() {
        return Err("empty byte size".into());
    }
    // Split into numeric prefix and suffix at the first non-digit/non-dot.
    let split = s
        .find(|c: char| !c.is_ascii_digit() && c != '.')
        .unwrap_or(s.len());
    let num_part = &s[..split];
    let suffix = s[split..].trim().to_ascii_lowercase();
    // Integer + optional fractional part, parsed without f64 to stay exact.
    let (int_part, frac_part) = match num_part.split_once('.') {
        Some((i, f)) => (i, f),
        None => (num_part, ""),
    };
    if int_part.is_empty() && frac_part.is_empty() {
        return Err(format!("`{s}` is not a number"));
    }
    if !int_part.chars().all(|c| c.is_ascii_digit())
        || !frac_part.chars().all(|c| c.is_ascii_digit())
    {
        return Err(format!("`{s}` is not a number"));
    }
    let mult: u128 = match suffix.as_str() {
        "" | "b" => 1,
        "k" | "kb" | "kib" => 1024,
        "m" | "mb" | "mib" => 1024 * 1024,
        "g" | "gb" | "gib" => 1024 * 1024 * 1024,
        other => return Err(format!("unknown byte-size suffix `{other}`")),
    };
    let int_val: u128 = int_part.parse().unwrap_or(0);
    let total = int_val
        .checked_mul(mult)
        .ok_or_else(|| "byte size too large".to_string())?;
    let frac_val: u128 = if frac_part.is_empty() {
        0
    } else {
        frac_part.parse().unwrap_or(0)
    };
    let denom = 10u128
        .checked_pow(u32::try_from(frac_part.len()).unwrap_or(0))
        .ok_or_else(|| "byte size too large".to_string())?;
    let frac_contrib = frac_val
        .checked_mul(mult)
        .ok_or_else(|| "byte size too large".to_string())?
        .checked_div(denom)
        .unwrap_or(0);
    let bytes = total
        .checked_add(frac_contrib)
        .ok_or_else(|| "byte size too large".to_string())?;
    u64::try_from(bytes).map_err(|_| "byte size too large".to_string())
}

/// Replay color theme (SRS §4.2 `[replay] theme`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Theme {
    /// Follow the terminal's reported color scheme.
    #[default]
    Auto,
    /// Force dark.
    Dark,
    /// Force light.
    Light,
}

/// Record-time options (SRS §4.2 `[record]`).
#[derive(Debug, Clone, PartialEq)]
pub struct RecordConfig {
    /// Max file size to capture, in bytes (default 4 MiB).
    pub max_file_size: u64,
    /// Whether to record user keystrokes (default off; NFR-4).
    pub record_input: bool,
    /// Whether to store binary file contents (default off).
    pub record_binary: bool,
    /// Extra ignore patterns extending the built-in list + .gitignore.
    pub ignore: Vec<String>,
}

impl Default for RecordConfig {
    fn default() -> Self {
        Self {
            max_file_size: 4 * 1024 * 1024,
            record_input: false,
            record_binary: false,
            ignore: Vec::new(),
        }
    }
}

/// Storage options (SRS §4.2 `[storage]`).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StorageConfig {
    /// Data directory override; empty means platform default.
    pub data_dir: PathBuf,
}

/// Replay options (SRS §4.2 `[replay]`).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ReplayConfig {
    /// Color theme.
    pub theme: Theme,
}

/// The full configuration.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Config {
    /// `[record]`
    pub record: RecordConfig,
    /// `[storage]`
    pub storage: StorageConfig,
    /// `[replay]`
    pub replay: ReplayConfig,
}

impl Config {
    /// Load configuration from `config_path`, falling back to [`Default`] when
    /// the file does not exist. Unknown keys warn on stderr but never fail.
    pub fn load(config_path: &Path) -> Result<Self> {
        let mut cfg = Self::default();
        let Some(table) = read_or_default_config(config_path)? else {
            return Ok(cfg);
        };
        warn_unknown_keys(&table);
        merge_table(&mut cfg, &table)?;
        Ok(cfg)
    }
}

/// Read the config file into a TOML table, returning `Ok(None)` if it does not
/// exist (not an error — the file is entirely optional per SRS §4.2).
fn read_or_default_config(path: &Path) -> Result<Option<toml::Table>> {
    match std::fs::read_to_string(path) {
        Ok(contents) => {
            let table: toml::Table = toml::from_str(&contents).map_err(|e| ConfigError::Parse {
                path: path.to_path_buf(),
                source: e,
            })?;
            Ok(Some(table))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(ConfigError::Read {
            path: path.to_path_buf(),
            source: e,
        }
        .into()),
    }
}

/// Known top-level tables and their allowed keys.
const KNOWN: &[(&str, &[&str])] = &[
    (
        "record",
        &["max_file_size", "record_input", "record_binary", "ignore"],
    ),
    ("storage", &["data_dir"]),
    ("replay", &["theme"]),
];

/// Walk the parsed table and warn on stderr about any key we do not recognize.
fn warn_unknown_keys(table: &toml::Table) {
    for (key, value) in table {
        let known_keys = KNOWN
            .iter()
            .find_map(|(k, keys)| (*k == key).then_some(*keys));
        match known_keys {
            None => eprintln!("warn: config: unknown top-level key `{key}` ignored"),
            Some(allowed) => {
                if let Some(sub) = value.as_table() {
                    for (subkey, _) in sub {
                        if !allowed.contains(&subkey.as_str()) {
                            eprintln!("warn: config: unknown key `{key}.{subkey}` ignored");
                        }
                    }
                }
            }
        }
    }
}

/// Merge a parsed TOML table into a [`Config`], interpreting known values.
fn merge_table(cfg: &mut Config, table: &toml::Table) -> Result<()> {
    if let Some(record) = table.get("record").and_then(toml::Value::as_table) {
        if let Some(v) = record.get("max_file_size") {
            cfg.record.max_file_size = value_to_bytes(v)?;
        }
        if let Some(v) = record.get("record_input").and_then(toml::Value::as_bool) {
            cfg.record.record_input = v;
        }
        if let Some(v) = record.get("record_binary").and_then(toml::Value::as_bool) {
            cfg.record.record_binary = v;
        }
        if let Some(v) = record.get("ignore").and_then(toml::Value::as_array) {
            cfg.record.ignore = v
                .iter()
                .filter_map(toml::Value::as_str)
                .map(String::from)
                .collect();
        }
    }
    if let Some(storage) = table.get("storage").and_then(toml::Value::as_table) {
        if let Some(v) = storage.get("data_dir").and_then(toml::Value::as_str) {
            cfg.storage.data_dir = PathBuf::from(v);
        }
    }
    if let Some(replay) = table.get("replay").and_then(toml::Value::as_table) {
        if let Some(v) = replay.get("theme").and_then(toml::Value::as_str) {
            cfg.replay.theme = match v {
                "auto" => Theme::Auto,
                "dark" => Theme::Dark,
                "light" => Theme::Light,
                other => {
                    return Err(ConfigError::Value(format!(
                        "replay.theme `{other}` not one of auto|dark|light"
                    ))
                    .into())
                }
            };
        }
    }
    Ok(())
}

fn value_to_bytes(v: &toml::Value) -> Result<u64> {
    match v {
        toml::Value::Integer(n) => u64::try_from(*n).map_err(|_| {
            ConfigError::Value(format!("max_file_size cannot be negative: {n}")).into()
        }),
        toml::Value::String(s) => Ok(parse_bytes(s).map_err(ConfigError::Value)?),
        other => Err(ConfigError::Value(format!(
            "max_file_size must be a string or integer, got {}",
            other.type_str()
        ))
        .into()),
    }
}

/// Resolved on-disk locations for the Halfhand data directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paths {
    /// The data directory itself (`$XDG_DATA_HOME/halfhand` by default).
    pub data_dir: PathBuf,
    /// The config file (`$XDG_CONFIG_HOME/halfhand/config.toml`).
    pub config_path: PathBuf,
    /// The SQLite database file (`<data_dir>/hh.db`).
    pub db_path: PathBuf,
    /// The blob store root (`<data_dir>/blobs`).
    pub blobs_dir: PathBuf,
}

impl Paths {
    /// Resolve paths from a loaded [`Config`] and the process environment.
    ///
    /// Precedence (SRS §2.3): `HH_DATA_DIR` env > `[storage] data_dir` file >
    /// platform default. The config file location is always the platform
    /// default (not overridable via config, only via `XDG_CONFIG_HOME`).
    pub fn resolve(config: &Config) -> Result<Self> {
        let env_dir = std::env::var_os("HH_DATA_DIR").filter(|s| !s.is_empty());
        let data_dir = if let Some(d) = env_dir {
            PathBuf::from(d)
        } else if !config.storage.data_dir.as_os_str().is_empty() {
            config.storage.data_dir.clone()
        } else {
            platform_data_dir()?
        };
        Ok(Self {
            db_path: data_dir.join("hh.db"),
            blobs_dir: data_dir.join("blobs"),
            config_path: platform_config_path()?,
            data_dir,
        })
    }

    /// Construct paths with an explicit data directory (used by tests so they
    /// never touch the real data directory, per CLAUDE.md testing standards).
    pub fn with_data_dir(data_dir: PathBuf) -> Self {
        Self {
            db_path: data_dir.join("hh.db"),
            blobs_dir: data_dir.join("blobs"),
            config_path: data_dir.join("config.toml"),
            data_dir,
        }
    }
}

fn platform_dirs() -> Result<directories::ProjectDirs> {
    directories::ProjectDirs::from("", "", "halfhand").ok_or_else(|| {
        ConfigError::Value("cannot determine platform config/data directories (no HOME?)".into())
            .into()
    })
}

fn platform_data_dir() -> Result<PathBuf> {
    Ok(platform_dirs()?.data_dir().to_path_buf())
}

fn platform_config_path() -> Result<PathBuf> {
    Ok(platform_dirs()?.config_dir().join("config.toml"))
}

impl fmt::Display for Theme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Theme::Auto => "auto",
            Theme::Dark => "dark",
            Theme::Light => "light",
        };
        f.write_str(s)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;
    use tempfile::TempDir;

    fn write_config(dir: &Path, body: &str) -> PathBuf {
        let p = dir.join("config.toml");
        let mut f = fs::File::create(&p).unwrap();
        f.write_all(body.as_bytes()).unwrap();
        p
    }

    #[test]
    fn parse_bytes_accepts_suffixes() {
        assert_eq!(parse_bytes("4MiB").unwrap(), 4 * 1024 * 1024);
        assert_eq!(parse_bytes("512KiB").unwrap(), 512 * 1024);
        assert_eq!(parse_bytes("100B").unwrap(), 100);
        assert_eq!(parse_bytes("2048").unwrap(), 2048);
        assert!(parse_bytes("nope").is_err());
        assert!(parse_bytes("4PiB").is_err());
    }

    #[test]
    fn config_defaults() {
        let cfg = Config::default();
        assert_eq!(cfg.record.max_file_size, 4 * 1024 * 1024);
        assert!(!cfg.record.record_input);
        assert!(!cfg.record.record_binary);
        assert!(cfg.record.ignore.is_empty());
        assert_eq!(cfg.replay.theme, Theme::Auto);
        assert!(cfg.storage.data_dir.as_os_str().is_empty());
    }

    #[test]
    fn config_loads_known_keys() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            tmp.path(),
            "\
[record]
max_file_size = \"1MiB\"
record_input = true
ignore = [\"dist/\", \"*.lock\"]

[storage]
data_dir = \"/tmp/hh-from-file\"

[replay]
theme = \"dark\"
",
        );
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg.record.max_file_size, 1024 * 1024);
        assert!(cfg.record.record_input);
        assert_eq!(cfg.record.ignore, vec!["dist/", "*.lock"]);
        assert_eq!(cfg.storage.data_dir, PathBuf::from("/tmp/hh-from-file"));
        assert_eq!(cfg.replay.theme, Theme::Dark);
    }

    #[test]
    fn config_unknown_keys_warn_but_load() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(
            tmp.path(),
            "\
[record]
max_file_size = \"2MiB\"
mystery = true

[storage]
data_dir = \"/tmp/hh-unknown\"

[experimental]
feature = \"x\"
",
        );
        let cfg = Config::load(&path).unwrap();
        // Known keys still applied.
        assert_eq!(cfg.record.max_file_size, 2 * 1024 * 1024);
        assert_eq!(cfg.storage.data_dir, PathBuf::from("/tmp/hh-unknown"));
        // Unknown keys were tolerated (no panic, no error).
    }

    #[test]
    fn config_missing_file_is_default() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("does-not-exist.toml");
        let cfg = Config::load(&path).unwrap();
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn config_malformed_toml_errors() {
        let tmp = TempDir::new().unwrap();
        let path = write_config(tmp.path(), "this is = = not toml");
        assert!(Config::load(&path).is_err());
    }

    #[test]
    fn paths_precedence_default_file_env() {
        // default: no file override, no env.
        std::env::remove_var("HH_DATA_DIR");
        let cfg = Config::default();
        let default_paths = Paths::resolve(&cfg).unwrap();
        assert!(default_paths.data_dir.ends_with("halfhand"));

        // file: storage.data_dir set in config.
        let cfg_file = Config {
            storage: StorageConfig {
                data_dir: PathBuf::from("/tmp/hh-file-wins"),
            },
            ..Config::default()
        };
        let file_paths = Paths::resolve(&cfg_file).unwrap();
        assert_eq!(file_paths.data_dir, PathBuf::from("/tmp/hh-file-wins"));

        // env overrides file.
        std::env::set_var("HH_DATA_DIR", "/tmp/hh-env-wins");
        let env_paths = Paths::resolve(&cfg_file).unwrap();
        assert_eq!(env_paths.data_dir, PathBuf::from("/tmp/hh-env-wins"));
        std::env::remove_var("HH_DATA_DIR");
    }

    #[test]
    fn paths_components_are_under_data_dir() {
        let p = Paths::with_data_dir(PathBuf::from("/tmp/hh-test"));
        assert_eq!(p.db_path, PathBuf::from("/tmp/hh-test/hh.db"));
        assert_eq!(p.blobs_dir, PathBuf::from("/tmp/hh-test/blobs"));
    }
}