shine-cli 2.0.1

Give personal automation a reviewable lifecycle
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
//! Config persistence: atomic writes, comment preservation, and sparse
//! project-layer diffing so inherited global values never materialize in
//! project config files.

use anyhow::{Context, Result, bail};
use std::path::PathBuf;
use tokio::fs;

use super::Config;

impl Config {
    pub async fn save(&self) -> Result<()> {
        let config_path = self.resolve_config_path_for_save().await?;

        let new_table = self.serialize_table_for_save()?;
        let new_toml = toml::to_string_pretty(&new_table).context("Failed to serialize config")?;

        let toml_str = if config_path.exists() {
            let existing = fs::read_to_string(&config_path).await.unwrap_or_default();
            if existing.is_empty() {
                new_toml
            } else {
                let mut doc: toml_edit::DocumentMut = existing
                    .parse()
                    .context("Fail to parse existing config for comment preservation")?;

                shine_core::migration::sync_table(doc.as_table_mut(), &new_table);
                doc.to_string()
            }
        } else {
            new_toml
        };

        crate::persist::atomic_write(&config_path, toml_str.as_bytes())
            .await
            .with_context(|| format!("Failed to write config to {config_path:?}"))?;

        Ok(())
    }

    fn serialize_table_for_save(&self) -> Result<toml::Table> {
        let table = self.serialize_effective_table()?;

        if self.is_project_config {
            let mut sparse = if let Some(state) = &self.project_save_state {
                let mut sparse = state.original.clone();
                apply_table_changes(&mut sparse, &state.loaded, &table);
                sparse
            } else {
                table
            };
            sparse.remove("schema_version");
            sparse.remove("last_cleared_schema_version");
            // Executable sys-code permission is intentionally global-only. Never preserve or
            // materialize it in a project configuration that could authorize its own presets.
            sparse.remove("allow_app_hooks");
            sparse.remove("allow_sys_code");
            return Ok(sparse);
        }

        Ok(table)
    }

    pub(super) fn serialize_effective_table(&self) -> Result<toml::Table> {
        let serialized = toml::to_string_pretty(self).context("Failed to serialize config")?;
        toml::from_str(&serialized).context("Failed to round-trip serialize config")
    }

    async fn resolve_config_path_for_save(&self) -> Result<PathBuf> {
        if self
            .config_path
            .parent()
            .is_some_and(|parent| !parent.as_os_str().is_empty())
        {
            return Ok(self.config_path.clone());
        }
        bail!("config path must not be empty");
    }
}

