cookcli-core 0.37.0

Recipe, shopping list, pantry and report operations for Cooklang, extracted from CookCLI
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
//! Resolved configuration for a set of recipe operations.

use crate::{ConfigSource, CoreError};
use camino::{Utf8Path, Utf8PathBuf};
use std::ffi::OsStr;

const APP_NAME: &str = "cook";

/// Environment variable that replaces the platform configuration directory.
///
/// See [`global_config_path`]. Set it to point every global lookup — aisle,
/// pantry, `session.json`, `sync.db` — at one directory of your choosing.
pub const CONFIG_DIR_ENV: &str = "COOK_CONFIG_DIR";
pub(crate) const LOCAL_CONFIG_DIR: &str = "config";
const AUTO_AISLE: &str = "aisle.conf";
pub(crate) const AUTO_PANTRY: &str = "pantry.conf";

/// The configuration bundle every command operates against.
///
/// [`Context::new`] performs no filesystem access. Ambient configuration
/// discovery is opt-in through [`Context::discover`], so a caller that already
/// knows its configuration — an editor holding an unsaved buffer, say — never
/// has the user's `~/.config` read behind its back.
#[derive(Debug, Clone)]
pub struct Context {
    base_path: Utf8PathBuf,
    aisle: ConfigSource,
    pantry: ConfigSource,
}

impl Context {
    /// A context with no aisle or pantry configuration. Touches nothing.
    pub fn new(base_path: Utf8PathBuf) -> Self {
        Self {
            base_path,
            aisle: ConfigSource::None,
            pantry: ConfigSource::None,
        }
    }

    /// A context with aisle and pantry resolved using CookCLI's search order:
    /// `<base>/config/<name>` first, then the global configuration directory
    /// ([`global_config_path`] — `$COOK_CONFIG_DIR` when set, otherwise
    /// `~/.config/cook/<name>` on Linux and the platform equivalent
    /// elsewhere).
    ///
    /// This is the only constructor that reads ambient state, and it is
    /// explicitly opted into.
    ///
    /// Two things to know before relying on it:
    ///
    /// - **It reports no errors.** A configuration directory that cannot be
    ///   resolved at all — no home directory, or a non-UTF-8 path — is treated
    ///   as one fewer place to look, exactly as the CLI treats it. An unset
    ///   [`ConfigSource`] therefore does not distinguish "the user has no
    ///   config file" from "this machine has no home directory". Call
    ///   [`global_config_path`] directly if you need to tell those apart.
    /// - **It stats, it does not read.** Discovery only checks that each
    ///   candidate is a file; the contents are read later by
    ///   [`ConfigSource::read`]. A `Context` held across an editing session can
    ///   therefore name a file that has since been deleted, which surfaces as a
    ///   [`CoreError::Io`] from whichever command reads it rather than from
    ///   here. Re-run `discover` if the configuration may have changed.
    pub fn discover(base_path: Utf8PathBuf) -> Self {
        let aisle = Self::discover_one(&base_path, AUTO_AISLE);
        let pantry = Self::discover_one(&base_path, AUTO_PANTRY);
        Self {
            base_path,
            aisle,
            pantry,
        }
    }

    fn discover_one(base_path: &Utf8Path, name: &str) -> ConfigSource {
        // A global path that cannot be determined at all is simply one fewer
        // place to look, exactly as in the CLI. This is part of `discover`'s
        // documented contract.
        Self::search(base_path, name, global_config_path(name).ok().as_deref())
    }

    /// The search order, with the global candidate passed in.
    ///
    /// Injecting it keeps the ordering testable without the result depending
    /// on what the machine running the tests has in its home directory.
    /// `global_config_path` supplies it in production. Resolving it eagerly,
    /// where the CLI resolves it lazily, makes no observable difference: it
    /// works out the configuration directory without touching the filesystem,
    /// and the trace output is unchanged either way.
    fn search(base_path: &Utf8Path, name: &str, global: Option<&Utf8Path>) -> ConfigSource {
        let local = base_path.join(LOCAL_CONFIG_DIR).join(name);
        tracing::trace!("checking local config file: {local}");
        if local.is_file() {
            return ConfigSource::Path(local);
        }

        match global {
            Some(global) => {
                tracing::trace!("checking global config file: {global}");
                if global.is_file() {
                    ConfigSource::Path(global.to_owned())
                } else {
                    ConfigSource::None
                }
            }
            None => ConfigSource::None,
        }
    }

