chromasync-core 0.5.3

Core generation pipeline and configuration loading for Chromasync
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use std::{
    fs,
    path::{Path, PathBuf},
};

use chromasync_types::{ChromaStrategy, ContrastStrategy};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};

use crate::CoreError;

/// Defines sync profiles and records where each configured target writes its
/// generated artifacts.
///
/// Stored at `~/.config/chromasync/config.toml` (see [`config_file_path`]).
/// Consumed by the CLI `generate`, `wallpaper`, `batch`, and `sync` commands so
/// that a configured target writes to its recorded directory instead of the
/// generic `--output` fallback.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChromasyncConfig {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub configs: Vec<SyncProfile>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub targets: Vec<ConfigTarget>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hooks: Vec<ConfigHook>,
}

/// One runnable generation profile under `[[configs]]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SyncProfile {
    /// Profile name selected by `chromasync sync [name]`.
    pub name: String,
    /// Seed color in #RRGGBB format. Mutually exclusive with `image`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<String>,
    /// Wallpaper image path. Mutually exclusive with `seed` and
    /// `image_fetch_command`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<PathBuf>,
    /// Shell command whose stdout returns a wallpaper image path. Mutually
    /// exclusive with `seed` and `image`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_fetch_command: Option<String>,
    /// Template name or path to a template TOML file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,
    /// Theme mode, with `auto` resolved by the CLI at runtime.
    #[serde(default)]
    pub mode: SyncMode,
    /// Contrast selection heuristic used when resolving readable foregrounds.
    #[serde(default)]
    pub contrast: ContrastStrategy,
    /// Chroma strategy used when generating palette families.
    #[serde(default)]
    pub chroma: ChromaStrategy,
    /// Target names or target TOML paths to generate.
    #[serde(default)]
    pub targets: Vec<String>,
    /// Fallback output directory for targets without a recorded `[[targets]]` entry.
    #[serde(default = "default_output_dir")]
    pub output_dir: PathBuf,
    /// Overwrite existing artifacts for targets without per-target overwrite.
    #[serde(default)]
    pub force: bool,
}

/// Sync profile mode. `Auto` is deliberately separate from `ThemeMode` because
/// resolving the user's current desktop preference belongs at the CLI boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum SyncMode {
    Light,
    #[default]
    Dark,
    Auto,
}

/// One row of the chromasync config under `[[targets]]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigTarget {
    /// Target name (matches the `name` field of the installed target TOML).
    pub name: String,
    /// Directory where this target's generated artifacts are written.
    ///
    /// Stored verbatim; a leading `~` is expanded to the user's home directory
    /// at resolve time (see [`expand_tilde`]).
    pub output_dir: PathBuf,
    /// Location of the installed target file relative to the config root
    /// (e.g. `targets/gtk.toml`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// When true, generation overwrites existing artifacts for this target
    /// (acts like a per-target `--force`).
    #[serde(default)]
    pub overwrite: bool,
}

/// One command hook under `[[hooks]]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigHook {
    /// Human-readable hook name used in error messages.
    pub name: String,
    /// Event or events that trigger this hook.
    pub on: HookEvents,
    /// Shell command to execute when this hook matches.
    pub command: String,
    /// Optional filters, such as `config:default`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub filters: Vec<String>,
}

/// Hook event list that accepts either `on = "event"` or `on = ["event"]`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HookEvents {
    One(String),
    Many(Vec<String>),
}

impl HookEvents {
    pub fn iter(&self) -> impl Iterator<Item = &str> + '_ {
        match self {
            Self::One(event) => std::slice::from_ref(event),
            Self::Many(events) => events.as_slice(),
        }
        .iter()
        .map(String::as_str)
    }
}

/// Summary of a successful [`install_target`] call, for echoing back to the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallSummary {
    pub target_name: String,
    pub target_file: PathBuf,
    pub config_file: PathBuf,
}

const CONFIG_HEADER: &str = "# Managed by `chromasync target install`. Records where each installed target writes its generated artifacts.\n";

/// Resolve the user config directory (`~/.config/chromasync` on Linux).
fn project_dirs() -> Option<ProjectDirs> {
    ProjectDirs::from("io", "chromasync", "chromasync")
}