fn apply_table_changes(target: &mut toml::Table, loaded: &toml::Table, current: &toml::Table) {
    let keys: std::collections::BTreeSet<_> = loaded.keys().chain(current.keys()).collect();
    for key in keys {
        match (loaded.get(key), current.get(key)) {
            (Some(toml::Value::Table(before)), Some(toml::Value::Table(after))) => {
                let entry = target
                    .entry(key.clone())
                    .or_insert_with(|| toml::Value::Table(toml::Table::new()));
                if !entry.is_table() {
                    *entry = toml::Value::Table(toml::Table::new());
                }
                apply_table_changes(entry.as_table_mut().unwrap(), before, after);
                if entry.as_table().is_some_and(toml::Table::is_empty) {
                    target.remove(key);
                }
            }
            (before, after) if before == after => {}
            (_, Some(value)) => {
                target.insert(key.clone(), value.clone());
            }
            (_, None) => {
                target.remove(key);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_util::{config_in, make_temp_dir};
    use super::*;
    use crate::config::CURRENT_RUNTIME_SCHEMA_VERSION;
    use std::path::Path;

    #[tokio::test]
    async fn save_writes_config_file_for_new_config() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir);

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert_eq!(
            parsed["schema_version"].as_integer(),
            Some(CURRENT_RUNTIME_SCHEMA_VERSION.into())
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_writes_new_toml_when_existing_file_is_empty() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir);
        fs::write(&config.config_path, b"").await.unwrap();

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(!content.is_empty());
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert!(parsed.contains_key("schema_version"));

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_merges_updates_changed_value() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir);
        fs::write(&config.config_path, "schema_version = 0\n")
            .await
            .unwrap();

        let updated = Config {
            schema_version: 2,
            ..config
        };
        updated.save().await.unwrap();

        let content = fs::read_to_string(&updated.config_path).await.unwrap();
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert_eq!(parsed["schema_version"].as_integer(), Some(2));

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_writes_last_cleared_schema_version_when_set() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.last_cleared_schema_version = Some(1);

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert_eq!(parsed["last_cleared_schema_version"].as_integer(), Some(1));

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_merges_preserves_comments() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.schema_version = 0;
        fs::write(&config.config_path, "# keep this\nschema_version = 0\n")
            .await
            .unwrap();

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(
            content.contains("# keep this"),
            "comment should be preserved"
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_updates_detailed_env_value_without_losing_description() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        fs::write(
            &config.config_path,
            "[env]\nMY_TOKEN = { value = \"old\", description = \"Internal token\" }\n",
        )
        .await
        .unwrap();
        config.env.insert("MY_TOKEN".into(), "new".into());

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(
            content.contains("MY_TOKEN = { value = \"new\", description = \"Internal token\" }")
        );
        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_merges_removes_stale_keys() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir);
        fs::write(
            &config.config_path,
            "schema_version = 0\nstale_key = \"old\"\n",
        )
        .await
        .unwrap();

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(
            !content.contains("stale_key"),
            "stale key should be removed"
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn save_returns_error_for_path_without_parent() {
        let config = Config {
            config_path: PathBuf::from("config.toml"),
            ..Config::new_for_test(Path::new("shine"))
        };
        assert!(config.save().await.is_err());
    }

    #[tokio::test]
    async fn presets_dir_override_round_trips_through_save() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.presets_dir_override = Some(PathBuf::from("/external/presets"));

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(
            content.contains("/external/presets"),
            "presets_dir should be written to config.toml"
        );

        let loaded: Config = toml::from_str(&content).unwrap();
        assert_eq!(
            loaded.presets_dir_override,
            Some(PathBuf::from("/external/presets"))
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn presets_overlay_dir_override_round_trips_through_save() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.presets_overlay_dir_override = Some(PathBuf::from("/external/overlay"));

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(content.contains("presets_overlay_dir"));

        let loaded: Config = toml::from_str(&content).unwrap();
        assert_eq!(
            loaded.presets_overlay_dir_override,
            Some(PathBuf::from("/external/overlay"))
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn presets_overlay_git_round_trips_through_save() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.presets_overlay_git = Some("https://example.com/overlay.git".to_string());
        config.presets_overlay_git_branch = Some("main".to_string());

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(content.contains("presets_overlay_git"));

        let loaded: Config = toml::from_str(&content).unwrap();
        assert_eq!(
            loaded.presets_overlay_git.as_deref(),
            Some("https://example.com/overlay.git")
        );
        assert_eq!(loaded.presets_overlay_git_branch.as_deref(), Some("main"));

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn gpg_recipients_round_trip_through_save() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.gpg_recipients = vec![
            "alice@example.com".to_string(),
            "bob@example.com".to_string(),
        ];

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        let loaded: Config = toml::from_str(&content).unwrap();
        assert_eq!(
            loaded.gpg_recipients,
            ["alice@example.com", "bob@example.com"]
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn retired_coarse_trust_flags_are_not_saved() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.legacy_allow_app_hooks = true;
        config.legacy_allow_sys_code = true;

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(!content.contains("allow_app_hooks"));
        assert!(!content.contains("allow_sys_code"));

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn sync_terminal_theme_false_round_trips_through_save() {
        let dir = make_temp_dir().await;
        let mut config = config_in(&dir);
        config.sync_terminal_theme = false;

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        assert!(content.contains("sync_terminal_theme"));
        let loaded: Config = toml::from_str(&content).unwrap();
        assert!(!loaded.sync_terminal_theme);

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn sync_terminal_theme_true_default_is_absent_from_toml() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir); // sync_terminal_theme defaults to true

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert!(
            !parsed.contains_key("sync_terminal_theme"),
            "default true value must not clutter a fresh config.toml"
        );
        // An old config.toml with no such key at all must still default true.
        let loaded: Config = toml::from_str(&content).unwrap();
        assert!(loaded.sync_terminal_theme);

        fs::remove_dir_all(&dir).await.unwrap();
    }

    #[tokio::test]
    async fn presets_dir_absent_from_toml_when_override_is_none() {
        let dir = make_temp_dir().await;
        let config = config_in(&dir); // presets_dir_override: None

        config.save().await.unwrap();

        let content = fs::read_to_string(&config.config_path).await.unwrap();
        let parsed: toml::Table = toml::from_str(&content).unwrap();
        assert!(
            !parsed.contains_key("presets_dir"),
            "presets_dir key must be absent when override is None"
        );

        fs::remove_dir_all(&dir).await.unwrap();
    }
}