Skip to main content

aft_base/
jsonc_edit.rs

1//! Comment-preserving edits to a JSONC document.
2//!
3//! `aft setup` and `aft fix-config` rewrite a handful of keys in files people
4//! edit by hand. Re-serializing the parsed value would drop every comment and
5//! reorder keys, so edits go through the concrete syntax tree of the
6//! `jsonc-parser` crate (dprint's parser): it keeps every comment, blank line,
7//! trailing comma and line-ending style that an edit does not touch, and fixes
8//! up commas and indentation around inserted and removed members.
9//!
10//! The accepted dialect is the one the config loader accepts: JSON plus `//`
11//! and `/* */` comments and trailing commas. The parser's other leniencies
12//! (unquoted keys, single quotes, hex numbers, missing commas) are switched
13//! off, because the loader would reject a file that used them.
14
15use std::io::Write;
16use std::path::Path;
17
18use jsonc_parser::cst::{CstInputValue, CstObject, CstObjectProp, CstRootNode};
19use jsonc_parser::ParseOptions;
20use serde_json::Value;
21
22fn loader_dialect() -> ParseOptions {
23    ParseOptions {
24        allow_comments: true,
25        allow_trailing_commas: true,
26        allow_loose_object_property_names: false,
27        allow_missing_commas: false,
28        allow_single_quoted_strings: false,
29        allow_hexadecimal_numbers: false,
30        allow_unary_plus_numbers: false,
31    }
32}
33
34fn to_input(value: &Value) -> CstInputValue {
35    match value {
36        Value::Null => CstInputValue::Null,
37        Value::Bool(value) => CstInputValue::Bool(*value),
38        Value::Number(number) => CstInputValue::Number(number.to_string()),
39        Value::String(text) => CstInputValue::String(text.clone()),
40        Value::Array(items) => CstInputValue::Array(items.iter().map(to_input).collect()),
41        Value::Object(map) => CstInputValue::Object(
42            map.iter()
43                .map(|(key, value)| (key.clone(), to_input(value)))
44                .collect(),
45        ),
46    }
47}
48
49/// The member named `key`. With duplicate keys the last one wins, as it does
50/// for the loader.
51fn last_prop(object: &CstObject, key: &str) -> Option<CstObjectProp> {
52    object
53        .properties()
54        .into_iter()
55        .rev()
56        .find(|prop| prop.decoded_name().as_deref() == Some(key))
57}
58
59fn child_object(object: &CstObject, key: &str) -> Option<CstObject> {
60    last_prop(object, key)?.object_value()
61}
62
63/// A JSONC document edited in place.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct JsoncDocument {
66    text: String,
67}
68
69impl JsoncDocument {
70    /// Parse `text`. The root must be an object; an empty (or
71    /// whitespace-only) document stands for an empty object.
72    pub fn parse(text: &str) -> Result<Self, String> {
73        let doc = Self {
74            text: text.to_string(),
75        };
76        let root = doc.root()?;
77        if root.value().is_some() && root.object_value().is_none() {
78            return Err("invalid JSONC: the root value must be an object".to_string());
79        }
80        Ok(doc)
81    }
82
83    fn root(&self) -> Result<CstRootNode, String> {
84        CstRootNode::parse(&self.text, &loader_dialect())
85            .map_err(|error| format!("invalid JSONC: {error}"))
86    }
87
88    /// The current document text.
89    pub fn text(&self) -> &str {
90        &self.text
91    }
92
93    /// The plain JSON value of the document (comments and trailing commas
94    /// removed). An empty document is `{}`.
95    pub fn value(&self) -> Result<Value, String> {
96        if self.text.trim().is_empty() {
97            return Ok(Value::Object(serde_json::Map::new()));
98        }
99        serde_json::from_str(&crate::jsonc::strip_jsonc(&self.text))
100            .map_err(|error| format!("invalid JSONC: {error}"))
101    }
102
103    /// Whether a member exists at `path`.
104    pub fn contains(&self, path: &[&str]) -> bool {
105        let Some((last, parents)) = path.split_last() else {
106            return true;
107        };
108        let Ok(root) = self.root() else {
109            return false;
110        };
111        let Some(mut object) = root.object_value() else {
112            return false;
113        };
114        for key in parents {
115            match child_object(&object, key) {
116                Some(child) => object = child,
117                None => return false,
118            }
119        }
120        last_prop(&object, last).is_some()
121    }
122
123    /// Set the member at `path` to `value`, creating missing parent objects.
124    /// An existing non-object parent is replaced by an object.
125    pub fn set(&mut self, path: &[&str], value: &Value) -> Result<(), String> {
126        let Some((last, parents)) = path.split_last() else {
127            return Err("cannot replace the document root".to_string());
128        };
129        let root = self.root()?;
130        let mut object = root.object_value_or_set();
131        for key in parents {
132            object = match last_prop(&object, key) {
133                Some(prop) => prop.object_value_or_set(),
134                None => object.object_value_or_set(key),
135            };
136        }
137        match last_prop(&object, last) {
138            Some(prop) => prop.set_value(to_input(value)),
139            None => {
140                object.append(last, to_input(value));
141            }
142        }
143        self.text = root.to_string();
144        Ok(())
145    }
146
147    /// Remove the member at `path`. Returns whether anything was removed.
148    pub fn remove(&mut self, path: &[&str]) -> Result<bool, String> {
149        let Some((last, parents)) = path.split_last() else {
150            return Err("cannot remove the document root".to_string());
151        };
152        let root = self.root()?;
153        let Some(mut object) = root.object_value() else {
154            return Ok(false);
155        };
156        for key in parents {
157            match child_object(&object, key) {
158                Some(child) => object = child,
159                None => return Ok(false),
160            }
161        }
162        let Some(prop) = last_prop(&object, last) else {
163            return Ok(false);
164        };
165        prop.remove();
166        self.text = root.to_string();
167        Ok(true)
168    }
169
170    /// Remove the object at `path` when it exists and has no members left.
171    pub fn remove_if_empty_object(&mut self, path: &[&str]) -> Result<bool, String> {
172        match self.value()?.pointer(&pointer(path)) {
173            Some(Value::Object(map)) if map.is_empty() => self.remove(path),
174            _ => Ok(false),
175        }
176    }
177}
178
179/// JSON pointer for a key path.
180pub fn pointer(path: &[&str]) -> String {
181    path.iter()
182        .map(|key| format!("/{}", key.replace('~', "~0").replace('/', "~1")))
183        .collect()
184}
185
186/// Replace `path` with `contents` atomically: write a sibling temporary file,
187/// flush it, then rename it over the target. A reader sees either the old or
188/// the new file, never a partial write. Existing permissions are kept.
189/// A directory-sync failure after replacement is logged, not returned as an
190/// uncommitted write. Callers needing that warning use the richer internal API.
191pub fn write_atomic(path: &Path, contents: &str) -> std::io::Result<()> {
192    if let Some(warning) = write_atomic_with_sync_warning(path, contents)? {
193        log::warn!(
194            "Config {} was updated, but syncing its directory failed: {warning}",
195            path.display()
196        );
197    }
198    Ok(())
199}
200
201/// Errors leave the target unchanged; success means the rename committed.
202/// A successful result may carry a warning that directory sync failed afterward.
203pub(crate) fn write_atomic_with_sync_warning(
204    path: &Path,
205    contents: &str,
206) -> std::io::Result<Option<std::io::Error>> {
207    write_atomic_with_sync_dir(path, contents, crate::durability::sync_dir)
208}
209
210pub(crate) fn write_atomic_with_sync_dir(
211    path: &Path,
212    contents: &str,
213    sync_dir: impl FnOnce(&Path) -> std::io::Result<()>,
214) -> std::io::Result<Option<std::io::Error>> {
215    // Dotfile managers often link configs into a separate repository. Replace
216    // the target file, not that link; a dangling link must fail without being lost.
217    let resolved;
218    let path = if std::fs::symlink_metadata(path)
219        .is_ok_and(|metadata| metadata.file_type().is_symlink())
220    {
221        resolved = std::fs::canonicalize(path)?;
222        resolved.as_path()
223    } else {
224        path
225    };
226    let parent = path
227        .parent()
228        .filter(|parent| !parent.as_os_str().is_empty())
229        .unwrap_or_else(|| Path::new("."));
230    std::fs::create_dir_all(parent)?;
231    let name = path
232        .file_name()
233        .map(|name| name.to_string_lossy().into_owned())
234        .unwrap_or_else(|| "config".to_string());
235    let mut nonce = [0_u8; 16];
236    getrandom::fill(&mut nonce).map_err(std::io::Error::other)?;
237    let temp = parent.join(format!(
238        ".{name}.tmp-{}-{:032x}",
239        std::process::id(),
240        u128::from_le_bytes(nonce)
241    ));
242    write_atomic_to_temp(path, contents, &temp, sync_dir)
243}
244
245fn write_atomic_to_temp(
246    path: &Path,
247    contents: &str,
248    temp: &Path,
249    sync_dir: impl FnOnce(&Path) -> std::io::Result<()>,
250) -> std::io::Result<Option<std::io::Error>> {
251    let parent = path
252        .parent()
253        .filter(|parent| !parent.as_os_str().is_empty())
254        .unwrap_or_else(|| Path::new("."));
255    // Acquire a private file before writing, and never clean up another writer's temp.
256    let mut file = crate::private_storage::options()
257        .write(true)
258        .create_new(true)
259        .open(temp)?;
260    let result = (|| {
261        file.write_all(contents.as_bytes())?;
262        aft_store::sync::sync_all(&file, temp)?;
263        drop(file);
264        if let Ok(metadata) = std::fs::metadata(path) {
265            std::fs::set_permissions(temp, metadata.permissions())?;
266        }
267        std::fs::rename(temp, path)?;
268        // The rename is the commit point. A later durability failure cannot
269        // undo it, so callers must not treat that failure as an unapplied write.
270        Ok(sync_dir(parent).err())
271    })();
272    if result.is_err() {
273        let _ = std::fs::remove_file(temp);
274    }
275    result
276}
277
278#[cfg(test)]
279mod tests {
280    #[test]
281    fn jsonc_collision_preserves_temporary_and_destination() {
282        let dir = tempfile::tempdir().unwrap();
283        let path = dir.path().join("aft.jsonc");
284        let temp = dir.path().join("occupied.tmp");
285        std::fs::write(&path, "old config").unwrap();
286        std::fs::write(&temp, "another writer").unwrap();
287        let error = write_atomic_to_temp(&path, "new config", &temp, |_| Ok(())).unwrap_err();
288        assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
289        assert_eq!(std::fs::read_to_string(&temp).unwrap(), "another writer");
290        assert_eq!(std::fs::read_to_string(&path).unwrap(), "old config");
291    }
292
293    #[test]
294    fn jsonc_failed_replace_cleans_owned_temporary() {
295        let dir = tempfile::tempdir().unwrap();
296        let path = dir.path().join("destination");
297        let temp = dir.path().join("owned.tmp");
298        std::fs::create_dir(&path).unwrap();
299        assert!(write_atomic_to_temp(&path, "config", &temp, |_| Ok(())).is_err());
300        assert!(!temp.exists());
301        assert!(path.is_dir());
302    }
303
304    #[cfg(unix)]
305    #[test]
306    fn jsonc_new_config_is_private_under_permissive_umask() {
307        use std::os::unix::fs::PermissionsExt;
308
309        const CHILD: &str = "AFT_TEST_JSONC_PRIVATE_CHILD";
310        if std::env::var_os(CHILD).is_some() {
311            // Only this isolated child changes umask; parallel tests keep theirs.
312            unsafe { libc::umask(0o022) };
313            let dir = tempfile::tempdir().unwrap();
314            let path = dir.path().join("aft.jsonc");
315            write_atomic(&path, "private config").unwrap();
316            assert_eq!(
317                std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
318                0o600
319            );
320            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
321            write_atomic(&path, "replacement config").unwrap();
322            assert_eq!(
323                std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
324                0o640
325            );
326            return;
327        }
328
329        let output = std::process::Command::new(std::env::current_exe().unwrap())
330            .args([
331                "--exact",
332                "jsonc_edit::tests::jsonc_new_config_is_private_under_permissive_umask",
333                "--nocapture",
334            ])
335            .env(CHILD, "1")
336            .output()
337            .unwrap();
338        assert!(
339            output.status.success(),
340            "private-config child failed: stdout={} stderr={}",
341            String::from_utf8_lossy(&output.stdout),
342            String::from_utf8_lossy(&output.stderr)
343        );
344    }
345
346    #[test]
347    fn atomic_write_reports_committed_sync_warning() {
348        let dir = tempfile::tempdir().unwrap();
349        let path = dir.path().join("aft.jsonc");
350        std::fs::write(&path, "old").unwrap();
351        let warning = super::write_atomic_with_sync_dir(&path, "new", |_| {
352            assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
353            Err(std::io::Error::new(
354                std::io::ErrorKind::PermissionDenied,
355                "directory sync denied",
356            ))
357        })
358        .expect("the rename has already committed");
359        assert_eq!(
360            warning.unwrap().kind(),
361            std::io::ErrorKind::PermissionDenied
362        );
363        assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
364        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
365    }
366
367    #[test]
368    fn atomic_write_pre_rename_failure_never_calls_directory_sync() {
369        let dir = tempfile::tempdir().unwrap();
370        let path = dir.path().join("aft.jsonc");
371        std::fs::create_dir(&path).unwrap();
372        let called = std::cell::Cell::new(false);
373        let result = super::write_atomic_with_sync_dir(&path, "new", |_| {
374            called.set(true);
375            Ok(())
376        });
377        assert!(result.is_err());
378        assert!(!called.get());
379        assert!(path.is_dir());
380        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
381    }
382
383    use super::*;
384    use serde_json::json;
385
386    const COMMENTED: &str = r#"{
387  // keep me
388  "$schema": "https://example/schema.json",
389  /* block */
390  "edit_mode": "hashline", // trailing
391  "indexes": {
392    "trigram": false,
393  },
394}
395"#;
396
397    #[test]
398    fn replacing_a_value_keeps_comments_and_other_keys() {
399        let mut doc = JsoncDocument::parse(COMMENTED).unwrap();
400        doc.set(&["indexes", "trigram"], &json!(true)).unwrap();
401        let text = doc.text();
402        assert!(text.contains("// keep me"));
403        assert!(text.contains("/* block */"));
404        assert!(text.contains("\"edit_mode\": \"hashline\", // trailing"));
405        assert!(text.contains("\"trigram\": true,"));
406        assert_eq!(doc.value().unwrap()["indexes"]["trigram"], json!(true));
407    }
408
409    #[test]
410    fn inserting_members_creates_parents_and_matches_indentation() {
411        let mut doc = JsoncDocument::parse(COMMENTED).unwrap();
412        doc.set(&["indexes", "semantic"], &json!(false)).unwrap();
413        doc.set(&["github", "write"], &json!(true)).unwrap();
414        doc.set(&["disabled_tools"], &json!([])).unwrap();
415        let value = doc.value().unwrap();
416        assert_eq!(
417            value["indexes"],
418            json!({"trigram": false, "semantic": false})
419        );
420        assert_eq!(value["github"], json!({"write": true}));
421        assert_eq!(value["disabled_tools"], json!([]));
422        assert!(doc.text().contains("\n  \"disabled_tools\": []"));
423        assert!(doc.text().contains("// keep me"));
424    }
425
426    #[test]
427    fn empty_documents_and_objects_accept_members() {
428        let mut doc = JsoncDocument::parse("").unwrap();
429        doc.set(&["disabled_tools"], &json!(["aft_move"])).unwrap();
430        assert_eq!(doc.text(), "{\n  \"disabled_tools\": [\"aft_move\"]\n}\n");
431        let mut doc = JsoncDocument::parse("{}").unwrap();
432        doc.set(&["a", "b"], &json!(1)).unwrap();
433        assert_eq!(doc.value().unwrap(), json!({"a": {"b": 1}}));
434    }
435
436    #[test]
437    fn removing_members_fixes_commas_and_keeps_comments() {
438        let mut doc = JsoncDocument::parse(COMMENTED).unwrap();
439        assert!(doc.remove(&["edit_mode"]).unwrap());
440        assert!(doc.remove(&["indexes"]).unwrap());
441        assert!(!doc.remove(&["missing"]).unwrap());
442        let value = doc.value().unwrap();
443        assert_eq!(value, json!({"$schema": "https://example/schema.json"}));
444        assert!(doc.text().contains("// keep me"));
445
446        let mut doc = JsoncDocument::parse("{\"a\": 1, \"b\": 2}").unwrap();
447        doc.remove(&["b"]).unwrap();
448        assert_eq!(doc.value().unwrap(), json!({"a": 1}));
449        let mut doc = JsoncDocument::parse("{\n  \"a\": 1,\n  \"b\": 2\n}").unwrap();
450        doc.remove(&["b"]).unwrap();
451        assert_eq!(doc.text(), "{\n  \"a\": 1\n}");
452    }
453
454    #[test]
455    fn empty_containers_can_be_dropped() {
456        let mut doc = JsoncDocument::parse("{\"gh_shim\": {\"enabled\": true}, \"x\": 1}").unwrap();
457        doc.remove(&["gh_shim", "enabled"]).unwrap();
458        assert!(doc.remove_if_empty_object(&["gh_shim"]).unwrap());
459        assert_eq!(doc.value().unwrap(), json!({"x": 1}));
460    }
461
462    #[test]
463    fn invalid_documents_are_refused() {
464        assert!(JsoncDocument::parse("[1]").is_err());
465        assert!(JsoncDocument::parse("{\"a\": }").is_err());
466        assert!(JsoncDocument::parse("{\"a\": 1} trailing").is_err());
467    }
468
469    #[test]
470    fn atomic_write_replaces_the_file_and_leaves_no_temporary() {
471        let dir = tempfile::tempdir().unwrap();
472        let path = dir.path().join("nested").join("aft.jsonc");
473        write_atomic(&path, "{\"a\": 1}\n").unwrap();
474        write_atomic(&path, "{\"a\": 2}\n").unwrap();
475        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"a\": 2}\n");
476        let entries: Vec<_> = std::fs::read_dir(path.parent().unwrap())
477            .unwrap()
478            .map(|entry| entry.unwrap().file_name())
479            .collect();
480        assert_eq!(entries.len(), 1);
481    }
482
483    #[cfg(unix)]
484    #[test]
485    fn atomic_write_preserves_config_symlinks() {
486        let dir = tempfile::tempdir().unwrap();
487        let target = dir.path().join("dotfiles.jsonc");
488        let link = dir.path().join("aft.jsonc");
489        std::fs::write(&target, "old").unwrap();
490        std::os::unix::fs::symlink("dotfiles.jsonc", &link).unwrap();
491        write_atomic(&link, "new").unwrap();
492        assert!(std::fs::symlink_metadata(&link)
493            .unwrap()
494            .file_type()
495            .is_symlink());
496        assert_eq!(std::fs::read_to_string(&target).unwrap(), "new");
497        assert_eq!(
498            std::fs::read_link(&link).unwrap(),
499            Path::new("dotfiles.jsonc")
500        );
501        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2);
502    }
503
504    #[cfg(unix)]
505    #[test]
506    fn atomic_write_refuses_dangling_config_symlinks() {
507        let dir = tempfile::tempdir().unwrap();
508        let link = dir.path().join("aft.jsonc");
509        std::os::unix::fs::symlink("missing.jsonc", &link).unwrap();
510        assert!(write_atomic(&link, "new").is_err());
511        assert!(std::fs::symlink_metadata(&link)
512            .unwrap()
513            .file_type()
514            .is_symlink());
515    }
516
517    #[cfg(unix)]
518    #[test]
519    fn atomic_write_syncs_target_directory() {
520        let dir = tempfile::tempdir().unwrap();
521        let path = dir.path().join("aft.jsonc");
522        crate::durability::take();
523        write_atomic(&path, "new").unwrap();
524        let events = crate::durability::take();
525        assert!(events.iter().any(|(kind, path)| {
526            *kind == crate::durability::EventKind::DirectorySync && path == dir.path()
527        }));
528        assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
529    }
530
531    #[test]
532    fn a_comment_between_members_stays_put_through_edits() {
533        let text = "{\n  \"a\": 1,\n  // about b\n  \"b\": 2,\n  /* about c */\n  \"c\": 3\n}\n";
534        let mut doc = JsoncDocument::parse(text).unwrap();
535        doc.set(&["b"], &json!(20)).unwrap();
536        doc.remove(&["c"]).unwrap();
537        doc.set(&["d"], &json!(true)).unwrap();
538        let out = doc.text();
539        assert!(out.contains("  // about b\n  \"b\": 20"), "{out}");
540        assert_eq!(doc.value().unwrap(), json!({"a": 1, "b": 20, "d": true}));
541    }
542
543    #[test]
544    fn trailing_commas_are_kept_and_edits_stay_loadable() {
545        let text = "{\n  \"a\": [1, 2,],\n  \"b\": {\"x\": 1,},\n}\n";
546        let mut doc = JsoncDocument::parse(text).unwrap();
547        doc.set(&["c"], &json!(false)).unwrap();
548        doc.set(&["b", "y"], &json!(2)).unwrap();
549        doc.remove(&["a"]).unwrap();
550        assert_eq!(
551            doc.value().unwrap(),
552            json!({"b": {"x": 1, "y": 2}, "c": false})
553        );
554        assert!(doc.text().trim_end().ends_with(",\n}"), "{}", doc.text());
555    }
556
557    #[test]
558    fn inline_nested_objects_accept_edits() {
559        let text = "{\"github\": {\"read\": true}, \"indexes\": {\"semantic\": false}}";
560        let mut doc = JsoncDocument::parse(text).unwrap();
561        doc.set(&["github", "write"], &json!(true)).unwrap();
562        doc.set(&["indexes", "semantic"], &json!(true)).unwrap();
563        doc.remove(&["github", "read"]).unwrap();
564        assert_eq!(
565            doc.value().unwrap(),
566            json!({"github": {"write": true}, "indexes": {"semantic": true}})
567        );
568    }
569
570    #[test]
571    fn crlf_line_endings_are_preserved() {
572        let text = "{\r\n  // note\r\n  \"a\": 1\r\n}\r\n";
573        let mut doc = JsoncDocument::parse(text).unwrap();
574        doc.set(&["b"], &json!(["x"])).unwrap();
575        doc.set(&["c", "d"], &json!(true)).unwrap();
576        let out = doc.text();
577        assert!(
578            !out.replace("\r\n", "").contains('\n'),
579            "bare LF in {out:?}"
580        );
581        assert!(out.contains("// note\r\n"));
582        assert_eq!(
583            doc.value().unwrap(),
584            json!({"a": 1, "b": ["x"], "c": {"d": true}})
585        );
586    }
587
588    #[test]
589    fn empty_object_and_empty_file_both_accept_members() {
590        for text in ["{}", "", "  \n", "{}\n"] {
591            let mut doc = JsoncDocument::parse(text).unwrap();
592            assert_eq!(doc.value().unwrap(), json!({}));
593            assert!(!doc.remove(&["x"]).unwrap());
594            doc.set(&["disabled_tools"], &json!([])).unwrap();
595            doc.set(&["github", "write"], &json!(true)).unwrap();
596            assert_eq!(
597                doc.value().unwrap(),
598                json!({"disabled_tools": [], "github": {"write": true}}),
599                "{text:?} -> {}",
600                doc.text()
601            );
602        }
603    }
604
605    #[test]
606    fn duplicate_keys_edit_the_last_occurrence_like_the_loader() {
607        let mut doc = JsoncDocument::parse("{\"a\": 1, \"a\": 2}").unwrap();
608        doc.set(&["a"], &json!(3)).unwrap();
609        assert_eq!(doc.value().unwrap(), json!({"a": 3}));
610    }
611}