    /// Replace the aisle configuration, whatever discovery found.
    pub fn with_aisle(mut self, source: ConfigSource) -> Self {
        self.aisle = source;
        self
    }

    /// Replace the pantry configuration, whatever discovery found.
    pub fn with_pantry(mut self, source: ConfigSource) -> Self {
        self.pantry = source;
        self
    }

    /// The directory recipe paths and searches are resolved against.
    ///
    /// Returned exactly as it was supplied. Unlike the CLI, which canonicalises
    /// it and rejects a non-directory before building a `Context`, core neither
    /// resolves nor validates it — so a relative path is interpreted against
    /// the *process* working directory, which for an in-process editor
    /// integration is the editor's, not the project's. Pass an absolute path
    /// unless you mean that.
    pub fn base_path(&self) -> &Utf8Path {
        &self.base_path
    }

    /// The aisle configuration to categorise shopping list ingredients with.
    pub fn aisle(&self) -> &ConfigSource {
        &self.aisle
    }

    /// The pantry configuration to filter already-stocked ingredients with.
    pub fn pantry(&self) -> &ConfigSource {
        &self.pantry
    }
}

/// Resolve `name` inside the global configuration directory for `cook`.
///
/// That directory is [`CONFIG_DIR_ENV`] (`COOK_CONFIG_DIR`) when it is set to
/// a non-empty value, and otherwise the platform's own — `~/.config/cook` on
/// Linux, `~/Library/Application Support/cook` on macOS,
/// `%APPDATA%\cook\config` on Windows.
///
/// The override is the only portable way to redirect these lookups. The
/// platform directory is resolved by `directories`, which on Windows asks the
/// Known Folder API and so ignores `HOME` and `XDG_CONFIG_HOME` entirely —
/// setting those isolates a test on Unix and silently does nothing on Windows,
/// where a `cook server` under test would then find the developer's real
/// `session.json` and sync database. Tests that spawn `cook` set
/// `COOK_CONFIG_DIR` instead.
///
/// The path is returned whether or not anything exists there; nothing is
/// created.
///
/// # Errors
///
/// [`CoreError::Config`] if there is no home directory to resolve against, or
/// if the resolved directory — the override included — is not valid UTF-8.
/// Both carry no path, because the failure is that no path could be built.
pub fn global_config_path(name: &str) -> Result<Utf8PathBuf, CoreError> {
    global_config_path_in(std::env::var_os(CONFIG_DIR_ENV).as_deref(), name)
}