/// Path to the managed chromasync config file, if a user config directory can be located.
pub fn config_file_path() -> Option<PathBuf> {
    project_dirs().map(|dirs| dirs.config_dir().join("config.toml"))
}

impl ChromasyncConfig {
    /// Load the config from disk, returning an empty config when the file does
    /// not exist yet (the common case before any target has been installed).
    pub fn load() -> Result<Self, CoreError> {
        let Some(path) = config_file_path() else {
            return Ok(Self::default());
        };

        if !path.exists() {
            return Ok(Self::default());
        }

        let content = fs::read_to_string(&path).map_err(|source| CoreError::ConfigRead {
            path: path.clone(),
            source,
        })?;
        let config: Self =
            toml::from_str(&content).map_err(|error| CoreError::ConfigParse { path, error })?;
        Ok(config)
    }

    /// Write the config back to disk, creating the config directory if needed.
    pub fn save(&self) -> Result<(), CoreError> {
        let path = config_file_path().ok_or(CoreError::UserConfigDirUnavailable)?;
        let body = toml::to_string(self).map_err(|error| CoreError::ConfigSerialize {
            error: error.to_string(),
        })?;

        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|source| CoreError::ConfigWrite {
                path: parent.to_path_buf(),
                source,
            })?;
        }

        let serialized = format!("{CONFIG_HEADER}\n{body}");
        fs::write(&path, &serialized).map_err(|source| CoreError::ConfigWrite { path, source })?;
        Ok(())
    }

    /// Resolve the effective output directory and force flag for a target name.
    ///
    /// Installed targets (present in the config) drive their own `output_dir`
    /// and `overwrite`. Targets without an entry fall back to the caller-provided
    /// defaults. A global `--force` (`fallback_force = true`) forces every target.
    pub fn resolve(
        &self,
        target_name: &str,
        fallback_dir: &Path,
        fallback_force: bool,
    ) -> (PathBuf, bool) {
        match self.targets.iter().find(|entry| entry.name == target_name) {
            Some(entry) => (
                expand_tilde(&entry.output_dir),
                entry.overwrite || fallback_force,
            ),
            None => (fallback_dir.to_path_buf(), fallback_force),
        }
    }

    /// Return the sync profile with `name`, if present.
    pub fn sync_profile(&self, name: &str) -> Option<&SyncProfile> {
        self.configs.iter().find(|entry| entry.name == name)
    }

    /// Insert or replace the config entry for `name`.
    fn upsert(&mut self, entry: ConfigTarget) {
        if let Some(existing) = self.targets.iter_mut().find(|t| t.name == entry.name) {
            *existing = entry;
        } else {
            self.targets.push(entry);
        }
    }
}

/// Install a target TOML into the user config and record its output directory.
///
/// The target file is validated (same rules as discovery), copied to
/// `~/.config/chromasync/targets/<name>.toml`, and a `[[targets]]` entry is
/// upserted into the config. Refuses to replace an already-installed target
/// file unless `overwrite` is set; the same flag is recorded in the config so
/// subsequent generation force-overwrites that target's artifacts.
pub fn install_target(
    target_path: &Path,
    output_dir: PathBuf,
    overwrite: bool,
) -> Result<InstallSummary, CoreError> {
    let spec = chromasync_renderers::parse_target_file(target_path)?;
    let name = spec.name.clone();

    let registry = chromasync_renderers::RendererRegistry::new();
    if registry.contains(&name) {
        return Err(CoreError::Renderer(
            chromasync_renderers::RendererError::TargetNameCollidesWithBuiltIn { name },
        ));
    }

    crate::load_output_registry()?.validate_path_target(target_path)?;

    let targets_dir =
        chromasync_renderers::user_targets_dir().ok_or(CoreError::UserConfigDirUnavailable)?;
    fs::create_dir_all(&targets_dir).map_err(|source| CoreError::CreateTargetsDir {
        path: targets_dir.clone(),
        source,
    })?;

    let dest = targets_dir.join(format!("{name}.toml"));
    if dest.exists() && !overwrite {
        return Err(CoreError::TargetAlreadyInstalled {
            name,
            path: dest.clone(),
        });
    }

    fs::copy(target_path, &dest).map_err(|source| CoreError::CopyTargetFile {
        from: target_path.to_path_buf(),
        to: dest.clone(),
        source,
    })?;

    let mut config = ChromasyncConfig::load()?;
    config.upsert(ConfigTarget {
        name: name.clone(),
        output_dir,
        source: Some(format!("targets/{name}.toml")),
        overwrite,
    });
    config.save()?;

    Ok(InstallSummary {
        target_name: name,
        target_file: dest,
        config_file: config_file_path().ok_or(CoreError::UserConfigDirUnavailable)?,
    })
}

