aoc-runtime 0.6.0

a runtime automation tool for Advent of Code: scaffold, run and submit puzzle solutions
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
//! Loading and validating `config.yaml`.
//!
//! ```yaml
//! template_path: "~/projects/aoc/{{year}}/day{{pad day}}/{{language}}"
//! cookie: "<advent of code session cookie>"
//! editor: "code"
//! ```
//!
//! Only `template_path` is required. The template is parsed - and therefore
//! validated - at load time rather than on first use.
//!
//! The cookie may instead live in a [`COOKIE_FILE_NAME`] file beside
//! `config.yaml`, holding nothing but the cookie, so the configuration itself
//! carries no secret and can be committed alongside other dotfiles.

use crate::{env::Env, template::Template};
use serde::Deserialize;
use std::{
    collections::BTreeMap,
    fs, io,
    path::{Path, PathBuf},
};

/// The default editor launched by `aoc code`.
pub const DEFAULT_EDITOR: &str = "code";

/// The file beside `config.yaml` read as a raw session cookie when the
/// configuration itself does not carry one.
pub const COOKIE_FILE_NAME: &str = "COOKIE";

/// Validated configuration.
#[derive(Debug, Clone)]
pub struct Config {
    /// The parsed project path template.
    pub template: Template,
    /// The Advent of Code session cookie, if one is available.
    pub cookie: Option<String>,
    /// The command launched by `aoc code`.
    pub editor: String,
    /// The directory the configuration was loaded from.
    pub config_dir: PathBuf,
}

/// A non-fatal problem noticed while loading configuration.
pub type Warning = String;

#[derive(Debug, Deserialize)]
struct RawConfig {
    template_path: String,
    #[serde(default)]
    cookie: Option<String>,
    #[serde(default)]
    editor: Option<String>,
    #[serde(flatten)]
    unknown: BTreeMap<String, serde_yaml_ng::Value>,
}

impl Config {
    /// Loads and validates the configuration described by `env`.
    ///
    /// Returns the configuration together with any non-fatal warnings, such as
    /// unrecognised keys - a misspelled `cookies:` would otherwise silently
    /// disable submission.
    ///
    /// With no cookie in the environment or the file itself, the
    /// [`COOKIE_FILE_NAME`] file beside `config.yaml` is read as one.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the file is missing, unreadable, not valid
    /// YAML, contains an invalid `template_path`, or if a cookie file exists
    /// but cannot be read.
    pub fn load(env: &Env) -> Result<(Self, Vec<Warning>), ConfigError> {
        let contents = read_config(&env.config_file)?;
        let (mut config, warnings) = Self::from_yaml(&contents, env)?;

        if config.cookie.is_none() {
            config.cookie = read_cookie(&env.config_dir.join(COOKIE_FILE_NAME))?;
        }

        Ok((config, warnings))
    }

    /// Parses configuration from a YAML document, resolving paths and the
    /// session cookie against `env`. Unlike [`Config::load`], this does not
    /// fall back to the cookie file.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError`] if the document is not valid YAML or the
    /// `template_path` is not a valid template.
    pub fn from_yaml(contents: &str, env: &Env) -> Result<(Self, Vec<Warning>), ConfigError> {
        let raw: RawConfig =
            serde_yaml_ng::from_str(contents).map_err(|source| ConfigError::Parse {
                path: env.config_file.clone(),
                source,
            })?;

        let mut warnings = Vec::new();
        for key in raw.unknown.keys() {
            warnings.push(format!(
                "ignoring unknown key `{key}` in {}",
                env.config_file.display()
            ));
        }

        let template_path = expand_home(&raw.template_path, &env.home);
        let template = Template::parse(&template_path).map_err(|source| ConfigError::Template {
            path: env.config_file.clone(),
            source,
        })?;

        let cookie = env
            .session_cookie
            .clone()
            .or(raw.cookie)
            .map(|cookie| cookie.trim().to_owned())
            .filter(|cookie| !cookie.is_empty());

        Ok((
            Self {
                template,
                cookie,
                editor: raw
                    .editor
                    .map(|editor| editor.trim().to_owned())
                    .filter(|editor| !editor.is_empty())
                    .unwrap_or_else(|| DEFAULT_EDITOR.to_owned()),
                config_dir: env.config_dir.clone(),
            },
            warnings,
        ))
    }
}

