Skip to main content

agentmux_common/
settings_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Writing `settings.json` without losing what the person put in it
5//! (docs/specs/SPEC_SETTINGS_JSON_EVERY_KEY_ONE_TO_ONE_2026_11_01.md §3, §5.4).
6//!
7//! The launcher's startup seed, srv's setting changes and the migrations all rewrite the file
8//! from the template plus the person's values. They used to read the file leniently (a file that
9//! did not parse read as "no settings") and write the result, so a half-pasted file, a missing
10//! comma or a byte-order mark replaced everything the person had set with the bare template. Here
11//! a file that cannot be read is never written, a write is atomic, and writers do not interleave.
12
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15
16use serde_json::{Map, Value};
17
18use crate::settings_jsonc::strip_trailing_commas;
19
20/// The 1-based line each top-level key of a settings file's text is written on, to say where a
21/// problem is. `None` when the text is not one object.
22pub fn key_lines(text: &str) -> Option<std::collections::HashMap<String, u32>> {
23    crate::settings_patch::key_lines(text)
24}
25
26/// Settings files are a few KiB. Anything past this is not one, and is left alone.
27pub const MAX_SETTINGS_BYTES: u64 = 1024 * 1024;
28
29/// How many times a write is redone because the file changed between its read and its rename.
30const MAX_REBASES: usize = 3;
31
32static WRITE_LOCK: Mutex<()> = Mutex::new(());
33
34/// Why a settings file could not be read. The file is left exactly as it is.
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum ReadError {
37    #[error("settings.json can't be read: {0}")]
38    Io(String),
39    #[error("settings.json is larger than 1 MiB, so it is not a settings file")]
40    TooLarge,
41    #[error("settings.json is not a text file (it has binary content or is not valid UTF-8)")]
42    NotText,
43    #[error("settings.json has an error at line {line}, column {column}: {message}")]
44    Syntax { line: usize, column: usize, message: String },
45    #[error("settings.json must hold one JSON object")]
46    NotObject,
47}
48
49/// Why a write did not happen. The file is left as it was.
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
51pub enum UpdateError {
52    #[error("{0}")]
53    Read(#[from] ReadError),
54    #[error("settings.json is saved as UTF-16; save it as UTF-8 and try again")]
55    Utf16,
56    #[error("settings.json could not be written: {0}")]
57    Write(String),
58    #[error("settings.json kept changing while it was being saved; try again")]
59    Conflict,
60}
61
62/// A settings file as read: its values, and the byte-level habits to write back.
63#[derive(Debug, Clone, PartialEq)]
64pub struct Loaded {
65    pub values: Map<String, Value>,
66    /// The file starts with a UTF-8 byte-order mark.
67    pub bom: bool,
68    /// Most of its line ends are CRLF.
69    pub crlf: bool,
70    /// It is UTF-16 (read, never written).
71    pub utf16: bool,
72}
73
74fn decode(bytes: &[u8]) -> Result<(String, bool, bool), ReadError> {
75    if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
76        return String::from_utf8(rest.to_vec()).map(|s| (s, true, false)).map_err(|_| ReadError::NotText);
77    }
78    let utf16 = |rest: &[u8], le: bool| -> Result<String, ReadError> {
79        if rest.len() % 2 != 0 {
80            return Err(ReadError::NotText);
81        }
82        let units: Vec<u16> = rest
83            .chunks_exact(2)
84            .map(|p| if le { u16::from_le_bytes([p[0], p[1]]) } else { u16::from_be_bytes([p[0], p[1]]) })
85            .collect();
86        String::from_utf16(&units).map_err(|_| ReadError::NotText)
87    };
88    if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
89        return utf16(rest, true).map(|s| (s, false, true));
90    }
91    if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
92        return utf16(rest, false).map(|s| (s, false, true));
93    }
94    if bytes.contains(&0) {
95        return Err(ReadError::NotText);
96    }
97    String::from_utf8(bytes.to_vec()).map(|s| (s, false, false)).map_err(|_| ReadError::NotText)
98}
99
100/// `bytes` as a settings file: JSONC (comments and trailing commas allowed), one object. An empty
101/// or blank file holds no settings.
102pub fn parse(bytes: &[u8]) -> Result<Loaded, ReadError> {
103    if bytes.len() as u64 > MAX_SETTINGS_BYTES {
104        return Err(ReadError::TooLarge);
105    }
106    let (text, bom, utf16) = decode(bytes)?;
107    let crlf = {
108        let crlf = text.matches("\r\n").count();
109        crlf > 0 && crlf * 2 >= text.matches('\n').count()
110    };
111    if text.trim().is_empty() {
112        return Ok(Loaded { values: Map::new(), bom, crlf, utf16 });
113    }
114    // `StripComments` blanks comments and `strip_trailing_commas` blanks commas, neither moves a
115    // line break, so a position in the cleaned text is the position in the file.
116    let mut stripped = Vec::new();
117    std::io::Read::read_to_end(&mut json_comments::StripComments::new(text.as_bytes()), &mut stripped)
118        .map_err(|e| ReadError::Io(e.to_string()))?;
119    let cleaned = strip_trailing_commas(&String::from_utf8_lossy(&stripped));
120    match serde_json::from_str::<Value>(&cleaned) {
121        Ok(Value::Object(values)) => Ok(Loaded { values, bom, crlf, utf16 }),
122        Ok(_) => Err(ReadError::NotObject),
123        Err(e) => Err(ReadError::Syntax { line: e.line(), column: e.column(), message: e.to_string() }),
124    }
125}
126
127/// The settings file at `path`: `Ok(None)` when there is none.
128pub fn read(path: &Path) -> Result<Option<Loaded>, ReadError> {
129    read_bytes(path)?.map(|bytes| parse(&bytes)).transpose()
130}
131
132fn read_bytes(path: &Path) -> Result<Option<Vec<u8>>, ReadError> {
133    match std::fs::metadata(path) {
134        Ok(meta) if meta.len() > MAX_SETTINGS_BYTES => return Err(ReadError::TooLarge),
135        Ok(_) => {}
136        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
137        Err(e) => return Err(ReadError::Io(e.to_string())),
138    }
139    match std::fs::read(path) {
140        Ok(bytes) => Ok(Some(bytes)),
141        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
142        Err(e) => Err(ReadError::Io(e.to_string())),
143    }
144}
145
146/// Merge user settings into a JSONC template string.
147///
148/// For each user key:
149/// - If the key exists as a commented-out line in the template (`// "key": ...`), that line is
150///   replaced with the uncommented user value.
151/// - If the key is NOT in the template, it is appended before the closing `}`.
152///
153/// The result is always a valid JSONC file with the full template structure intact.
154pub fn merge_into_template(template: &str, user_settings: &Map<String, Value>) -> String {
155    if user_settings.is_empty() {
156        return template.to_string();
157    }
158
159    let mut remaining: std::collections::HashMap<&str, &Value> =
160        user_settings.iter().map(|(k, v)| (k.as_str(), v)).collect();
161    let mut lines: Vec<String> = Vec::new();
162
163    for line in template.lines() {
164        if let Some(key) = extract_commented_setting_key(line) {
165            if let Some(value) = remaining.remove(key) {
166                let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
167                let val_str = serde_json::to_string(value).unwrap_or_default();
168                lines.push(format!("{}\"{}\": {},", indent, key, val_str));
169                continue;
170            }
171        }
172        lines.push(line.to_string());
173    }
174
175    if !remaining.is_empty() {
176        if let Some(brace_pos) = lines.iter().rposition(|l| l.trim() == "}") {
177            let mut extra: Vec<String> = vec![String::new(), "    // -- User Overrides --".to_string()];
178            let mut sorted_keys: Vec<&&str> = remaining.keys().collect();
179            sorted_keys.sort();
180            for key in sorted_keys {
181                let val_str = serde_json::to_string(remaining[*key]).unwrap_or_default();
182                extra.push(format!("    \"{}\": {},", key, val_str));
183            }
184            for (i, line) in extra.into_iter().enumerate() {
185                lines.insert(brace_pos + i, line);
186            }
187        }
188    }
189
190    let mut result = lines.join("\n");
191    if !result.ends_with('\n') {
192        result.push('\n');
193    }
194    result
195}
196
197/// The settings key of a commented-out template line, e.g. `    // "some:key": value,`.
198fn extract_commented_setting_key(line: &str) -> Option<&str> {
199    let rest = line.trim_start().strip_prefix("//")?.trim_start().strip_prefix('"')?;
200    let end = rest.find('"')?;
201    Some(&rest[..end])
202}
203
204/// Write `contents` to `path` so a reader sees the old file or the new one, never a short one: a
205/// temporary file in the same folder, flushed, then renamed over it.
206///
207/// A settings file that is a symlink (a dotfile manager's) is written through: the file it points
208/// to is replaced and the link stays.
209pub fn write_atomic(path: &Path, contents: &[u8]) -> std::io::Result<()> {
210    use std::io::Write;
211    let resolved;
212    let path = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
213        resolved = match std::fs::canonicalize(path) {
214            Ok(target) => target,
215            // A link to a file that is not there yet: the link's own target path.
216            Err(_) => {
217                let target = std::fs::read_link(path)?;
218                if target.is_absolute() {
219                    target
220                } else {
221                    path.parent().unwrap_or_else(|| Path::new(".")).join(target)
222                }
223            }
224        };
225        resolved.as_path()
226    } else {
227        path
228    };
229    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
230    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "settings".into());
231    let tmp: PathBuf = dir.join(format!(".{name}.{}.tmp", std::process::id()));
232    let result = (|| {
233        let mut file = std::fs::File::create(&tmp)?;
234        // The file can hold tokens: the new file keeps the old one's permissions (set before any
235        // content is written), and a file that did not exist is private to its owner.
236        match std::fs::metadata(path) {
237            Ok(existing) => file.set_permissions(existing.permissions())?,
238            #[cfg(unix)]
239            Err(_) => {
240                use std::os::unix::fs::PermissionsExt;
241                file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
242            }
243            #[cfg(not(unix))]
244            Err(_) => {}
245        }
246        file.write_all(contents)?;
247        file.sync_all()?;
248        drop(file);
249        rename_over(&tmp, path)
250    })();
251    if result.is_err() {
252        let _ = std::fs::remove_file(&tmp);
253    }
254    result
255}
256
257/// Rename, retrying briefly: on Windows an editor or a scanner holding the target fails it.
258fn rename_over(from: &Path, to: &Path) -> std::io::Result<()> {
259    let mut last = None;
260    for attempt in 0..5u64 {
261        match std::fs::rename(from, to) {
262            Ok(()) => return Ok(()),
263            Err(e) => {
264                last = Some(e);
265                std::thread::sleep(std::time::Duration::from_millis(20 * (attempt + 1)));
266            }
267        }
268    }
269    Err(last.expect("at least one attempt"))
270}
271
272/// The file's text with LF line ends, for editing in place; the template for a file that is not
273/// there or holds nothing.
274fn working_text(bytes: Option<&[u8]>, template: &str) -> String {
275    match bytes.and_then(|b| decode(b).ok()) {
276        Some((text, _, _)) if !text.trim().is_empty() => text.replace("\r\n", "\n"),
277        _ => template.to_string(),
278    }
279}
280
281/// `text` with `new` in place of `old`, edited where the changes are (`settings_patch`), then
282/// brought up to the template's commented defaults. Falls back to writing the template with the
283/// values in it, losing the person's comments, only for a layout the editor cannot place.
284fn patched(text: &str, old: &Map<String, Value>, new: &Map<String, Value>, template: &str) -> String {
285    let edit = || -> Option<String> {
286        let mut out = text.to_string();
287        for (key, value) in new {
288            if old.get(key) != Some(value) {
289                out = crate::settings_patch::set(&out, key, value)?;
290            }
291        }
292        for key in old.keys().filter(|k| !new.contains_key(*k)) {
293            out = crate::settings_patch::reset(&out, key, template)?;
294        }
295        // The refresh is a courtesy: it is used only when it settles (a second one changes nothing),
296        // so a layout it cannot place never makes the file grow at every start.
297        let settled = crate::settings_patch::refresh(&out, template)
298            .filter(|r| crate::settings_patch::refresh(r, template).as_deref() == Some(r.as_str()))
299            .filter(|r| parse(r.as_bytes()).is_ok_and(|read| read.values == *new));
300        Some(settled.unwrap_or(out))
301    };
302    // What is written must read back as the values asked for: an edit that does not is not used.
303    edit().filter(|out| parse(out.as_bytes()).is_ok_and(|read| read.values == *new)).unwrap_or_else(|| {
304        tracing::warn!("settings.json has a layout that cannot be edited in place; rewriting it from the template");
305        merge_into_template(template, new)
306    })
307}
308
309/// `text` as file bytes, in the byte-order mark and line ends of the file it replaces.
310fn encode(mut text: String, habits: Option<&Loaded>) -> Vec<u8> {
311    if habits.is_some_and(|h| h.crlf) {
312        text = text.replace("\r\n", "\n").replace('\n', "\r\n");
313    }
314    let mut out = Vec::new();
315    if habits.is_some_and(|h| h.bom) {
316        out.extend_from_slice(&[0xEF, 0xBB, 0xBF]);
317    }
318    out.extend_from_slice(text.as_bytes());
319    out
320}
321
322/// Read the settings at `path`, let `change` edit the values, and write the file with the changes
323/// made where they belong in its own text, and its commented defaults brought up to `template`.
324///
325/// Nothing is written when the file cannot be read: a file with a mistake in it is the person's
326/// to fix, not ours to replace (`UpdateError::Read` says where the mistake is). Writers in this
327/// process take turns. When the file changes between the read and the rename (a hand edit, the
328/// launcher), the read is taken again and `change` is applied to the new values, so both edits
329/// land. A missing file is created. Nothing is written when the result is the file's own bytes.
330pub fn update(
331    path: &Path,
332    template: &str,
333    mut change: impl FnMut(&mut Map<String, Value>),
334) -> Result<(), UpdateError> {
335    let _turn = WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
336    if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
337        std::fs::create_dir_all(dir).map_err(|e| UpdateError::Write(e.to_string()))?;
338    }
339    for _ in 0..MAX_REBASES {
340        let before = read_bytes(path)?;
341        let loaded = before.as_deref().map(parse).transpose()?;
342        if loaded.as_ref().is_some_and(|l| l.utf16) {
343            return Err(UpdateError::Utf16);
344        }
345        let old = loaded.as_ref().map(|l| l.values.clone()).unwrap_or_default();
346        let mut values = old.clone();
347        change(&mut values);
348        let text = working_text(before.as_deref(), template);
349        let out = encode(patched(&text, &old, &values, template), loaded.as_ref());
350        if before.as_deref() == Some(out.as_slice()) {
351            return Ok(());
352        }
353        if read_bytes(path)? != before {
354            continue;
355        }
356        return write_atomic(path, &out).map_err(|e| UpdateError::Write(e.to_string()));
357    }
358    Err(UpdateError::Conflict)
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364    use serde_json::json;
365
366    const TEMPLATE: &str = "// AgentMux settings\n{\n    // -- Terminal --\n    // \"term:fontsize\": 15,\n    // \"term:scrollback\": 2000,\n}\n";
367
368    fn set(key: &'static str, value: Value) -> impl FnMut(&mut Map<String, Value>) {
369        move |m| {
370            m.insert(key.to_string(), value.clone());
371        }
372    }
373
374    fn file(contents: &[u8]) -> (tempfile::TempDir, PathBuf) {
375        let dir = tempfile::tempdir().unwrap();
376        let path = dir.path().join("settings.json");
377        std::fs::write(&path, contents).unwrap();
378        (dir, path)
379    }
380
381    #[test]
382    fn a_file_with_a_mistake_in_it_is_never_replaced() {
383        for broken in [
384            "{\n  \"term:fontsize\": 20\n  \"term:scrollback\": 500\n}\n", // a missing comma
385            "{\n  \"term:fontsize\": 20,\n",                               // cut off in the middle of a paste
386            "{ {\n  \"term:fontsize\": 20 } }\n",                          // a file pasted into a file
387        ] {
388            let (_dir, path) = file(broken.as_bytes());
389            let err = update(&path, TEMPLATE, set("term:scrollback", json!(1))).unwrap_err();
390            assert!(matches!(err, UpdateError::Read(ReadError::Syntax { .. })), "{broken:?}: {err:?}");
391            assert_eq!(std::fs::read(&path).unwrap(), broken.as_bytes(), "{broken:?} must be left as it is");
392        }
393    }
394
395    #[test]
396    fn a_mistake_is_reported_with_its_line_and_column() {
397        let (_dir, path) = file(b"{\n  // note\n  \"a\": 1\n  \"b\": 2\n}\n");
398        let Err(ReadError::Syntax { line, .. }) = read(&path) else { panic!("expected a syntax error") };
399        assert_eq!(line, 4, "the missing comma is found at the next member, on the file's own line");
400    }
401
402    #[test]
403    fn a_file_that_is_not_one_object_is_left_alone() {
404        for (text, want) in [("[1, 2]\n", ReadError::NotObject), ("\"hello\"", ReadError::NotObject)] {
405            let (_dir, path) = file(text.as_bytes());
406            assert_eq!(read(&path).unwrap_err(), want);
407            assert!(update(&path, TEMPLATE, set("term:fontsize", json!(18))).is_err());
408            assert_eq!(std::fs::read(&path).unwrap(), text.as_bytes());
409        }
410    }
411
412    #[test]
413    fn a_byte_order_mark_reads_and_is_kept() {
414        let mut bytes = vec![0xEF, 0xBB, 0xBF];
415        bytes.extend_from_slice(b"{\n  \"term:fontsize\": 20,\n}\n");
416        let (_dir, path) = file(&bytes);
417        assert_eq!(read(&path).unwrap().unwrap().values["term:fontsize"], json!(20));
418        update(&path, TEMPLATE, set("term:scrollback", json!(500))).unwrap();
419        let after = std::fs::read(&path).unwrap();
420        assert!(after.starts_with(&[0xEF, 0xBB, 0xBF]), "the mark stays");
421        let loaded = parse(&after).unwrap();
422        assert_eq!((loaded.values["term:fontsize"].clone(), loaded.values["term:scrollback"].clone()), (json!(20), json!(500)));
423    }
424
425    #[test]
426    fn crlf_line_ends_stay_crlf() {
427        let (_dir, path) = file(b"{\r\n  \"term:fontsize\": 20,\r\n}\r\n");
428        update(&path, TEMPLATE, set("term:scrollback", json!(500))).unwrap();
429        let after = String::from_utf8(std::fs::read(&path).unwrap()).unwrap();
430        assert!(after.contains("\r\n"));
431        assert!(!after.replace("\r\n", "").contains('\n'), "no bare LF in a CRLF file");
432    }
433
434    #[test]
435    fn a_missing_file_is_created_from_the_template() {
436        let dir = tempfile::tempdir().unwrap();
437        let path = dir.path().join("nested").join("settings.json");
438        update(&path, TEMPLATE, set("term:fontsize", json!(18))).unwrap();
439        let text = std::fs::read_to_string(&path).unwrap();
440        assert!(text.contains("\"term:fontsize\": 18,") && text.contains("// \"term:scrollback\""));
441    }
442
443    #[test]
444    fn an_empty_file_holds_no_settings() {
445        let (_dir, path) = file(b"  \n");
446        update(&path, TEMPLATE, set("term:fontsize", json!(18))).unwrap();
447        assert!(std::fs::read_to_string(&path).unwrap().contains("\"term:fontsize\": 18,"));
448    }
449
450    #[test]
451    fn a_file_that_is_not_text_or_is_too_big_is_left_alone() {
452        let mut huge = b"{\n".to_vec();
453        huge.extend(std::iter::repeat(b' ').take(MAX_SETTINGS_BYTES as usize));
454        huge.extend_from_slice(b"}\n");
455        for (bytes, want) in [
456            (vec![0u8, 1, 2, 0, 255], ReadError::NotText),
457            (vec![b'{', 0xC3, 0x28, b'}'], ReadError::NotText),
458            (huge, ReadError::TooLarge),
459        ] {
460            let (_dir, path) = file(&bytes);
461            assert_eq!(read(&path).unwrap_err(), want);
462            assert!(update(&path, TEMPLATE, set("term:fontsize", json!(18))).is_err());
463            assert_eq!(std::fs::read(&path).unwrap(), bytes);
464        }
465    }
466
467    #[test]
468    fn a_utf16_file_reads_but_is_not_written() {
469        let mut bytes = vec![0xFF, 0xFE];
470        for unit in "{\"term:fontsize\": 20}".encode_utf16() {
471            bytes.extend_from_slice(&unit.to_le_bytes());
472        }
473        let (_dir, path) = file(&bytes);
474        assert_eq!(read(&path).unwrap().unwrap().values["term:fontsize"], json!(20));
475        assert_eq!(update(&path, TEMPLATE, set("term:scrollback", json!(1))).unwrap_err(), UpdateError::Utf16);
476        assert_eq!(std::fs::read(&path).unwrap(), bytes);
477    }
478
479    #[test]
480    fn a_hand_edit_made_while_saving_is_not_lost() {
481        let (_dir, path) = file(b"{\n  \"term:fontsize\": 20,\n}\n");
482        let mut hand_edit = Some(path.clone());
483        update(&path, TEMPLATE, |values| {
484            values.insert("term:scrollback".into(), json!(500));
485            // The person saves their editor between our read and our rename.
486            if let Some(p) = hand_edit.take() {
487                std::fs::write(p, "{\n  \"term:fontsize\": 20,\n  \"window:zoom\": 1.5,\n}\n").unwrap();
488            }
489        })
490        .unwrap();
491        let values = read(&path).unwrap().unwrap().values;
492        assert_eq!(values["window:zoom"], json!(1.5), "their edit");
493        assert_eq!(values["term:scrollback"], json!(500), "ours");
494    }
495
496    #[test]
497    fn writers_in_a_process_take_turns() {
498        let (_dir, path) = file(b"{\n}\n");
499        let path = std::sync::Arc::new(path);
500        let threads: Vec<_> = (0..8)
501            .map(|i| {
502                let path = path.clone();
503                std::thread::spawn(move || {
504                    update(&path, TEMPLATE, |m| {
505                        m.insert(format!("custom:k{i}"), json!(i));
506                    })
507                    .unwrap()
508                })
509            })
510            .collect();
511        threads.into_iter().for_each(|t| t.join().unwrap());
512        let values = read(&path).unwrap().unwrap().values;
513        assert_eq!((0..8).filter(|i| values.get(&format!("custom:k{i}")) == Some(&json!(i))).count(), 8);
514    }
515
516    #[test]
517    fn a_write_that_fails_leaves_the_file_whole_and_no_temporary_file() {
518        let (dir, path) = file(b"{\n  \"term:fontsize\": 20,\n}\n");
519        let before = std::fs::read(&path).unwrap();
520        // The target is a folder now: the rename cannot replace it.
521        std::fs::remove_file(&path).unwrap();
522        std::fs::create_dir(&path).unwrap();
523        assert!(write_atomic(&path, b"new").is_err());
524        let leftovers: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(|e| e.ok()).collect();
525        assert_eq!(leftovers.len(), 1, "only the folder: {leftovers:?}");
526        assert!(before.starts_with(b"{"));
527    }
528
529    #[cfg(unix)]
530    #[test]
531    fn a_symlinked_settings_file_is_written_through() {
532        let dir = tempfile::tempdir().unwrap();
533        let target = dir.path().join("dotfiles-settings.json");
534        std::fs::write(&target, "{
535  \"term:fontsize\": 20,
536}
537").unwrap();
538        let link = dir.path().join("settings.json");
539        std::os::unix::fs::symlink(&target, &link).unwrap();
540        update(&link, TEMPLATE, set("term:scrollback", json!(500))).unwrap();
541        assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays");
542        let values = parse(&std::fs::read(&target).unwrap()).unwrap().values;
543        assert_eq!((values["term:fontsize"].clone(), values["term:scrollback"].clone()), (json!(20), json!(500)));
544    }
545
546    #[cfg(unix)]
547    #[test]
548    fn a_private_settings_file_stays_private() {
549        use std::os::unix::fs::PermissionsExt;
550        let (_dir, path) = file(b"{
551  \"messaging:discord:token\": \"t\",
552}
553");
554        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
555        update(&path, TEMPLATE, set("term:scrollback", json!(500))).unwrap();
556        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
557        // A file made from nothing is private too.
558        let fresh = path.with_file_name("fresh.json");
559        update(&fresh, TEMPLATE, set("term:fontsize", json!(18))).unwrap();
560        assert_eq!(std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777, 0o600);
561    }
562
563    #[test]
564    fn a_write_keeps_the_persons_comments_order_and_layout() {
565        let mine = "// my settings, tuned over a year\n{\n    // -- Terminal --\n    // bigger on the laptop\n    \"term:fontsize\": 20,   // was 15\n    // \"term:scrollback\": 2000,\n\n    \"connections\": {\n        \"alpha\": {\"ssh:hostname\": \"a\"}\n    },\n    // -- Window --\n    // \"window:zoom\": 1.0,\n}\n";
566        let (_dir, path) = file(mine.as_bytes());
567        update(&path, TEMPLATE, set("term:scrollback", json!(500))).unwrap();
568        let after = std::fs::read_to_string(&path).unwrap();
569        assert_eq!(after, mine.replace("// \"term:scrollback\": 2000,", "\"term:scrollback\": 500,"));
570        update(&path, TEMPLATE, |m| {
571            m.remove("term:scrollback");
572        })
573        .unwrap();
574        let reset = std::fs::read_to_string(&path).unwrap();
575        assert!(!reset.contains("\"term:scrollback\": 500"));
576        assert!(reset.contains("// \"term:scrollback\": 2000,"), "a reset key shows its default again: {reset}");
577        assert!(reset.contains("// bigger on the laptop\n    \"term:fontsize\": 20,   // was 15\n"));
578        assert!(reset.contains("\"connections\": {\n        \"alpha\": {\"ssh:hostname\": \"a\"}\n    },\n"));
579    }
580
581    #[test]
582    fn a_key_new_in_the_template_reaches_an_old_file_and_set_lines_stay() {
583        let template = "{\n    // -- Terminal --\n    // \"term:fontsize\": 15,\n    // Lines kept after they scroll off.\n    // \"term:scrollback\": 2000,\n\n    // -- Window --\n    // \"window:zoom\": 1.0,\n}\n";
584        let old = "{\n    // -- Terminal --\n    \"term:fontsize\": 20,\n}\n";
585        let (_dir, path) = file(old.as_bytes());
586        update(&path, template, |_| {}).unwrap();
587        let after = std::fs::read_to_string(&path).unwrap();
588        assert!(after.contains("    \"term:fontsize\": 20,\n    // Lines kept after they scroll off.\n"));
589        assert!(after.contains("// -- Window --") && after.contains("// \"window:zoom\": 1.0,"));
590        let again = std::fs::metadata(&path).unwrap().modified().unwrap();
591        std::thread::sleep(std::time::Duration::from_millis(30));
592        update(&path, template, |_| {}).unwrap();
593        assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), again, "a second refresh changes nothing");
594    }
595
596    #[test]
597    fn a_value_equal_to_its_default_stays_set_until_it_is_reset() {
598        let (_dir, path) = file(TEMPLATE.as_bytes());
599        update(&path, TEMPLATE, set("term:fontsize", json!(15))).unwrap();
600        assert!(std::fs::read_to_string(&path).unwrap().contains("    \"term:fontsize\": 15,"));
601        update(&path, TEMPLATE, set("term:fontsize", json!(15))).unwrap();
602        assert!(std::fs::read_to_string(&path).unwrap().contains("    \"term:fontsize\": 15,"));
603    }
604
605    #[test]
606    fn writing_the_same_bytes_again_changes_nothing() {
607        let (_dir, path) = file(TEMPLATE.as_bytes());
608        update(&path, TEMPLATE, set("term:fontsize", json!(18))).unwrap();
609        let first = std::fs::metadata(&path).unwrap().modified().unwrap();
610        std::thread::sleep(std::time::Duration::from_millis(30));
611        update(&path, TEMPLATE, set("term:fontsize", json!(18))).unwrap();
612        assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), first, "no rewrite");
613    }
614
615    #[test]
616    fn merge_puts_a_value_where_its_commented_default_was() {
617        let mut values = Map::new();
618        values.insert("term:fontsize".into(), json!(18));
619        values.insert("custom:key".into(), json!("x"));
620        let out = merge_into_template(TEMPLATE, &values);
621        assert!(out.contains("    \"term:fontsize\": 18,"));
622        assert!(out.contains("// \"term:scrollback\""));
623        assert!(out.contains("// -- User Overrides --") && out.contains("\"custom:key\": \"x\""));
624        assert_eq!(merge_into_template(TEMPLATE, &Map::new()), TEMPLATE);
625    }
626}