/// Expand a leading `~` or `~/` to the user's home directory.
///
/// Paths without a leading tilde are returned unchanged. When the home
/// directory cannot be determined, the original path is returned as a fallback.
pub fn expand_tilde(path: &Path) -> PathBuf {
    let lossy = path.to_string_lossy();

    if lossy == "~" {
        return home_dir().unwrap_or_else(|| path.to_path_buf());
    }

    if let Some(rest) = lossy.strip_prefix("~/")
        && let Some(home) = home_dir()
    {
        return home.join(rest);
    }

    path.to_path_buf()
}

fn home_dir() -> Option<PathBuf> {
    directories::BaseDirs::new().map(|base| base.home_dir().to_path_buf())
}

fn default_output_dir() -> PathBuf {
    PathBuf::from("chromasync")
}

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

    #[test]
    fn resolve_falls_back_when_target_not_installed() {
        let config = ChromasyncConfig::default();
        let (dir, force) = config.resolve("missing", Path::new("fallback"), false);

        assert_eq!(dir, PathBuf::from("fallback"));
        assert!(!force);
    }

    #[test]
    fn resolve_uses_installed_output_dir_and_overwrite() {
        let config = ChromasyncConfig {
            configs: Vec::new(),
            targets: vec![ConfigTarget {
                name: "gtk".to_owned(),
                output_dir: PathBuf::from("~/.config/gtk-4.0"),
                source: Some("targets/gtk.toml".to_owned()),
                overwrite: true,
            }],
            hooks: Vec::new(),
        };
        let (dir, force) = config.resolve("gtk", Path::new("fallback"), false);

        assert_eq!(dir, expand_tilde(&PathBuf::from("~/.config/gtk-4.0")));
        assert!(force);
    }

    #[test]
    fn resolve_global_force_overrides_installed_overwrite_false() {
        let config = ChromasyncConfig {
            configs: Vec::new(),
            targets: vec![ConfigTarget {
                name: "gtk".to_owned(),
                output_dir: PathBuf::from("/tmp/gtk"),
                source: Some("targets/gtk.toml".to_owned()),
                overwrite: false,
            }],
            hooks: Vec::new(),
        };
        let (_, force) = config.resolve("gtk", Path::new("fallback"), true);

        assert!(force);
    }

    #[test]
    fn upsert_replaces_existing_entry() {
        let mut config = ChromasyncConfig {
            configs: Vec::new(),
            targets: vec![ConfigTarget {
                name: "gtk".to_owned(),
                output_dir: PathBuf::from("/old"),
                source: Some("targets/gtk.toml".to_owned()),
                overwrite: false,
            }],
            hooks: Vec::new(),
        };
        config.upsert(ConfigTarget {
            name: "gtk".to_owned(),
            output_dir: PathBuf::from("/new"),
            source: Some("targets/gtk.toml".to_owned()),
            overwrite: true,
        });

        assert_eq!(config.targets.len(), 1);
        assert_eq!(config.targets[0].output_dir, PathBuf::from("/new"));
        assert!(config.targets[0].overwrite);
    }

    #[test]
    fn config_toml_accepts_sync_profiles() {
        let config = toml::from_str::<ChromasyncConfig>(
            r##"
[[configs]]
name = "default"
seed = "#4ecdc4"
template = "materialish"
mode = "auto"
contrast = "apca-experimental"
chroma = "industrial"
targets = ["ghostty", "kitty"]
output_dir = "fallback-output"
force = true

[[targets]]
name = "kitty"
output_dir = "~/.config/kitty"
overwrite = true
"##,
        )
        .expect("sync profile config should parse");

        let profile = config
            .sync_profile("default")
            .expect("default profile should be present");
        assert_eq!(profile.seed.as_deref(), Some("#4ecdc4"));
        assert_eq!(profile.image_fetch_command, None);
        assert_eq!(profile.template.as_deref(), Some("materialish"));
        assert_eq!(profile.mode, SyncMode::Auto);
        assert_eq!(profile.contrast, ContrastStrategy::ApcaExperimental);
        assert_eq!(profile.chroma, ChromaStrategy::Industrial);
        assert_eq!(profile.targets, ["ghostty", "kitty"]);
        assert_eq!(profile.output_dir, PathBuf::from("fallback-output"));
        assert!(profile.force);
        assert_eq!(config.targets[0].source, None);
    }

    #[test]
    fn sync_profile_defaults_match_generate_defaults() {
        let config = toml::from_str::<ChromasyncConfig>(
            r##"
[[configs]]
name = "default"
seed = "#4ecdc4"
"##,
        )
        .expect("minimal sync profile should parse");

        let profile = config
            .sync_profile("default")
            .expect("default profile should be present");
        assert_eq!(profile.mode, SyncMode::Dark);
        assert_eq!(profile.contrast, ContrastStrategy::RelativeLuminance);
        assert_eq!(profile.chroma, ChromaStrategy::Normal);
        assert_eq!(profile.targets, Vec::<String>::new());
        assert_eq!(profile.output_dir, PathBuf::from("chromasync"));
        assert!(!profile.force);
    }

    #[test]
    fn config_toml_accepts_image_fetch_command_source() {
        let config = toml::from_str::<ChromasyncConfig>(
            r#"
[[configs]]
name = "default"
image_fetch_command = "qs -c noctalia-shell ipc call wallpaper get"
targets = ["kitty"]
"#,
        )
        .expect("image fetch command profile should parse");

        let profile = config
            .sync_profile("default")
            .expect("default profile should be present");
        assert_eq!(
            profile.image_fetch_command.as_deref(),
            Some("qs -c noctalia-shell ipc call wallpaper get")
        );
        assert_eq!(profile.seed, None);
        assert_eq!(profile.image, None);
    }

    #[test]
    fn config_toml_accepts_hooks_with_single_or_multiple_events() {
        let config = toml::from_str::<ChromasyncConfig>(
            r##"
[[hooks]]
name = "all-targets"
on = "targets:done"
command = "printf all"

[[hooks]]
name = "hyprland-lua"
filters = ["config:default"]
on = ["target:hyprland-lua:done"]
command = "hyprctl reload"
"##,
        )
        .expect("hooks should deserialize");

        assert_eq!(config.hooks.len(), 2);
        assert_eq!(
            config.hooks[0].on.iter().collect::<Vec<_>>(),
            vec!["targets:done"]
        );
        assert_eq!(
            config.hooks[1].on.iter().collect::<Vec<_>>(),
            vec!["target:hyprland-lua:done"]
        );
        assert_eq!(config.hooks[1].filters, vec!["config:default"]);
    }

    #[test]
    fn config_toml_rejects_unknown_root_fields() {
        let error = toml::from_str::<ChromasyncConfig>(
            r#"
unknown = true
"#,
        )
        .expect_err("unknown root config fields should be rejected");

        assert!(
            error.to_string().contains("unknown field"),
            "expected unknown-field parse error, got: {error}"
        );
    }

    #[test]
    fn config_toml_rejects_unknown_target_fields() {
        let error = toml::from_str::<ChromasyncConfig>(
            r#"
[[targets]]
name = "gtk"
output_dir = "/tmp/gtk"
source = "targets/gtk.toml"
extra = true
"#,
        )
        .expect_err("unknown target config fields should be rejected");

        assert!(
            error.to_string().contains("unknown field"),
            "expected unknown-field parse error, got: {error}"
        );
    }

    #[test]
    fn expand_tilde_leaves_absolute_paths_untouched() {
        assert_eq!(
            expand_tilde(&PathBuf::from("/etc/x")),
            PathBuf::from("/etc/x")
        );
        assert_eq!(
            expand_tilde(&PathBuf::from("relative")),
            PathBuf::from("relative")
        );
    }
}