fn read_config(path: &Path) -> Result<String, ConfigError> {
    match fs::read_to_string(path) {
        Ok(contents) => Ok(contents),
        Err(source) if source.kind() == io::ErrorKind::NotFound => Err(ConfigError::NotFound {
            path: path.to_path_buf(),
        }),
        Err(source) => Err(ConfigError::Read {
            path: path.to_path_buf(),
            source,
        }),
    }
}

fn read_cookie(path: &Path) -> Result<Option<String>, ConfigError> {
    match fs::read_to_string(path) {
        Ok(contents) => Ok(Some(contents.trim().to_owned()).filter(|cookie| !cookie.is_empty())),
        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
        Err(source) => Err(ConfigError::Cookie {
            path: path.to_path_buf(),
            source,
        }),
    }
}

fn expand_home(path: &str, home: &Path) -> String {
    let expanded = match path {
        "~" => home.to_path_buf(),
        _ => match path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) {
            Some(rest) => home.join(rest),
            None => return path.to_owned(),
        },
    };

    expanded.to_string_lossy().into_owned()
}

/// Errors produced while loading configuration.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// No configuration file exists.
    #[error(
        "no config file at {path}\n\n\
         create it with at least a project path template, for example:\n  \
         template_path: \"~/projects/aoc/{{{{year}}}}/day{{{{pad day}}}}/{{{{language}}}}\""
    )]
    NotFound {
        /// Where the file was expected.
        path: PathBuf,
    },
    /// The configuration file could not be read.
    #[error("failed to read config file {path}")]
    Read {
        /// The file that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: io::Error,
    },
    /// The configuration file is not valid YAML, or is missing a required key.
    #[error("failed to parse config file {path}")]
    Parse {
        /// The offending file.
        path: PathBuf,
        /// The underlying deserialisation error.
        #[source]
        source: serde_yaml_ng::Error,
    },
    /// The cookie file exists but could not be read.
    #[error("failed to read cookie file {path}")]
    Cookie {
        /// The file that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: io::Error,
    },
    /// The `template_path` is not a valid template.
    #[error("invalid `template_path` in {path}")]
    Template {
        /// The offending file.
        path: PathBuf,
        /// The underlying template error.
        #[source]
        source: crate::template::TemplateError,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        env::CONFIG_FILE_NAME, language::Language, puzzle::Day, puzzle::Year, template::Params,
    };

    fn env() -> Env {
        Env {
            home: PathBuf::from("/home/tester"),
            config_dir: PathBuf::from("/home/tester/.config/aoc"),
            config_file: PathBuf::from("/home/tester/.config/aoc/config.yaml"),
            state_dir: PathBuf::from("/home/tester/.local/state/aoc"),
            cwd: PathBuf::from("/home/tester"),
            session_cookie: None,
        }
    }

    fn load(yaml: &str) -> Result<(Config, Vec<Warning>), ConfigError> {
        Config::from_yaml(yaml, &env())
    }

    /// Writes `config.yaml`, and a cookie file when one is given, into a
    /// throwaway configuration directory, then loads it from disk.
    fn load_from_disk(
        yaml: &str,
        cookie_file: Option<&str>,
    ) -> Result<(Config, Vec<Warning>), ConfigError> {
        let dir = tempfile::tempdir().expect("temp dir");
        fs::write(dir.path().join(CONFIG_FILE_NAME), yaml).expect("write config");
        if let Some(cookie) = cookie_file {
            fs::write(dir.path().join(COOKIE_FILE_NAME), cookie).expect("write cookie file");
        }

        let mut env = env();
        env.config_dir = dir.path().to_path_buf();
        env.config_file = dir.path().join(CONFIG_FILE_NAME);

        Config::load(&env)
    }

    fn project_path(config: &Config) -> PathBuf {
        config.template.render(Params {
            year: Year::new(2024).expect("valid year"),
            day: Day::new(7).expect("valid day"),
            language: Language::Rust,
        })
    }

    #[test]
    fn loads_a_minimal_config() {
        let (config, warnings) =
            load("template_path: \"/aoc/{{year}}/day{{pad day}}/{{language}}\"")
                .expect("config should load");

        assert!(warnings.is_empty());
        assert_eq!(config.cookie, None);
        assert_eq!(config.editor, DEFAULT_EDITOR);
        assert_eq!(project_path(&config), Path::new("/aoc/2024/day07/rust"));
    }

    #[test]
    fn expands_a_leading_tilde() {
        let (config, _) = load("template_path: \"~/aoc/{{year}}/day{{pad day}}/{{language}}\"")
            .expect("config should load");

        assert_eq!(
            project_path(&config),
            Path::new("/home/tester/aoc/2024/day07/rust")
        );
    }

    #[test]
    fn leaves_a_tilde_elsewhere_alone() {
        let (config, _) = load("template_path: \"/aoc/~backup/{{year}}/day{{day}}\"")
            .expect("config should load");

        assert_eq!(project_path(&config), Path::new("/aoc/~backup/2024/day7"));
    }

    #[test]
    fn reads_the_cookie_and_editor() {
        let (config, _) = load(
            "template_path: \"/aoc/{{year}}/day{{day}}\"\ncookie: \"  abc123  \"\neditor: nvim\n",
        )
        .expect("config should load");

        assert_eq!(config.cookie.as_deref(), Some("abc123"));
        assert_eq!(config.editor, "nvim");
    }

    #[test]
    fn an_empty_cookie_is_no_cookie() {
        let (config, _) = load("template_path: \"/aoc/{{year}}/day{{day}}\"\ncookie: \"\"\n")
            .expect("config should load");

        assert_eq!(config.cookie, None);
    }

    #[test]
    fn the_environment_cookie_wins() {
        let mut env = env();
        env.session_cookie = Some("from-env".to_owned());

        let (config, _) = Config::from_yaml(
            "template_path: \"/aoc/{{year}}/day{{day}}\"\ncookie: from-file\n",
            &env,
        )
        .expect("config should load");

        assert_eq!(config.cookie.as_deref(), Some("from-env"));
    }

    #[test]
    fn the_cookie_file_stands_in_for_a_missing_cookie_key() {
        let (config, _) = load_from_disk(
            "template_path: \"/aoc/{{year}}/day{{day}}\"\n",
            Some("from-file\n"),
        )
        .expect("config should load");

        assert_eq!(config.cookie.as_deref(), Some("from-file"));
    }

    #[test]
    fn the_configured_cookie_wins_over_the_cookie_file() {
        let (config, _) = load_from_disk(
            "template_path: \"/aoc/{{year}}/day{{day}}\"\ncookie: from-config\n",
            Some("from-file"),
        )
        .expect("config should load");

        assert_eq!(config.cookie.as_deref(), Some("from-config"));
    }

    #[test]
    fn a_blank_cookie_file_is_no_cookie() {
        let (config, _) = load_from_disk(
            "template_path: \"/aoc/{{year}}/day{{day}}\"\n",
            Some("  \n"),
        )
        .expect("config should load");

        assert_eq!(config.cookie, None);
    }

    #[test]
    fn no_cookie_file_is_no_cookie() {
        let (config, _) = load_from_disk("template_path: \"/aoc/{{year}}/day{{day}}\"\n", None)
            .expect("config should load");

        assert_eq!(config.cookie, None);
    }

    #[test]
    fn unknown_keys_produce_a_warning_instead_of_silence() {
        let (config, warnings) =
            load("template_path: \"/aoc/{{year}}/day{{day}}\"\ncookies: oops\n")
                .expect("config should load");

        assert_eq!(config.cookie, None);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("cookies"), "{warnings:?}");
    }

    #[test]
    fn a_missing_template_path_is_an_error() {
        let error = load("cookie: abc123").expect_err("template_path is required");

        assert!(matches!(error, ConfigError::Parse { .. }), "got {error:?}");
    }

    #[test]
    fn an_invalid_template_names_the_config_file() {
        let error = load("template_path: \"/aoc/{{year}}\"").expect_err("day is missing");

        assert!(
            matches!(error, ConfigError::Template { .. }),
            "got {error:?}"
        );
        assert!(error.to_string().contains("config.yaml"), "{error}");
    }

    #[test]
    fn malformed_yaml_is_an_error() {
        let error = load("template_path: [unclosed").expect_err("yaml is malformed");

        assert!(matches!(error, ConfigError::Parse { .. }), "got {error:?}");
    }

    #[test]
    fn a_missing_file_explains_how_to_create_one() {
        let error = read_config(Path::new("/nonexistent/aoc/config.yaml"))
            .expect_err("file should not exist");

        assert!(
            matches!(error, ConfigError::NotFound { .. }),
            "got {error:?}"
        );
        assert!(error.to_string().contains("template_path"), "{error}");
    }
}