Dough Git

commit

Show effective configuration as JPCL

commit
7ebdb7dff2300d0b00b217ab280b1c863db61b42
author
Clove <[email protected]>
date
2026-11-23 11:39
Seed the global configuration from bundled defaults and prepare alpha 2.

Co-Authored-By: Sandrone <[email protected]>

diff --git a/Cargo.lock b/Cargo.lock
index d50bd4d..13c78b2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -19,7 +19,7 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
 
 [[package]]
 name = "c4d"
-version = "1.0.0-alpha-1"
+version = "1.0.0-alpha-2"
 dependencies = [
  "jpcl",
  "proc-macro2",
diff --git a/Cargo.toml b/Cargo.toml
index 85a0a76..896db26 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
 
 [package]
 name = "c4d"
-version = "1.0.0-alpha-1"
+version = "1.0.0-alpha-2"
 edition = "2024"
 rust-version = "1.85"
 description = "Local source-code formatting and accessibility checks"
@@ -21,6 +21,8 @@ include = [
 jpcl = "=2.0.0"
 proc-macro2 = { version = "=1.0.106", features = ["span-locations"] }
 regex = "=1.12.3"
-serde_json = "=1.0.149"
 syn = { version = "=2.0.117", features = ["full", "visit"] }
 tempfile = "=3.27.0"
+
+[dev-dependencies]
+serde_json = "=1.0.149"
diff --git a/README.md b/README.md
index acd3fc7..8c97ba1 100644
--- a/README.md
+++ b/README.md
@@ -14,8 +14,14 @@ Those choices can depend on intent, public interfaces, or a reader's preferences
 
 ## Install
 
-After the first crates.io release, install with `cargo install c4d --locked`.
-To install from source, run this from the repository root.
+Install the published alpha from crates.io by specifying its version explicitly.
+
+```sh
+cargo install c4d --version 1.0.0-alpha-1 --locked
+```
+
+Cargo skips prereleases when you omit the version. To install the current
+checkout instead, run this from the repository root.
 
 ```sh
 cargo install --path . --locked
@@ -44,7 +50,7 @@ c4d config show src/main.rs --language rust
 | `check` | Reports naming and formatting issues with file, line, and column. |
 | `format` | Applies whitespace rules and adds path headers when enabled. |
 | `format --check` | Lists files that would change without writing. |
-| `config show` | Prints effective settings and the source of each value as JSON. |
+| `config show` | Prints effective settings as JPCL, with the source of each value in comments. |
 
 Paths default to the current directory. `check` and `format` accept multiple
 files and directories. Use `--` before input paths starting with a dash.
@@ -56,6 +62,9 @@ file by file, so an error can occur after other files have been written.
 
 ## Configuration
 
+`c4d config show` creates `~/.c4d/config.jp` from the bundled defaults if it
+is missing. Existing global settings keep their contents.
+
 Use `~/.c4d/config.jp` for global settings and
 `<project-root>/.c4d/config.jp` for project settings. C4D looks upward from
 each source directory for the nearest project file and stops at the Git root
@@ -157,7 +166,7 @@ color: catppuccin
 | `plain` | Plain text. |
 
 Themes style rule names and formatting status labels. Those labels remain
-readable in plain text. Redirected output, JSON, `TERM=dumb`, and a non-empty
+readable in plain text. Redirected output, configuration output, `TERM=dumb`, and a non-empty
 `NO_COLOR` environment variable all produce plain text. The RGB themes work
 best in a true-colour terminal. To choose a theme for Rust specifically,
 set `color` under `[overrides.rust.terminal]`.
diff --git a/src/config.rs b/src/config.rs
index 35d388a..50ac046 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,12 +1,13 @@
 // src/config.rs
 
 use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::fmt::Write as _;
 use std::fs;
-use std::io::ErrorKind;
+use std::io::{ErrorKind, Write as _};
 use std::path::{Path, PathBuf};
 
 use jpcl::{Object, ParseOptions, Value};
-use serde_json::{Value as Json, json};
+use tempfile::NamedTempFile;
 
 use crate::terminal::Theme;
 
@@ -21,18 +22,15 @@ pub const CLASSES: &str = "cases.classes";
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
 pub enum Case {
-
     Flat,
     Camel,
     Pascal,
     Snake,
     ScreamingSnake,
     Disabled,
-
 }
 
 impl Case {
-
     fn parse(label: &str) -> Option<Self> {
         match label {
             "flatcase" => Some(Self::Flat),
@@ -47,14 +45,12 @@ impl Case {
 
     pub fn label(self) -> &'static str {
         match self {
-
             Self::Flat => "flatcase",
             Self::Camel => "camelCase",
             Self::Pascal => "PascalCase",
             Self::Snake => "snake_case",
             Self::ScreamingSnake => "SCREAMING_SNAKE_CASE",
             Self::Disabled => "disabled",
-            
         }
     }
 
@@ -269,22 +265,82 @@ impl Effective {
         }
     }
 
-    pub fn json(&self) -> Json {
-        json!({
-            "formatting": {
-                "indentSize": self.indent_size(),
-                "newLineSize": self.newline_size(),
-                "filePathHeader": self.file_path_header(),
-            },
-            "cases": {
-                "functions": self.convention(FUNCTIONS).label(),
-                "variables": self.convention(VARIABLES).label(),
-                "classes": self.convention(CLASSES).label(),
-            },
-            "terminal": { "color": self.theme().name },
-            "origins": self.origins,
-        })
+    pub fn document(&self) -> Object {
+        let sections = [
+            (
+                "terminal",
+                Object::from_iter([("color".into(), Value::String(self.theme().name.into()))]),
+            ),
+            (
+                "formatting",
+                Object::from_iter([
+                    (
+                        "indentSize".into(),
+                        Value::Integer(self.indent_size() as i128),
+                    ),
+                    (
+                        "newLineSize".into(),
+                        Value::Integer(self.newline_size() as i128),
+                    ),
+                    (
+                        "filePathHeader".into(),
+                        Value::Bool(self.file_path_header()),
+                    ),
+                    ]),
+            ),
+            (
+                "cases",
+                Object::from_iter([
+                    (
+                        "functions".into(),
+                        Value::String(self.convention(FUNCTIONS).label().into()),
+                    ),
+                    (
+                        "variables".into(),
+                        Value::String(self.convention(VARIABLES).label().into()),
+                    ),
+                    (
+                        "classes".into(),
+                        Value::String(self.convention(CLASSES).label().into()),
+                    ),
+                    ]),
+            ),
+        ];
+        sections
+        .into_iter()
+        .map(|(key, section)| (key.into(), Value::Object(section)))
+        .collect()
     }
+
+    pub fn write_origins(&self, output: &mut String, prefix: &str) {
+        for (key, origin) in &self.origins {
+            writeln!(output, "~~ {prefix}{key} from {}", origin.escape_debug()).unwrap();
+        }
+    }
+}
+
+pub fn initialize_global(home: &Path) -> Result<(), String> {
+    let directory = home.join(".c4d");
+    let path = directory.join("config.jp");
+    let initialize = || -> std::io::Result<()> {
+        match path.symlink_metadata() {
+            Ok(_) => return Ok(()),
+            Err(error) if error.kind() == ErrorKind::NotFound => {}
+            Err(error) => return Err(error),
+        }
+
+        fs::create_dir_all(&directory)?;
+        let mut temporary = NamedTempFile::new_in(&directory)?;
+        temporary.write_all(DEFAULT_SOURCE.as_bytes())?;
+
+        match temporary.persist_noclobber(&path) {
+            Ok(_) => Ok(()),
+            Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(()),
+            Err(error) => Err(error.error),
+        }
+    };
+
+    initialize().map_err(|error| format!("{}: {error}", path.display()))
 }
 
 pub struct ConfigStore {
diff --git a/src/main.rs b/src/main.rs
index a2c3169..4b312bd 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -17,7 +17,7 @@ use std::io::{self, IsTerminal, Write};
 use std::path::Path;
 use std::process::ExitCode;
 
-use serde_json::{Map, json};
+use jpcl::{Object, StringifyOptions, Value};
 use tempfile::NamedTempFile;
 
 use crate::config::ConfigStore;
@@ -56,7 +56,11 @@ fn report(path: &Path, source: &str, issues: &[Diagnostic], terminal: &Terminal)
         }
 
         let column = source[line_start..issue.offset].chars().count() + 1;
-        let tone = if issue.rule == "syntax" { Tone::Error } else { Tone::Notice };
+        let tone = if issue.rule == "syntax" {
+            Tone::Error
+        } else {
+            Tone::Notice
+        };
         let rule = terminal.paint(tone, issue.rule);
         println!(
             "{}:{line}:{column} {} — {}",
@@ -168,12 +172,20 @@ fn inspect(
             1
         }
         Mode::DryRun if analysis.formatted != source => {
-            println!("{}: {}", shown.display(), terminal.paint(Tone::Notice, "would format"));
+            println!(
+                "{}: {}",
+                shown.display(),
+                terminal.paint(Tone::Notice, "would format")
+            );
             1
         }
         Mode::Write if analysis.formatted != source => {
             replace_source(path, source, &analysis.formatted).map_err(|error| error.to_string())?;
-            println!("{}: {}", shown.display(), terminal.paint(Tone::Success, "formatted"));
+            println!(
+                "{}: {}",
+                shown.display(),
+                terminal.paint(Tone::Success, "formatted")
+            );
             0
         }
         _ => 0,
@@ -181,11 +193,7 @@ fn inspect(
     Ok(Some((status, terminal)))
 }
 
-fn show_config(
-    arguments: &[OsString],
-    config: &mut ConfigStore,
-    discovery: &Discovery,
-) -> Result<u8, String> {
+fn show_config(arguments: &[OsString], discovery: &Discovery) -> Result<u8, String> {
     let mut iter = arguments.iter();
     let mut language = None;
     let mut input = None;
@@ -215,34 +223,41 @@ fn show_config(
     } else {
         path.parent().unwrap_or(&path)
     };
+    let home = env::home_dir();
+
+    if let Some(home) = &home {
+        config::initialize_global(home)?;
+    }
+
+    let mut config = ConfigStore::load(home.as_deref())?;
     let project = config.project(directory)?;
     let root = project.as_deref();
+    let effective = config.settings(root, language);
+    let mut document = effective.document();
+    let mut origins = String::from("\n~~ Setting origins\n");
+    effective.write_origins(&mut origins, "");
 
-    let output = if let Some(language) = language {
-        config.settings(root, Some(language)).json()
-    } else {
+    if language.is_none() {
+        let mut overrides = Object::new();
         let mut ids = config.override_languages(root);
         ids.extend(
             language::LANGUAGES
             .iter()
             .map(|language| language.id.to_owned()),
         );
-        let by_language: Map<_, _> = ids
-        .into_iter()
-        .map(|language| {
-            let effective = config.settings(root, Some(&language)).json();
-            (language, effective)
-            })
-        .collect();
-        json!({
-            "base": config.settings(root, None).json(),
-            "languages": by_language,
-        })
-    };
 
-    println!(
-        "{}",
-        serde_json::to_string_pretty(&output).map_err(|error| error.to_string())?
+        for id in ids {
+            let effective = config.settings(root, Some(&id));
+            overrides.insert(&id, Value::Object(effective.document()));
+            effective.write_origins(&mut origins, &format!("overrides.{id}."));
+        }
+
+        document.insert("overrides", Value::Object(overrides));
+    }
+
+    print!(
+        "{}{origins}",
+        jpcl::stringify(&document, &StringifyOptions::default())
     );
     Ok(0)
 }
@@ -264,8 +279,7 @@ fn run(arguments: Vec<OsString>) -> Result<u8, String> {
     let mut discovery = Discovery::new(working_directory.clone());
 
     if command == Some("config") && arguments.get(1) == Some(&OsString::from("show")) {
-        let mut config = ConfigStore::load(env::home_dir().as_deref())?;
-        return show_config(&arguments[2..], &mut config, &discovery);
+        return show_config(&arguments[2..], &discovery);
     }
 
     let mut mode = match command {
@@ -355,7 +369,10 @@ fn run(arguments: Vec<OsString>) -> Result<u8, String> {
                 Mode::Write => "Formatting complete",
             };
             let noun = if scanned == 1 { "file" } else { "files" };
-            println!("{} ({scanned} {noun} checked).", terminal.paint(Tone::Success, label));
+            println!(
+                "{} ({scanned} {noun} checked).",
+                terminal.paint(Tone::Success, label)
+            );
         } else {
             println!("No supported source files to check.");
         }
diff --git a/tests/cli.rs b/tests/cli.rs
index b9164bc..7195629 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -55,10 +55,16 @@ impl Workspace {
         output
     }
 
-    fn config(&self, arguments: &[&str]) -> Value {
+    fn config_source(&self, arguments: &[&str]) -> Vec<u8> {
         let mut command = vec!["config", "show"];
         command.extend(arguments);
-        serde_json::from_slice(&self.cli(&command, 0).stdout).unwrap()
+        self.cli(&command, 0).stdout
+    }
+
+    fn config(&self, arguments: &[&str]) -> Value {
+        let source = self.config_source(arguments);
+        let parsed = jpcl::parse_bytes(&source, &jpcl::ParseOptions::default()).unwrap();
+        serde_json::from_str(&jpcl::to_json(&jpcl::Value::Object(parsed), 2)).unwrap()
     }
 }
 
@@ -72,8 +78,8 @@ fn write(path: impl AsRef<Path>, source: impl AsRef<[u8]>) {
 fn inherited_values_merge_by_field_and_preserve_disabled_and_zero() {
     let workspace = Workspace::new();
     let defaults = workspace.config(&[]);
-    assert_eq!(defaults["languages"]["rust"]["formatting"]["indentSize"], 4);
-    assert_eq!(defaults["base"]["cases"]["functions"], "disabled");
+    assert_eq!(defaults["overrides"]["rust"]["formatting"]["indentSize"], 4);
+    assert_eq!(defaults["cases"]["functions"], "disabled");
 
     write(
         workspace.home.join(".c4d/config.jp"),
@@ -108,22 +114,21 @@ functions: PascalCase
     workspace.write("src/nested/main.rs", "fn main() {}");
 
     let settings = workspace.config(&["src/nested/main.rs"]);
-    let base = &settings["base"];
-    let rust = &settings["languages"]["rust"];
+    let base = &settings;
+    let rust = &settings["overrides"]["rust"];
     assert_eq!(base["formatting"]["newLineSize"], 5);
     assert_eq!(rust["formatting"]["indentSize"], 0);
     assert_eq!(rust["formatting"]["newLineSize"], 3);
     assert_eq!(rust["cases"]["functions"], "disabled");
     assert_eq!(rust["cases"]["classes"], "PascalCase");
     assert_eq!(rust["cases"]["variables"], "snake_case");
-    assert!(
-        rust["origins"]["formatting.newLineSize"]
-            .as_str()
-            .unwrap()
-            .ends_with("[overrides.rust]")
-    );
+    let source = workspace.config_source(&["src/nested/main.rs"]);
+    assert!(String::from_utf8_lossy(&source).lines().any(|line| {
+        line.starts_with("~~ overrides.rust.formatting.newLineSize from ")
+            && line.ends_with("[overrides.rust]")
+    }));
     assert_eq!(
-        settings["languages"]["typescript"]["cases"]["functions"],
+        settings["overrides"]["typescript"]["cases"]["functions"],
         "PascalCase"
     );
 
@@ -138,7 +143,7 @@ fn missing_configuration_stops_at_git_root_and_invalid_configuration_fails() {
     let workspace = Workspace::new();
     workspace.write("../.c4d/config.jp", "[formatting]\nindentSize: 8\n");
     workspace.write(".git/HEAD", "ref: refs/heads/main");
-    assert_eq!(workspace.config(&[])["base"]["formatting"]["indentSize"], 4);
+    assert_eq!(workspace.config(&[])["formatting"]["indentSize"], 4);
 
     for invalid in [
         "[formatting",
@@ -440,10 +445,7 @@ fn file_path_headers_are_opt_in_and_use_project_paths() {
     workspace.write("src/main.rs", source);
     workspace.cli(&["format", "."], 0);
     assert_eq!(workspace.read("src/main.rs"), source);
-    assert_eq!(
-        workspace.config(&[])["base"]["formatting"]["filePathHeader"],
-        false
-    );
+    assert_eq!(workspace.config(&[])["formatting"]["filePathHeader"], false);
 
     workspace.write(
         ".c4d/config.jp",
@@ -540,14 +542,23 @@ fn version_command_and_flags_report_the_build_version() {
 #[test]
 fn output_theme_inherits_and_captured_output_stays_plain() {
     let workspace = Workspace::new();
-    assert_eq!(workspace.config(&[])["base"]["terminal"]["color"], "default");
-    write(workspace.home.join(".c4d/config.jp"), "[terminal]\ncolor: pastel");
-    workspace.write(".c4d/config.jp", "[overrides.rust.terminal]\ncolor: catppuccin");
+    assert_eq!(workspace.config(&[])["terminal"]["color"], "default");
+    write(
+        workspace.home.join(".c4d/config.jp"),
+        "[terminal]\ncolor: pastel",
+    );
+    workspace.write(
+        ".c4d/config.jp",
+        "[overrides.rust.terminal]\ncolor: catppuccin",
+    );
     workspace.write("main.rs", "fn main() {\nlet value = 1;\n}\n");
 
     let config = workspace.config(&[]);
-    assert_eq!(config["base"]["terminal"]["color"], "pastel");
-    assert_eq!(config["languages"]["rust"]["terminal"]["color"], "catppuccin");
+    assert_eq!(config["terminal"]["color"], "pastel");
+    assert_eq!(
+        config["overrides"]["rust"]["terminal"]["color"],
+        "catppuccin"
+    );
     let preview = workspace.cli(&["format", "--check", "."], 1);
     assert_eq!(preview.stdout, b"main.rs: would format\n");
 
@@ -555,3 +566,28 @@ fn output_theme_inherits_and_captured_output_stays_plain() {
     let invalid = workspace.cli(&["config", "show"], 2);
     assert!(String::from_utf8_lossy(&invalid.stderr).contains("terminal.color"));
 }
+
+#[test]
+fn config_show_initializes_the_global_file_and_preserves_user_edits() {
+    let workspace = Workspace::new();
+    let global = workspace.home.join(".c4d/config.jp");
+
+    assert!(!global.exists());
+    workspace.cli(&["check", "."], 0);
+    assert!(!global.exists());
+
+    let source = workspace.config_source(&[]);
+    assert!(String::from_utf8_lossy(&source).starts_with("[terminal]"));
+    assert_eq!(
+        fs::read(&global).unwrap(),
+        include_bytes!("../data/default.jp")
+    );
+
+    let custom = b"~~ My preferences\n[formatting]\nindentSize: 8\n";
+    fs::write(&global, custom).unwrap();
+    assert_eq!(
+        workspace.config(&["--language", "rust"])["formatting"]["indentSize"],
+        8
+    );
+    assert_eq!(fs::read(&global).unwrap(), custom);
+}