/// [`global_config_path`] with the override supplied rather than read.
///
/// Injecting it keeps the resolution testable: `std::env::set_var` mutates
/// process-wide state that the rest of the test binary's threads share, so a
/// test that set `COOK_CONFIG_DIR` for itself would be setting it for whatever
/// else happened to be running.
fn global_config_path_in(
    override_dir: Option<&OsStr>,
    name: &str,
) -> Result<Utf8PathBuf, CoreError> {
    // An empty value is treated as unset, as the XDG variables it stands in
    // for are: exporting `COOK_CONFIG_DIR=` should not silently resolve the
    // configuration to the process working directory.
    if let Some(dir) = override_dir.filter(|dir| !dir.is_empty()) {
        let dir =
            Utf8Path::from_path(std::path::Path::new(dir)).ok_or_else(|| CoreError::Config {
                path: None,
                message: format!(
                    "{CONFIG_DIR_ENV} is not valid utf-8, and cook only supports utf-8 paths"
                ),
            })?;
        return Ok(dir.join(name));
    }

    let dirs =
        directories::ProjectDirs::from("", "", APP_NAME).ok_or_else(|| CoreError::Config {
            path: None,
            message: format!("could not determine the home directory to locate {name}"),
        })?;
    let config = Utf8Path::from_path(dirs.config_dir()).ok_or_else(|| CoreError::Config {
        path: None,
        message: format!(
            "the configuration directory holding {name} is not valid utf-8, \
             and cook only supports utf-8 paths"
        ),
    })?;
    Ok(config.join(name))
}

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

    /// Config files are planted where discovery *would* find them, so this
    /// fails if `new` ever grows a filesystem lookup. Asserting only that the
    /// sources come back unset would pass even if `new` called `discover`.
    #[test]
    fn new_touches_nothing() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        write(&base.join("config").join("aisle.conf"), "[produce]\nleek");
        write(
            &base.join("config").join("pantry.conf"),
            "[freezer]\npeas = \"1kg\"",
        );

        let ctx = Context::new(base.clone());
        assert!(ctx.aisle().is_unset(), "new must not discover local config");
        assert!(
            ctx.pantry().is_unset(),
            "new must not discover local config"
        );
        assert_eq!(ctx.base_path(), base);
    }

    #[test]
    fn with_aisle_overrides() {
        let ctx = Context::new(Utf8PathBuf::from("/tmp"))
            .with_aisle(ConfigSource::Inline("[produce]\nleek".to_string()));
        assert_eq!(
            ctx.aisle().read().unwrap().as_deref(),
            Some("[produce]\nleek")
        );
        assert!(
            ctx.pantry().is_unset(),
            "with_aisle must not set the pantry"
        );
    }

    #[test]
    fn with_pantry_overrides() {
        let ctx = Context::new(Utf8PathBuf::from("/tmp")).with_pantry(ConfigSource::Inline(
            "[freezer]\npeas = \"1kg\"".to_string(),
        ));
        assert_eq!(
            ctx.pantry().read().unwrap().as_deref(),
            Some("[freezer]\npeas = \"1kg\"")
        );
        assert!(ctx.aisle().is_unset(), "with_pantry must not set the aisle");
    }

    #[test]
    fn discover_finds_local_config() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        write(&base.join("config").join("aisle.conf"), "[produce]\nleek");
        write(
            &base.join("config").join("pantry.conf"),
            "[freezer]\npeas = \"1kg\"",
        );

        let ctx = Context::discover(base.clone());

        assert_eq!(
            ctx.aisle().path(),
            Some(base.join("config").join("aisle.conf").as_path())
        );
        assert_eq!(
            ctx.pantry().path(),
            Some(base.join("config").join("pantry.conf").as_path())
        );
    }

    #[test]
    fn global_config_path_joins_the_app_name() {
        // Asserted as properties rather than a fixed suffix, because the shape
        // of the prefix is the platform's: `~/.config/cook/aisle.conf` on
        // Linux and `…/Application Support/cook/aisle.conf` on macOS put the
        // app name immediately before the file, but on Windows `directories`
        // yields `…\Roaming\cook\config`, so the last component before the
        // file is `config`. What holds everywhere is that the file is named
        // last, somewhere under a directory belonging to `cook`.
        //
        // Resolved with the override explicitly absent, so the assertion still
        // describes the platform directory on a machine that happens to export
        // `COOK_CONFIG_DIR`.
        let path = global_config_path_in(None, "aisle.conf").expect("a home directory");
        assert_eq!(
            path.file_name(),
            Some("aisle.conf"),
            "the name asked for must be the last component: {path}"
        );
        assert!(
            path.components().any(|c| c.as_str() == APP_NAME),
            "expected a `{APP_NAME}` component in {path}"
        );
        assert!(
            path.is_absolute(),
            "the platform config directory is absolute: {path}"
        );
    }

    // The override is exercised through `global_config_path_in`, which takes
    // the environment value as a parameter. `std::env::set_var` would reach
    // every other thread in the test binary, and these run in parallel with
    // `global_config_path_joins_the_app_name` above, which asserts the
    // *un*-overridden result.

    #[test]
    fn config_dir_env_replaces_the_platform_directory() {
        let dir = Utf8PathBuf::from("/somewhere/else");
        let path =
            global_config_path_in(Some(OsStr::new(dir.as_str())), "session.json").expect("a path");
        assert_eq!(path, dir.join("session.json"));
    }

    /// The point of the override: no component of the platform directory —
    /// `~/.config`, `Application Support`, `%APPDATA%` — survives it. Without
    /// this, a test setting `COOK_CONFIG_DIR` could still be reading the
    /// developer's real `session.json`.
    #[test]
    fn config_dir_env_leaves_nothing_of_the_platform_directory() {
        let dir = Utf8PathBuf::from("/somewhere/isolated");
        let overridden =
            global_config_path_in(Some(OsStr::new(dir.as_str())), "sync.db").expect("a path");
        let platform = global_config_path_in(None, "sync.db").expect("a home directory");
        assert_eq!(overridden, dir.join("sync.db"));
        assert_ne!(overridden, platform);
    }

    /// `COOK_CONFIG_DIR=` means "unset", not "the working directory".
    #[test]
    fn an_empty_config_dir_env_falls_back_to_the_platform_directory() {
        let empty = global_config_path_in(Some(OsStr::new("")), "aisle.conf").expect("a path");
        let unset = global_config_path_in(None, "aisle.conf").expect("a home directory");
        assert_eq!(empty, unset);
    }

    /// Discovery honours the override through the same call the CLI makes, so
    /// a global `aisle.conf` placed there is found when there is no local one.
    #[test]
    fn a_config_dir_env_aisle_is_discoverable() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        let config = base.join("isolated");
        write(&config.join("aisle.conf"), "[produce]\nleek");

        let global =
            global_config_path_in(Some(OsStr::new(config.as_str())), "aisle.conf").expect("a path");
        let found = Context::search(&base, "aisle.conf", Some(&global));

        assert_eq!(found, ConfigSource::Path(config.join("aisle.conf")));
    }

    #[cfg(unix)]
    #[test]
    fn a_non_utf8_config_dir_env_is_an_error() {
        use std::os::unix::ffi::OsStrExt;

        let err = global_config_path_in(Some(OsStr::from_bytes(b"/tmp/\xff")), "session.json")
            .expect_err("non-utf-8 override");
        assert!(
            err.to_string().contains(CONFIG_DIR_ENV),
            "the message should name the variable at fault: {err}"
        );
    }

    fn write(path: &Utf8Path, text: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, text).unwrap();
    }

    fn utf8(dir: &tempfile::TempDir) -> Utf8PathBuf {
        Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).unwrap()
    }

    // The search order is exercised through `Context::search`, which takes the
    // global candidate as a parameter. Going through `discover` instead would
    // make these depend on whether the machine running them happens to have a
    // `~/.config/cook/aisle.conf`.
    #[test]
    fn local_config_wins_over_global() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        let local = base.join("config").join("aisle.conf");
        let global = base.join("global").join("aisle.conf");
        write(&local, "[produce]\nleek");
        write(&global, "[dairy]\nmilk");

        let found = Context::search(&base, "aisle.conf", Some(&global));
        assert_eq!(found, ConfigSource::Path(local));
    }

    #[test]
    fn global_config_is_used_when_there_is_no_local_one() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        let global = base.join("global").join("pantry.conf");
        write(&global, "[freezer]\npeas = \"1kg\"");

        let found = Context::search(&base, "pantry.conf", Some(&global));
        assert_eq!(found, ConfigSource::Path(global));
    }

    #[test]
    fn absent_everywhere_is_unset() {
        let dir = tempfile::TempDir::new().unwrap();
        let base = utf8(&dir);
        let global = base.join("global").join("pantry.conf");

        assert!(Context::search(&base, "pantry.conf", Some(&global)).is_unset());
        assert!(Context::search(&base, "pantry.conf", None).is_unset());
    }
}