commit
initial commit
diff --git a/.c4d/config.jp b/.c4d/config.jp
new file mode 100644
index 0000000..80326b7
--- /dev/null
+++ b/.c4d/config.jp
@@ -0,0 +1,19 @@
+~~ .c4d/config.jp
+
+[terminal]
+color: catppuccin
+
+[formatting]
+filePathHeader: true
+newLineSize: 2
+indentSize: 4
+
+[overrides]
+typescript: {
+ formatting: {
+ newLineSize: 3
+ },
+ cases: {
+ functions: camelCase
+ }
+}
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..0cc2574
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,44 @@
+# .github/workflows/publish.yml
+
+name: Publish c4d to crates.io
+
+on:
+ push:
+ tags:
+ - 'v*'
+
+permissions:
+ contents: read
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ environment: crates-io
+ permissions:
+ contents: read
+ id-token: write
+ steps:
+ - name: Check out release
+ uses: actions/checkout@v5
+ with:
+ persist-credentials: false
+
+ - name: Verify tag matches Cargo version
+ run: |
+ version="$(cargo metadata --locked --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "c4d") | .version')"
+ if [[ "$GITHUB_REF_NAME" != "v$version" ]]; then
+ echo "Release tag must be v$version, found $GITHUB_REF_NAME." >&2
+ exit 1
+ fi
+
+ - name: Test release
+ run: cargo test --locked
+
+ - name: Authenticate with crates.io
+ id: crates-io
+ uses: rust-lang/crates-io-auth-action@v1
+
+ - name: Publish c4d
+ run: cargo publish --locked
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ steps.crates-io.outputs.token }}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..39afb48
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,18 @@
+# --- Rust ---
+target/
+
+# --- Node ---
+node_modules/
+dist/
+out/
+
+# --- AI Agents ---
+.gemini/
+.codex/
+.claude/
+.aws/
+.agents/
+
+# --- IDEs ---
+.idea/
+.vscode/
\ No newline at end of file
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..d50bd4d
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,269 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "c4d"
+version = "1.0.0-alpha-1"
+dependencies = [
+ "jpcl",
+ "proc-macro2",
+ "regex",
+ "serde_json",
+ "syn 2.0.117",
+ "tempfile",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "errno"
+version = "0.3.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "jpcl"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7382dd2f498998b20f643f96c5a89dc49baad7f5d1d28d3d44dc8b56e9b42da7"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "regex"
+version = "1.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
+
+[[package]]
+name = "rustix"
+version = "1.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.10",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom",
+ "once_cell",
+ "rustix",
+ "windows-sys",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..85a0a76
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,26 @@
+# Cargo.toml
+
+[package]
+name = "c4d"
+version = "1.0.0-alpha-1"
+edition = "2024"
+rust-version = "1.85"
+description = "Local source-code formatting and accessibility checks"
+license = "MIT"
+repository = "https://github.com/doughmination/code4dyslexia"
+readme = "README.md"
+include = [
+ "/src/**",
+ "/tests/**",
+ "/data/default.jp",
+ "/LICENSE",
+ "/README.md",
+]
+
+[dependencies]
+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"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..b414b04
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Clove Twilight
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..acd3fc7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,266 @@
+<!-- README.md -->
+
+# code4dyslexia
+
+`c4d` is a local formatter and naming checker for developers with dyslexia. The
+same file and settings produce the same output. The executable needs no AI,
+API keys, network access, or language-server process.
+
+The [dyslexia-friendly-code skill](https://github.com/doughmination/dyslexia-friendly-code)
+inspired consistent indentation, spacing between logical blocks, and optional
+checks for common naming conventions. C4D leaves line wrapping, comment
+placement, file headers, identifier similarity, and renaming to the author.
+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.
+
+```sh
+cargo install --path . --locked
+c4d version
+```
+
+Cargo may fetch dependencies on the first build. For a machine with a populated
+Cargo cache, add `--offline` to install without the network. Cargo installs the
+native executable in `~/.cargo/bin` by default. Alternatively, build with
+`cargo build --release --locked` and run `target/release/c4d`.
+
+## Commands
+
+```sh
+c4d version
+c4d check .
+c4d format .
+c4d format --check src/main.rs tests/
+c4d config show
+c4d config show src/main.rs --language rust
+```
+
+| Command | Behaviour |
+| --- | --- |
+| `version` | Prints the installed version. Also available as `-V` and `--version`. |
+| `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. |
+
+Paths default to the current directory. `check` and `format` accept multiple
+files and directories. Use `--` before input paths starting with a dash.
+Successful interactive scans print a summary, including when no supported files are found.
+Exit code `0` means the command succeeded, `1` means a check found issues,
+and `2` means usage, configuration, syntax, or I/O errors. Explicit skips are
+reported on stderr and do not count as issues. A formatting run operates
+file by file, so an error can occur after other files have been written.
+
+## Configuration
+
+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
+if it finds one first. A nested project config takes the project layer for
+files in its subtree.
+
+Each setting inherits independently. From lowest to highest precedence
+
+1. Built-in defaults
+2. Global settings
+3. Global language override
+4. Project settings
+5. Project language override
+
+Omit a key to inherit it. Set a formatting option to `0` to disable that
+transformation, or a naming option to `disabled` to turn off its check.
+Formatting sizes are integers from 0 to 100. Invalid configuration reports the
+file and, for JPCL syntax errors, the parser's line and column.
+
+The official [JPCL parser](https://github.com/jpcl-lang/jpcl) accepts bare
+setting values, `[section]` headers, nested objects, line comments beginning
+with `~~`, and block comments wrapped in `~*` and `*~`.
+The following [default file](data/default.jp) is embedded in the executable.
+
+```jpcl
+~* Default configuration for code4dyslexia
+ (c) MIT - Clove Twilight 2026
+ https://github.com/doughmination/code4dyslexia
+*~
+
+[terminal]
+color: default
+
+[formatting]
+~~ Set any of these to 0 to disable them
+indentSize: 4
+newLineSize: 2
+~~ Enable to add a file path comment automatically
+filePathHeader: false
+
+[cases]
+~* Accepted values:
+ flatcase - acoolfunction
+ camelCase - aCoolFunction
+ PascalCase - ACoolFunction
+ snake_case - a_cool_function
+ SCREAMING_SNAKE_CASE - A_COOL_FUNCTION
+ disabled - Disables checks
+*~
+functions: disabled
+variables: disabled
+classes: disabled
+
+~~ Uncomment the override block to customise individual languages
+
+~*
+[overrides]
+typescript: {
+ formatting: {
+ newLineSize: 3
+ }
+ cases: {
+ functions: camelCase
+ }
+}
+*~
+```
+
+The commented TypeScript example is valid JPCL and can be inspected when
+enabled. Language overrides for an adapter that has yet to be implemented
+have no effect on file processing. To configure the Rust adapter, use the
+`rust` language identifier.
+
+```jpcl
+[overrides.rust.formatting]
+newLineSize: 3
+
+[overrides.rust.cases]
+functions: snake_case
+```
+
+## Terminal colours
+
+Choose a theme in global or project JPCL settings.
+
+```jpcl
+[terminal]
+color: catppuccin
+```
+
+| Theme | Appearance |
+| --- | --- |
+| `default` or `normal` | Standard terminal colours. This is the default. |
+| `pastel` | Soft teal, lilac, and rose accents. |
+| `catppuccin` | Green, yellow, and red from [Catppuccin Mocha](https://catppuccin.com/palette/#mocha). |
+| `protanopia`, `protanomaly`, `deuteranopia`, `deuteranomaly` | Blue and amber accents for red–green colour vision differences. |
+| `tritanopia`, `tritanomaly` | Green and pink accents for blue–yellow colour vision differences. |
+| `achromatopsia`, `blue-cone-monochromacy`, `monochrome` | Bold and underlined labels without colour. |
+| `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
+`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]`.
+
+## Supported sources
+
+The initial adapter handles UTF-8 Rust files (`.rs`, case-insensitive).
+TypeScript, Python, and other file types are skipped. The adapter uses
+[syn](https://docs.rs/syn/2.0.117/syn/) for the syntax tree and
+[proc-macro2](https://docs.rs/proc-macro2/1.0.106/proc_macro2/struct.Span.html)
+for source token spans.
+
+### Formatting
+
+- `indentSize` controls leading spaces on lines that begin with a token.
+ Each active multiline brace, bracket, or parenthesis group contributes
+ one level. Nested groups opened on the same line share a level. A line
+ that begins with a closing delimiter uses the enclosing level.
+- `newLineSize` counts newline sequences between sibling items or statements
+ already on separate lines, where at least one sibling is a logical block.
+ Logical blocks include functions, structs, enums, unions, impls, traits,
+ modules, and extern blocks. At statement level they also include standalone
+ blocks and control-flow expressions such as `if`, `match`, and loops.
+ C4D edits gaps made entirely of whitespace and uses the first newline
+ sequence in the gap. A size of `2` gives one empty line.
+- By default, formatting edits only leading indentation and qualifying gaps. Literals,
+ comments, macro arguments, and attribute contents keep their bytes.
+ Files containing explicit `line!()` or `column!()` calls retain all source
+ positions. Checks still report naming issues in those files.
+
+The syntax check is based on the parser available in the pinned version of
+`syn`. It does not type-check, resolve names, evaluate configuration
+attributes, or expand macros. Some macro-expanded code and compiler features
+are opaque to the tool. Formatting can shift source locations observed
+indirectly through macros, compiler diagnostics, or caller metadata.
+
+### File path headers
+
+Enable this option in `.c4d/config.jp` to have `c4d format` add a comment
+such as `// src/main.rs`. The option defaults to `false`.
+
+```jpcl
+[formatting]
+filePathHeader: true
+```
+
+C4D uses the path relative to the project root, or the working directory
+when there is no project root. Files outside both use their basename.
+The comment goes after a byte-order mark or shebang when present.
+An exact matching path in the leading comments counts as an existing header.
+`c4d check` reports missing headers and `c4d format --check` previews them.
+Files with explicit `line!()` or `column!()` calls also skip header insertion.
+
+### Naming
+
+| Option | Rust declarations checked |
+| --- | --- |
+| `functions` | Named functions and method signatures |
+| `variables` | Pattern bindings, including function parameters, and named const and static items |
+| `classes` | Structs, enums, unions, and traits |
+
+All checks are disabled by default. With a check enabled, names are matched
+against that convention's ASCII letters, digits, and underscore pattern.
+A Rust raw identifier prefix `r#` is ignored for matching. Diagnostics
+never change the identifier.
+
+### Discovery
+
+Directories are traversed in name order. The tool skips symlinks, non-source
+files, and common dependency, cache, and build directories such as `.git`,
+`node_modules`, `target`, `vendor`, and `dist`. It also skips invalid UTF-8,
+files with NUL bytes, generated suffixes such as `.generated.rs`, and
+recognised generated markers in the leading comments. Add unusual generated
+paths to `.c4dignore`.
+
+C4D reads ancestor and nested `.gitignore` and `.c4dignore` files. It supports
+ordinary Git-style path patterns, including anchors, directory-only patterns,
+wildcards, character ranges, escaped leading markers, and negation. Global
+Git excludes and `.git/info/exclude` are outside this first release.
+
+Writes replace a changed file atomically and preserve its permission bits.
+On Unix, C4D rejects files with multiple hard links. It checks for changes to
+the source immediately before replacement. Avoid concurrent formatting and
+editing of the same file.
+
+## Contributing
+
+Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`,
+and `cargo test --locked` before submitting a change. When adding a language,
+register its adapter in `src/language.rs` and add representative fixtures
+covering syntax-sensitive whitespace, literals, comments, and repeat runs.
+Keep transformations constrained to the spans that the adapter can verify.
+
+## Publishing
+
+1. Verify the package with `cargo publish --locked --dry-run`. For the first
+ release, authenticate locally and run `cargo publish --locked` from a clean
+ checkout.
+2. Set up [crates.io Trusted Publishing](https://crates.io/docs/trusted-publishing)
+ for `doughmination/code4dyslexia`. Use the workflow filename `publish.yml`
+ and the GitHub environment `crates-io`.
+3. For later versions, push a tag such as `v0.1.1` that matches `Cargo.toml`.
+ The [release workflow](.github/workflows/publish.yml) runs the tests and
+ publishes via an OIDC token.
+
+[MIT licence](LICENSE).
diff --git a/data/default.jp b/data/default.jp
new file mode 100644
index 0000000..c7e016a
--- /dev/null
+++ b/data/default.jp
@@ -0,0 +1,41 @@
+~* Default configuration for code4dyslexia
+ (c) MIT - Clove Twilight 2026
+ https://github.com/doughmination/code4dyslexia
+*~
+
+[terminal]
+color: default
+
+[formatting]
+~~ Set any of these to 0 to disable them
+indentSize: 4
+newLineSize: 2
+~~ Enable to add a file path comment automatically
+filePathHeader: false
+
+[cases]
+~* Accepted values:
+ flatcase - acoolfunction
+ camelCase - aCoolFunction
+ PascalCase - ACoolFunction
+ snake_case - a_cool_function
+ SCREAMING_SNAKE_CASE - A_COOL_FUNCTION
+ disabled - Disables checks
+*~
+functions: disabled
+variables: disabled
+classes: disabled
+
+~~ Uncomment the override block to customise individual languages
+
+~*
+[overrides]
+typescript: {
+ formatting: {
+ newLineSize: 3
+ }
+ cases: {
+ functions: camelCase
+ }
+}
+*~
diff --git a/src/config.rs b/src/config.rs
new file mode 100644
index 0000000..35d388a
--- /dev/null
+++ b/src/config.rs
@@ -0,0 +1,410 @@
+// src/config.rs
+
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::fs;
+use std::io::ErrorKind;
+use std::path::{Path, PathBuf};
+
+use jpcl::{Object, ParseOptions, Value};
+use serde_json::{Value as Json, json};
+
+use crate::terminal::Theme;
+
+const THEME: &str = "terminal.color";
+const DEFAULT_SOURCE: &str = include_str!("../data/default.jp");
+const INDENT: &str = "formatting.indentSize";
+pub const FILE_HEADER: &str = "formatting.filePathHeader";
+const NEWLINE: &str = "formatting.newLineSize";
+pub const FUNCTIONS: &str = "cases.functions";
+pub const VARIABLES: &str = "cases.variables";
+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),
+ "camelCase" => Some(Self::Camel),
+ "PascalCase" => Some(Self::Pascal),
+ "snake_case" => Some(Self::Snake),
+ "SCREAMING_SNAKE_CASE" => Some(Self::ScreamingSnake),
+ "disabled" => Some(Self::Disabled),
+ _ => None,
+ }
+ }
+
+ 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",
+
+ }
+ }
+
+ pub fn matches(self, name: &str) -> bool {
+ let mut remaining = name.bytes();
+ let first = remaining.next().unwrap_or_default();
+
+ match self {
+ Self::Disabled => true,
+ Self::Flat => {
+ first.is_ascii_lowercase()
+ && remaining.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
+ }
+ Self::Camel => {
+ first.is_ascii_lowercase() && remaining.all(|byte| byte.is_ascii_alphanumeric())
+ }
+ Self::Pascal => {
+ first.is_ascii_uppercase() && remaining.all(|byte| byte.is_ascii_alphanumeric())
+ }
+ Self::Snake | Self::ScreamingSnake => {
+ let letter = |byte: u8| {
+ if self == Self::Snake {
+ byte.is_ascii_lowercase()
+ } else {
+ byte.is_ascii_uppercase()
+ }
+ };
+ letter(first)
+ && name.split('_').all(|word| {
+ !word.is_empty()
+ && word
+ .bytes()
+ .all(|byte| letter(byte) || byte.is_ascii_digit())
+ })
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+enum Setting {
+ Size(usize),
+ Toggle(bool),
+ Case(Case),
+ Theme(Theme),
+}
+
+type Layer = BTreeMap<&'static str, Setting>;
+
+#[derive(Debug)]
+struct Config {
+ base: Layer,
+ overrides: BTreeMap<String, Layer>,
+ origin: String,
+}
+
+fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Object, String> {
+ value
+ .as_object()
+ .ok_or_else(|| format!("{path} must be an object"))
+}
+
+fn parse_section(
+ layer: &mut Layer,
+ section: &str,
+ value: &Value,
+ origin: &str,
+) -> Result<(), String> {
+ let path = format!("{origin}.{section}");
+
+ if !matches!(section, "formatting" | "cases" | "terminal") {
+ return Err(format!("{path} is unknown"));
+ }
+
+ for (key, value) in object(value, &path)?.iter() {
+ let field = format!("{path}.{key}");
+ let full_key = match (section, key) {
+ ("formatting", "indentSize") => INDENT,
+ ("formatting", "filePathHeader") => FILE_HEADER,
+ ("formatting", "newLineSize") => NEWLINE,
+ ("terminal", "color") => THEME,
+ ("cases", "functions") => FUNCTIONS,
+ ("cases", "variables") => VARIABLES,
+ ("cases", "classes") => CLASSES,
+ _ => return Err(format!("{field} is unknown")),
+ };
+
+ let setting = if full_key == THEME {
+ let theme = value.as_str().and_then(Theme::parse).ok_or_else(|| {
+ let names = Theme::names().collect::<Vec<_>>().join(", ");
+ format!("{field} must be one of {names}")
+ })?;
+ Setting::Theme(theme)
+ } else if full_key == FILE_HEADER {
+ let Value::Bool(enabled) = value else {
+ return Err(format!("{field} must be true or false"));
+ };
+ Setting::Toggle(*enabled)
+ } else if section == "formatting" {
+ let Value::Integer(value @ 0..=100) = value else {
+ return Err(format!("{field} must be an integer from 0 to 100"));
+ };
+ Setting::Size(*value as usize)
+ } else {
+ let convention = value.as_str().and_then(Case::parse).ok_or_else(|| {
+ format!("{field} must be flatcase, camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, or disabled")
+ })?;
+ Setting::Case(convention)
+ };
+ layer.insert(full_key, setting);
+ }
+
+ Ok(())
+}
+
+pub fn language_id(language: &str) -> bool {
+ language.starts_with(|character: char| character.is_ascii_lowercase())
+ && language
+ .bytes()
+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
+}
+
+fn parse_config(source: &[u8], origin: String) -> Result<Config, String> {
+ let parsed = jpcl::parse_bytes(source, &ParseOptions::default())
+ .map_err(|error| error.with_filename(origin.clone()).to_string())?;
+ let mut config = Config {
+ base: Layer::new(),
+ overrides: BTreeMap::new(),
+ origin,
+ };
+
+ for (section, value) in parsed.iter() {
+ if section != "overrides" {
+ parse_section(&mut config.base, section, value, &config.origin)?;
+ continue;
+ }
+
+ let path = format!("{}.overrides", config.origin);
+
+ for (language, values) in object(value, &path)?.iter() {
+ let label = format!("{path}.{language}");
+
+ if !language_id(language) {
+ return Err(format!("{label} must use a lowercase language identifier"));
+ }
+
+ let mut layer = Layer::new();
+
+ for (section, value) in object(values, &label)?.iter() {
+ parse_section(&mut layer, section, value, &label)?;
+ }
+
+ config.overrides.insert(language.to_owned(), layer);
+ }
+ }
+
+ Ok(config)
+}
+
+fn load(path: &Path) -> Result<Option<Config>, String> {
+ match fs::read(path) {
+ Ok(source) => parse_config(&source, path.display().to_string()).map(Some),
+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
+ Err(error) => Err(format!("{}: {error}", path.display())),
+ }
+}
+
+#[derive(Default)]
+pub struct Effective {
+ values: Layer,
+ origins: BTreeMap<&'static str, String>,
+}
+
+impl Effective {
+ fn apply(&mut self, layer: &Layer, origin: &str) {
+ for (&key, &setting) in layer {
+ self.values.insert(key, setting);
+ self.origins.insert(key, origin.to_owned());
+ }
+ }
+
+ pub fn indent_size(&self) -> usize {
+ self.size(INDENT)
+ }
+
+ pub fn newline_size(&self) -> usize {
+ self.size(NEWLINE)
+ }
+
+ pub fn file_path_header(&self) -> bool {
+ matches!(self.values[FILE_HEADER], Setting::Toggle(true))
+ }
+
+ fn size(&self, key: &str) -> usize {
+ match self.values[key] {
+ Setting::Size(value) => value,
+ _ => unreachable!("validated numeric setting"),
+ }
+ }
+
+ pub fn convention(&self, key: &str) -> Case {
+ match self.values[key] {
+ Setting::Case(value) => value,
+ _ => unreachable!("validated naming setting"),
+ }
+ }
+
+ pub fn theme(&self) -> Theme {
+ match self.values[THEME] {
+ Setting::Theme(theme) => theme,
+ _ => unreachable!("validated terminal theme"),
+ }
+ }
+
+ 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 struct ConfigStore {
+ defaults: Config,
+ global: Option<Config>,
+ locations: HashMap<PathBuf, Option<PathBuf>>,
+ projects: HashMap<PathBuf, Option<Config>>,
+ effective: HashMap<(Option<PathBuf>, Option<String>), Effective>,
+}
+
+impl ConfigStore {
+ pub fn load(home: Option<&Path>) -> Result<Self, String> {
+ Ok(Self {
+ defaults: parse_config(DEFAULT_SOURCE.as_bytes(), "built-in defaults".into())?,
+ global: match home {
+ Some(home) => load(&home.join(".c4d/config.jp"))?,
+ None => None,
+ },
+ locations: HashMap::new(),
+ projects: HashMap::new(),
+ effective: HashMap::new(),
+ })
+ }
+
+ pub fn project(&mut self, directory: &Path) -> Result<Option<PathBuf>, String> {
+ let mut visited = Vec::new();
+ let mut root = None;
+
+ for candidate in directory.ancestors() {
+ if let Some(cached) = self.locations.get(candidate) {
+ root.clone_from(cached);
+ break;
+ }
+
+ visited.push(candidate.to_owned());
+ let config = load(&candidate.join(".c4d/config.jp"))?;
+
+ if config.is_some() || candidate.join(".git").symlink_metadata().is_ok() {
+ root = Some(candidate.to_owned());
+ self.projects.insert(candidate.to_owned(), config);
+ break;
+ }
+ }
+
+ for candidate in visited {
+ self.locations.insert(candidate, root.clone());
+ }
+
+ Ok(root)
+ }
+
+ pub fn settings(&mut self, root: Option<&Path>, language: Option<&str>) -> &Effective {
+ self.effective
+ .entry((root.map(Path::to_owned), language.map(str::to_owned)))
+ .or_insert_with(|| {
+ let mut effective = Effective::default();
+ let project = root
+ .and_then(|root| self.projects.get(root))
+ .and_then(Option::as_ref);
+
+ for config in [Some(&self.defaults), self.global.as_ref(), project]
+ .into_iter()
+ .flatten()
+ {
+ effective.apply(&config.base, &config.origin);
+
+ if let Some(layer) = language.and_then(|id| config.overrides.get(id)) {
+ effective.apply(
+ layer,
+ &format!("{} [overrides.{}]", config.origin, language.unwrap()),
+ );
+ }
+ }
+
+ effective
+ })
+ }
+
+ pub fn override_languages(&self, root: Option<&Path>) -> BTreeSet<String> {
+ let project = root
+ .and_then(|root| self.projects.get(root))
+ .and_then(Option::as_ref);
+ [self.global.as_ref(), project]
+ .into_iter()
+ .flatten()
+ .flat_map(|config| config.overrides.keys().cloned())
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn official_jpcl_parses_default_and_uncommented_example() {
+ let store = ConfigStore::load(None).unwrap();
+ assert!(store.defaults.overrides.is_empty());
+
+ let example = DEFAULT_SOURCE.replace("~*\n[overrides]", "[overrides]");
+ let example = example.trim_end().strip_suffix("*~").unwrap();
+ let config = parse_config(example.as_bytes(), "example.jp".into()).unwrap();
+ assert!(config.overrides.contains_key("typescript"));
+ }
+
+ #[test]
+ fn naming_cases_distinguish_valid_and_invalid_identifiers() {
+ for (case, valid, invalid) in [
+ (Case::Flat, "acoolfunction", "aCoolFunction"),
+ (Case::Camel, "aCoolFunction", "ACoolFunction"),
+ (Case::Pascal, "ACoolFunction", "aCoolFunction"),
+ (Case::Snake, "a_cool_function", "a__cool_function"),
+ (Case::ScreamingSnake, "A_COOL_FUNCTION", "a_COOL_FUNCTION"),
+ (Case::Disabled, "_any_Name", ""),
+ ] {
+ assert!(case.matches(valid));
+
+ if case != Case::Disabled {
+ assert!(!case.matches(invalid));
+ }
+ }
+ }
+}
diff --git a/src/discovery.rs b/src/discovery.rs
new file mode 100644
index 0000000..02db8d6
--- /dev/null
+++ b/src/discovery.rs
@@ -0,0 +1,399 @@
+// src/discovery.rs
+
+use std::collections::{HashMap, HashSet};
+use std::fs;
+use std::io::ErrorKind;
+use std::path::{Component, Path, PathBuf};
+use std::sync::Arc;
+
+use regex::Regex;
+
+use crate::language;
+
+const EXCLUDED: &[&str] = &[
+ ".git",
+ ".c4d",
+ ".cache",
+ ".deno",
+ ".next",
+ ".nuxt",
+ ".output",
+ ".svelte-kit",
+ ".turbo",
+ ".wrangler",
+ "bower_components",
+ "build",
+ "coverage",
+ "dist",
+ "node_modules",
+ "out",
+ "target",
+ "vendor",
+];
+
+fn excluded(path: &Path) -> bool {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| EXCLUDED.contains(&name))
+}
+
+pub fn generated_name(path: &Path) -> bool {
+ let name = path
+ .file_stem()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_ascii_lowercase();
+ [".generated", ".gen", ".min"]
+ .iter()
+ .any(|suffix| name.ends_with(suffix))
+}
+
+struct Pattern {
+ regex: Regex,
+ ignored: bool,
+ directories_only: bool,
+}
+
+fn trim_pattern(mut line: &str) -> &str {
+ while let Some(before) = line.strip_suffix(' ') {
+ let escapes = before
+ .bytes()
+ .rev()
+ .take_while(|&byte| byte == b'\\')
+ .count();
+
+ if escapes % 2 == 1 {
+ break;
+ }
+
+ line = before;
+ }
+
+ line
+}
+
+impl Pattern {
+ fn parse(line: &str) -> Result<Option<Self>, regex::Error> {
+ let line = trim_pattern(line);
+
+ if line.is_empty() || line.starts_with('#') {
+ return Ok(None);
+ }
+
+ let (ignored, pattern) = line
+ .strip_prefix('!')
+ .map_or((true, line), |rest| (false, rest));
+ let (directories_only, pattern) = pattern
+ .strip_suffix('/')
+ .map_or((false, pattern), |rest| (true, rest));
+ let anchored = pattern.contains('/');
+ let pattern = pattern.strip_prefix('/').unwrap_or(pattern);
+
+ if pattern.is_empty() {
+ return Ok(None);
+ }
+
+ let mut expression = String::from(if anchored { "^" } else { "(?:^|/)" });
+ let mut characters = pattern.char_indices().peekable();
+
+ while let Some((offset, character)) = characters.next() {
+ match character {
+ '\\' => {
+ let escaped = characters.next().map_or('\\', |(_, escaped)| escaped);
+ expression.push_str(®ex::escape(&escaped.to_string()));
+ }
+ '?' => expression.push_str("[^/]"),
+ '*' => {
+ let mut count = 1;
+
+ while matches!(characters.peek(), Some((_, '*'))) {
+ characters.next();
+ count += 1;
+ }
+
+ let boundary = offset == 0 || pattern.as_bytes()[offset - 1] == b'/';
+
+ match characters.peek() {
+ Some((_, '/')) if count == 2 && boundary => {
+ characters.next();
+ expression.push_str("(?s:.*/)?");
+ }
+ None if count == 2 && boundary => expression.push_str("(?s:.*)"),
+ _ => expression.push_str("[^/]*"),
+ }
+ }
+ '[' => {
+ let interior = &pattern[offset + 1..];
+
+ if let Some(end) = interior.find(']').filter(|&end| end > 0) {
+ let class = &interior[..end];
+
+ for _ in 0..=class.chars().count() {
+ characters.next();
+ }
+
+ expression.push_str("[[^/]&&[");
+
+ if let Some(negative) = class.strip_prefix('!') {
+ expression.push('^');
+ expression.push_str(negative);
+ } else {
+ if class.starts_with('^') {
+ expression.push('\\');
+ }
+
+ expression.push_str(class);
+ }
+
+ expression.push_str("]]");
+ } else {
+ expression.push_str("\\[");
+ }
+ }
+ _ => expression.push_str(®ex::escape(&character.to_string())),
+ }
+ }
+
+ expression.push('$');
+
+ Ok(Some(Self {
+ regex: Regex::new(&expression)?,
+ ignored,
+ directories_only,
+ }))
+ }
+}
+
+struct IgnoreRules {
+ directory: PathBuf,
+ patterns: Vec<Pattern>,
+}
+
+pub struct Discovery {
+ working_directory: PathBuf,
+ rules: HashMap<PathBuf, Arc<IgnoreRules>>,
+ visited: HashSet<PathBuf>,
+}
+
+impl Discovery {
+ pub fn new(working_directory: PathBuf) -> Self {
+ Self {
+ working_directory,
+ rules: HashMap::new(),
+ visited: HashSet::new(),
+ }
+ }
+
+ pub fn explicit(&self, input: &Path) -> Result<Option<PathBuf>, String> {
+ let absolute = self.working_directory.join(input);
+ let mut current = PathBuf::new();
+
+ for part in absolute.components() {
+ match part {
+ Component::ParentDir => {
+ current.pop();
+ }
+ Component::Normal(_) => {
+ current.push(part);
+ let metadata = current
+ .symlink_metadata()
+ .map_err(|error| format!("{}: {error}", current.display()))?;
+
+ if metadata.file_type().is_symlink()
+ || (metadata.is_dir() && excluded(¤t))
+ {
+ eprintln!(
+ "{}: skipped (symbolic link or excluded directory)",
+ input.display()
+ );
+ return Ok(None);
+ }
+ }
+ _ => current.push(part),
+ }
+ }
+
+ Ok(Some(current))
+ }
+
+ fn extend(
+ &mut self,
+ directory: &Path,
+ layers: &mut Vec<Arc<IgnoreRules>>,
+ ) -> Result<(), String> {
+ if let Some(cached) = self.rules.get(directory) {
+ if !cached.patterns.is_empty() {
+ layers.push(Arc::clone(cached));
+ }
+
+ return Ok(());
+ }
+
+ let mut patterns = Vec::new();
+
+ for name in [".gitignore", ".c4dignore"] {
+ let path = directory.join(name);
+ let source = match fs::read_to_string(&path) {
+ Ok(source) => source,
+ Err(error) if error.kind() == ErrorKind::NotFound => continue,
+ Err(error) => return Err(format!("{}: {error}", path.display())),
+ };
+
+ for (index, line) in source.lines().enumerate() {
+ let pattern = Pattern::parse(line).map_err(|error| {
+ format!(
+ "{}:{}: invalid ignore pattern: {error}",
+ path.display(),
+ index + 1
+ )
+ })?;
+ patterns.extend(pattern);
+ }
+ }
+
+ let rules = Arc::new(IgnoreRules {
+ directory: directory.to_owned(),
+ patterns,
+ });
+
+ if !rules.patterns.is_empty() {
+ layers.push(Arc::clone(&rules));
+ }
+
+ self.rules.insert(directory.to_owned(), rules);
+ Ok(())
+ }
+
+ fn ignored(path: &Path, directory: bool, layers: &[Arc<IgnoreRules>]) -> bool {
+ for layer in layers.iter().rev() {
+ let Ok(relative) = path.strip_prefix(&layer.directory) else {
+ continue;
+ };
+ let relative = relative
+ .iter()
+ .map(|part| part.to_string_lossy())
+ .collect::<Vec<_>>()
+ .join("/");
+
+ for pattern in layer.patterns.iter().rev() {
+ if (!pattern.directories_only || directory) && pattern.regex.is_match(&relative) {
+ return pattern.ignored;
+ }
+ }
+ }
+
+ false
+ }
+
+ pub fn scan(
+ &mut self,
+ path: &Path,
+ project: Option<&Path>,
+ mut process: impl FnMut(&Path),
+ ) -> Result<(), String> {
+ let entry = path
+ .symlink_metadata()
+ .map_err(|error| format!("{}: {error}", path.display()))?;
+ let directory = if entry.is_dir() {
+ path
+ } else {
+ path.parent().unwrap_or(path)
+ };
+ let mut boundary = project.unwrap_or(directory);
+
+ if boundary.starts_with(&self.working_directory)
+ && directory.starts_with(&self.working_directory)
+ {
+ boundary = &self.working_directory;
+ }
+
+ if let Some(git_root) = directory
+ .ancestors()
+ .find(|candidate| candidate.join(".git").symlink_metadata().is_ok())
+ {
+ boundary = git_root;
+ }
+
+ let mut layers = Vec::new();
+ let mut ancestors: Vec<_> = path
+ .ancestors()
+ .skip(1)
+ .take_while(|ancestor| ancestor.starts_with(boundary))
+ .collect();
+
+ while let Some(ancestor) = ancestors.pop() {
+ if Self::ignored(ancestor, true, &layers) {
+ eprintln!("{}: skipped (ignored by project rules)", path.display());
+ return Ok(());
+ }
+
+ self.extend(ancestor, &mut layers)?;
+ }
+
+ self.walk(path, &mut layers, true, &mut process)
+ }
+
+ fn walk(
+ &mut self,
+ path: &Path,
+ layers: &mut Vec<Arc<IgnoreRules>>,
+ explicit: bool,
+ process: &mut impl FnMut(&Path),
+ ) -> Result<(), String> {
+ let entry = path
+ .symlink_metadata()
+ .map_err(|error| format!("{}: {error}", path.display()))?;
+
+ if entry.file_type().is_symlink() || (entry.is_dir() && excluded(path)) {
+ return Ok(());
+ }
+
+ if Self::ignored(path, entry.is_dir(), layers) {
+ if explicit {
+ eprintln!("{}: skipped (ignored by project rules)", path.display());
+ }
+
+ return Ok(());
+ }
+
+ if entry.is_dir() {
+ if !self.visited.insert(path.to_owned()) {
+ return Ok(());
+ }
+
+ let mut children = fs::read_dir(path)
+ .and_then(|entries| entries.collect::<Result<Vec<_>, _>>())
+ .map_err(|error| format!("{}: {error}", path.display()))?;
+ children.sort_unstable_by_key(|child| child.file_name());
+
+ let inherited = layers.len();
+ self.extend(path, layers)?;
+
+ for child in children {
+ let child_path = child.path();
+ let kind = child
+ .file_type()
+ .map_err(|error| format!("{}: {error}", child_path.display()))?;
+
+ if (kind.is_dir() && !excluded(&child_path))
+ || (kind.is_file() && language::detect(&child_path).is_some())
+ {
+ self.walk(&child_path, layers, false, process)?;
+ }
+ }
+
+ layers.truncate(inherited);
+ } else if !entry.is_file() || language::detect(path).is_none() || generated_name(path) {
+ if explicit {
+ eprintln!(
+ "{}: skipped (unsupported or generated file)",
+ path.display()
+ );
+ }
+ } else if self.visited.insert(path.to_owned()) {
+ process(path);
+ }
+
+ Ok(())
+ }
+}
diff --git a/src/language.rs b/src/language.rs
new file mode 100644
index 0000000..b3eb8aa
--- /dev/null
+++ b/src/language.rs
@@ -0,0 +1,43 @@
+// src/language.rs
+
+use std::borrow::Cow;
+use std::path::Path;
+
+use crate::config::Effective;
+
+pub struct Diagnostic {
+ pub offset: usize,
+ pub rule: &'static str,
+ pub message: String,
+}
+
+pub struct Analysis<'source> {
+ pub formatted: Cow<'source, str>,
+ pub issues: Vec<Diagnostic>,
+}
+
+pub struct Language {
+ pub id: &'static str,
+ pub extension: &'static str,
+ pub generated_header: fn(&str, &str) -> bool,
+ pub analyze: for<'source> fn(
+ &'source str,
+ &str,
+ &Effective,
+ bool,
+ ) -> Result<Analysis<'source>, Diagnostic>,
+}
+
+pub static LANGUAGES: &[Language] = &[Language {
+ id: "rust",
+ extension: "rs",
+ generated_header: crate::rust_source::generated_header,
+ analyze: crate::rust_source::analyze,
+ }];
+
+pub fn detect(path: &Path) -> Option<&'static Language> {
+ let extension = path.extension()?.to_str()?;
+ LANGUAGES
+ .iter()
+ .find(|language| extension.eq_ignore_ascii_case(language.extension))
+}
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..a2c3169
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,375 @@
+// src/main.rs
+
+mod config;
+
+mod discovery;
+
+mod language;
+
+mod rust_source;
+
+mod terminal;
+
+use std::env;
+use std::ffi::{OsStr, OsString};
+use std::fs;
+use std::io::{self, IsTerminal, Write};
+use std::path::Path;
+use std::process::ExitCode;
+
+use serde_json::{Map, json};
+use tempfile::NamedTempFile;
+
+use crate::config::ConfigStore;
+use crate::discovery::Discovery;
+use crate::language::Diagnostic;
+use crate::terminal::{Terminal, Tone};
+
+const USAGE: &str = "Usage:
+ c4d check [PATH ...]
+ c4d format [PATH ...]
+ c4d format --check [PATH ...]
+ c4d config show [PATH] [--language LANGUAGE]
+ c4d version";
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Mode {
+ Check,
+ DryRun,
+ Write,
+}
+
+fn report(path: &Path, source: &str, issues: &[Diagnostic], terminal: &Terminal) {
+ let mut line = 1;
+ let mut line_start = 0;
+ let mut breaks = source.match_indices('\n').peekable();
+
+ for issue in issues {
+ while let Some(&(offset, _)) = breaks.peek() {
+ if offset >= issue.offset {
+ break;
+ }
+
+ breaks.next();
+ line += 1;
+ line_start = offset + 1;
+ }
+
+ let column = source[line_start..issue.offset].chars().count() + 1;
+ let tone = if issue.rule == "syntax" { Tone::Error } else { Tone::Notice };
+ let rule = terminal.paint(tone, issue.rule);
+ println!(
+ "{}:{line}:{column} {} — {}",
+ path.display(),
+ rule,
+ issue.message,
+ );
+ }
+}
+
+fn replace_source(path: &Path, original: &str, formatted: &str) -> io::Result<()> {
+ let initial = path.symlink_metadata()?;
+
+ if !initial.is_file() {
+ return Err(io::Error::other("source is no longer a regular file"));
+ }
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+
+ if initial.nlink() > 1 {
+ return Err(io::Error::other("source has multiple hard links"));
+ }
+ }
+
+ let directory = path.parent().expect("absolute file path");
+ let mut temporary = NamedTempFile::new_in(directory)?;
+ temporary.write_all(formatted.as_bytes())?;
+ temporary.as_file().set_permissions(initial.permissions())?;
+ temporary.as_file().sync_all()?;
+
+ let current = path.symlink_metadata()?;
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+
+ if (current.dev(), current.ino(), current.nlink())
+ != (initial.dev(), initial.ino(), initial.nlink())
+ {
+ return Err(io::Error::other("source changed during formatting"));
+ }
+ }
+
+ if !current.is_file()
+ || current.permissions() != initial.permissions()
+ || fs::read(path)? != original.as_bytes()
+ {
+ return Err(io::Error::other("source changed during formatting"));
+ }
+
+ temporary.persist(path)?;
+ Ok(())
+}
+
+fn inspect(
+ path: &Path,
+ shown: &Path,
+ cwd: &Path,
+ config: &mut ConfigStore,
+ mode: Mode,
+) -> Result<Option<(u8, Terminal)>, String> {
+ let language = language::detect(path).expect("discovered language");
+ let bytes = fs::read(path).map_err(|error| error.to_string())?;
+ let source = match std::str::from_utf8(&bytes) {
+ Ok(source) if !bytes.contains(&0) => source,
+ _ => {
+ eprintln!("{}: skipped (binary or non-UTF-8 file)", shown.display());
+ return Ok(None);
+ }
+ };
+
+ let project = config.project(path.parent().expect("absolute file path"))?;
+ let relative_path = project
+ .as_deref()
+ .and_then(|root| path.strip_prefix(root).ok())
+ .or_else(|| path.strip_prefix(cwd).ok())
+ .unwrap_or_else(|| Path::new(path.file_name().expect("discovered filename")));
+ let header_path = relative_path
+ .iter()
+ .map(|part| {
+ part.to_string_lossy()
+ .replace('\\', "\\\\")
+ .replace('\r', "\\r")
+ .replace('\n', "\\n")
+ })
+ .collect::<Vec<_>>()
+ .join("/");
+
+ if (language.generated_header)(source, &header_path) {
+ eprintln!("{}: skipped (generated header)", shown.display());
+ return Ok(None);
+ }
+
+ let settings = config.settings(project.as_deref(), Some(language.id));
+ let terminal = settings.theme().stdout();
+ let analysis = match (language.analyze)(source, &header_path, settings, mode == Mode::Check) {
+ Ok(result) => result,
+ Err(issue) => {
+ report(shown, source, &[issue], &terminal);
+ return Ok(Some((2, terminal)));
+ }
+ };
+
+ let status = match mode {
+ Mode::Check if !analysis.issues.is_empty() => {
+ report(shown, source, &analysis.issues, &terminal);
+ 1
+ }
+ Mode::DryRun if analysis.formatted != source => {
+ 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"));
+ 0
+ }
+ _ => 0,
+ };
+ Ok(Some((status, terminal)))
+}
+
+fn show_config(
+ arguments: &[OsString],
+ config: &mut ConfigStore,
+ discovery: &Discovery,
+) -> Result<u8, String> {
+ let mut iter = arguments.iter();
+ let mut language = None;
+ let mut input = None;
+
+ while let Some(argument) = iter.next() {
+ if argument == "--language" && language.is_none() {
+ language = iter.next().and_then(|value| value.to_str());
+
+ if !language.is_some_and(config::language_id) {
+ return Err("expected a lowercase language identifier after --language".into());
+ }
+ } else if !argument.to_string_lossy().starts_with('-') && input.is_none() {
+ input = Some(Path::new(argument));
+ } else {
+ return Err(format!(
+ "unexpected argument {}",
+ argument.to_string_lossy()
+ ));
+ }
+ }
+
+ let Some(path) = discovery.explicit(input.unwrap_or(Path::new(".")))? else {
+ return Ok(2);
+ };
+ let directory = if path.is_dir() {
+ &path
+ } else {
+ path.parent().unwrap_or(&path)
+ };
+ let project = config.project(directory)?;
+ let root = project.as_deref();
+
+ let output = if let Some(language) = language {
+ config.settings(root, Some(language)).json()
+ } else {
+ 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())?
+ );
+ Ok(0)
+}
+
+fn run(arguments: Vec<OsString>) -> Result<u8, String> {
+ let command = arguments.first().and_then(|arg| arg.to_str());
+
+ if matches!(command, Some("-h" | "--help")) {
+ println!("{USAGE}");
+ return Ok(0);
+ }
+
+ if matches!(command, Some("version" | "-V" | "--version")) {
+ println!("c4d {}", env!("CARGO_PKG_VERSION"));
+ return Ok(0);
+ }
+
+ let working_directory = env::current_dir().map_err(|error| error.to_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);
+ }
+
+ let mut mode = match command {
+ Some("check") => Mode::Check,
+ Some("format") => Mode::Write,
+ _ => return Err(USAGE.into()),
+ };
+ let mut positional_only = false;
+ let mut inputs = Vec::new();
+
+ for argument in &arguments[1..] {
+ if !positional_only && argument == "--" {
+ positional_only = true;
+ } else if !positional_only && argument == "--check" && mode == Mode::Write {
+ mode = Mode::DryRun;
+ } else if !positional_only && argument.to_string_lossy().starts_with('-') {
+ return Err(format!(
+ "unexpected argument {}",
+ argument.to_string_lossy()
+ ));
+ } else {
+ inputs.push(argument.as_os_str());
+ }
+ }
+
+ if inputs.is_empty() {
+ inputs.push(OsStr::new("."));
+ }
+
+ let mut config = ConfigStore::load(env::home_dir().as_deref())?;
+ let mut status = 0;
+ let mut scanned = 0;
+ let mut summary_terminal = None;
+
+ for input in inputs {
+ let path = match discovery.explicit(Path::new(input)) {
+ Ok(Some(path)) => path,
+ Ok(None) => continue,
+ Err(error) => {
+ eprintln!("{error}");
+ status = 2;
+ continue;
+ }
+ };
+ let directory = if path.is_dir() {
+ &path
+ } else {
+ path.parent().unwrap_or(&path)
+ };
+ // The nearest config is still resolved per file to support nested projects.
+ let project = match config.project(directory) {
+ Ok(project) => project,
+ Err(error) => {
+ eprintln!("{error}");
+ status = 2;
+ continue;
+ }
+ };
+ let result = discovery.scan(&path, project.as_deref(), |path| {
+ let shown = path.strip_prefix(&working_directory).unwrap_or(path);
+
+ match inspect(path, shown, &working_directory, &mut config, mode) {
+ Ok(Some((result, terminal))) => {
+ status = status.max(result);
+ scanned += 1;
+ summary_terminal.get_or_insert(terminal);
+ }
+ Ok(None) => {}
+ Err(error) => {
+ eprintln!("{}: {error}", shown.display());
+ status = 2;
+ }
+ }
+ });
+
+ if let Err(error) = result {
+ eprintln!("{error}");
+ status = 2;
+ }
+ }
+
+ if status == 0 && io::stdout().is_terminal() {
+ if let Some(terminal) = summary_terminal {
+ let label = match mode {
+ Mode::Check => "No issues found",
+ Mode::DryRun => "Formatting is up to date",
+ Mode::Write => "Formatting complete",
+ };
+ let noun = if scanned == 1 { "file" } else { "files" };
+ println!("{} ({scanned} {noun} checked).", terminal.paint(Tone::Success, label));
+ } else {
+ println!("No supported source files to check.");
+ }
+ }
+
+ Ok(status)
+}
+
+fn main() -> ExitCode {
+ match run(env::args_os().skip(1).collect()) {
+ Ok(status) => ExitCode::from(status),
+ Err(error) => {
+ eprintln!("{error}");
+ ExitCode::from(2)
+ }
+ }
+}
diff --git a/src/rust_source.rs b/src/rust_source.rs
new file mode 100644
index 0000000..72564dd
--- /dev/null
+++ b/src/rust_source.rs
@@ -0,0 +1,495 @@
+// src/rust_source.rs
+
+use std::borrow::Cow;
+use std::ops::Range;
+
+use proc_macro2::{Delimiter, Span, TokenStream, TokenTree};
+use syn::spanned::Spanned;
+use syn::visit::{self, Visit};
+
+use crate::config::{CLASSES, Case, Effective, FILE_HEADER, FUNCTIONS, VARIABLES};
+use crate::language::{Analysis, Diagnostic};
+
+struct Edit {
+ range: Range<usize>,
+ replacement: String,
+ issue: Diagnostic,
+}
+
+struct Rules<'source, 'settings> {
+ source: &'source str,
+ line_starts: Vec<usize>,
+ settings: &'settings Effective,
+ naming: bool,
+ newline_size: usize,
+ protected: Vec<Range<usize>>,
+ edits: Vec<Edit>,
+ issues: Vec<Diagnostic>,
+}
+
+fn block_item(item: &syn::Item) -> bool {
+ matches!(
+ item,
+ syn::Item::Fn(_)
+ | syn::Item::Struct(_)
+ | syn::Item::Enum(_)
+ | syn::Item::Union(_)
+ | syn::Item::Impl(_)
+ | syn::Item::Trait(_)
+ | syn::Item::Mod(_)
+ | syn::Item::ForeignMod(_)
+ )
+}
+
+fn block_statement(statement: &syn::Stmt) -> bool {
+ match statement {
+ syn::Stmt::Item(item) => block_item(item),
+ syn::Stmt::Expr(expression, _) => matches!(
+ expression,
+ syn::Expr::If(_)
+ | syn::Expr::ForLoop(_)
+ | syn::Expr::While(_)
+ | syn::Expr::Loop(_)
+ | syn::Expr::Match(_)
+ | syn::Expr::Block(_)
+ | syn::Expr::Unsafe(_)
+ ),
+ _ => false,
+ }
+}
+
+impl Rules<'_, '_> {
+ fn line(&self, offset: usize) -> usize {
+ self.line_starts.partition_point(|start| *start <= offset) - 1
+ }
+
+ fn name(&mut self, ident: &syn::Ident, rule: &'static str) {
+ let convention = self.settings.convention(rule);
+ if !self.naming || convention == Case::Disabled {
+ return;
+ }
+
+ let spelling = ident.to_string();
+ let name = spelling.strip_prefix("r#").unwrap_or(&spelling);
+ if !convention.matches(name) {
+ self.issues.push(Diagnostic {
+ offset: ident.span().byte_range().start,
+ rule,
+ message: format!("“{spelling}” should use {}", convention.label()),
+ });
+ }
+ }
+
+ fn gap(&mut self, left: Span, right: Span) {
+ if self.newline_size == 0 {
+ return;
+ }
+ let start = left.byte_range().end;
+ let end = self.line_starts[self.line(right.byte_range().start)];
+ if end <= start {
+ return;
+ }
+
+ let gap = &self.source[start..end];
+ if !gap
+ .bytes()
+ .all(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
+ {
+ return;
+ }
+ let newlines = gap.bytes().filter(|&byte| byte == b'\n').count();
+ if newlines == 0 || newlines == self.newline_size {
+ return;
+ }
+
+ let first_break = gap.find('\n').expect("counted a newline");
+ let ending = if gap[..first_break].ends_with('\r') {
+ "\r\n"
+ } else {
+ "\n"
+ };
+ self.edits.push(Edit {
+ range: start..end,
+ replacement: ending.repeat(self.newline_size),
+ issue: Diagnostic {
+ offset: start,
+ rule: "formatting.newLineSize",
+ message: format!(
+ "Expected {} newline character(s) between logical blocks",
+ self.newline_size
+ ),
+ },
+ });
+ }
+
+ fn item_gaps(&mut self, items: &[syn::Item]) {
+ for pair in items.windows(2) {
+ if block_item(&pair[0]) || block_item(&pair[1]) {
+ self.gap(pair[0].span(), pair[1].span());
+ }
+ }
+ }
+
+ fn indent(&mut self, offset: usize, depth: usize) {
+ let start = self.line_starts[self.line(offset)];
+ let index = self.protected.partition_point(|range| range.end <= start);
+ if self
+ .protected
+ .get(index)
+ .is_some_and(|range| range.start < offset)
+ {
+ return;
+ }
+ let prefix = &self.source[start..offset];
+ let width = depth * self.settings.indent_size();
+ if (prefix.len() == width && prefix.bytes().all(|byte| byte == b' '))
+ || !prefix.bytes().all(|byte| matches!(byte, b' ' | b'\t'))
+ {
+ return;
+ }
+
+ self.edits.push(Edit {
+ range: start..offset,
+ replacement: " ".repeat(width),
+ issue: Diagnostic {
+ offset: start,
+ rule: "formatting.indentSize",
+ message: format!("Expected {width} space(s) of indentation"),
+ },
+ });
+ }
+
+ fn indent_tokens(&mut self, stream: TokenStream, depth: usize, opening: Option<usize>) {
+ for token in stream {
+ if let TokenTree::Group(group) = token {
+ let first = group.span_open().byte_range().start;
+ let last = group.span_close().byte_range().start;
+ let delimiters = match group.delimiter() {
+ Delimiter::Brace => (b'{', b'}'),
+ Delimiter::Bracket => (b'[', b']'),
+ Delimiter::Parenthesis => (b'(', b')'),
+ Delimiter::None => continue,
+ };
+
+ // Doc comments produce synthetic bracket groups at the comment's span.
+ if self.source.as_bytes().get(first) != Some(&delimiters.0)
+ || self.source.as_bytes().get(last) != Some(&delimiters.1)
+ {
+ continue;
+ }
+
+ self.indent(first, depth);
+ let line = self.line(first);
+ let nested = usize::from(opening != Some(line) && line != self.line(last));
+ self.indent_tokens(
+ group.stream(),
+ depth + nested,
+ (nested != 0).then_some(line).or(opening),
+ );
+ self.indent(last, depth);
+ } else {
+ let offset = token.span().byte_range().start;
+ if !self.source[offset..].starts_with("//")
+ && !self.source[offset..].starts_with("/*")
+ {
+ self.indent(offset, depth);
+ }
+ }
+ }
+ }
+}
+
+impl<'ast> Visit<'ast> for Rules<'_, '_> {
+ fn visit_file(&mut self, node: &'ast syn::File) {
+ self.item_gaps(&node.items);
+ visit::visit_file(self, node);
+ }
+
+ fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
+ if let Some((_, items)) = &node.content {
+ self.item_gaps(items);
+ }
+ visit::visit_item_mod(self, node);
+ }
+
+ fn visit_block(&mut self, node: &'ast syn::Block) {
+ for pair in node.stmts.windows(2) {
+ if block_statement(&pair[0]) || block_statement(&pair[1]) {
+ self.gap(pair[0].span(), pair[1].span());
+ }
+ }
+ visit::visit_block(self, node);
+ }
+
+ fn visit_macro(&mut self, node: &'ast syn::Macro) {
+ self.protected.push(node.span().byte_range());
+ }
+
+ fn visit_attribute(&mut self, node: &'ast syn::Attribute) {
+ self.protected.push(node.span().byte_range());
+ }
+
+ fn visit_signature(&mut self, node: &'ast syn::Signature) {
+ self.name(&node.ident, FUNCTIONS);
+ visit::visit_signature(self, node);
+ }
+
+ fn visit_pat_ident(&mut self, node: &'ast syn::PatIdent) {
+ self.name(&node.ident, VARIABLES);
+ visit::visit_pat_ident(self, node);
+ }
+
+ fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
+ self.name(&node.ident, VARIABLES);
+ visit::visit_item_const(self, node);
+ }
+
+ fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
+ self.name(&node.ident, VARIABLES);
+ visit::visit_item_static(self, node);
+ }
+
+ fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
+ self.name(&node.ident, CLASSES);
+ visit::visit_item_struct(self, node);
+ }
+
+ fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
+ self.name(&node.ident, CLASSES);
+ visit::visit_item_enum(self, node);
+ }
+
+ fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
+ self.name(&node.ident, CLASSES);
+ visit::visit_item_union(self, node);
+ }
+
+ fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
+ self.name(&node.ident, CLASSES);
+ visit::visit_item_trait(self, node);
+ }
+}
+
+fn comment(source: &str) -> Option<(&str, &str)> {
+ if source.starts_with("//") {
+ let end = source.find('\n').unwrap_or(source.len());
+ return Some(source.split_at(end));
+ }
+ if !source.starts_with("/*") {
+ return None;
+ }
+
+ let mut depth = 1;
+ let mut offset = 2;
+ let bytes = source.as_bytes();
+ while offset + 1 < bytes.len() {
+ match &bytes[offset..offset + 2] {
+ b"/*" => {
+ depth += 1;
+ offset += 2;
+ }
+ b"*/" => {
+ depth -= 1;
+ offset += 2;
+ if depth == 0 {
+ return Some(source.split_at(offset));
+ }
+ }
+ _ => offset += 1,
+ }
+ }
+ None
+}
+
+fn code_after_header(source: &str) -> &str {
+ let code = source.strip_prefix('\u{feff}').unwrap_or(source);
+ let Some(mut tail) = code.strip_prefix("#!") else {
+ return code;
+ };
+
+ loop {
+ tail = tail.trim_start();
+ if tail.starts_with('[') {
+ return code;
+ }
+ if let Some((_, rest)) = comment(tail) {
+ tail = rest;
+ } else {
+ return code
+ .split_once('\n')
+ .map_or(&code[code.len()..], |(_, rest)| rest);
+ }
+ }
+}
+
+pub fn generated_header(source: &str, path: &str) -> bool {
+ let mut remaining = code_after_header(source);
+
+ while let Some((text, tail)) = comment(remaining.trim_start()) {
+ if is_path_comment(text, path) {
+ remaining = tail;
+ continue;
+ }
+ let lowercase = text.to_ascii_lowercase();
+ if [
+ "@generated",
+ "auto-generated",
+ "autogenerated",
+ "automatically generated",
+ "do not edit",
+ ]
+ .iter()
+ .any(|marker| lowercase.contains(marker))
+ {
+ return true;
+ }
+ remaining = tail;
+ }
+
+ false
+}
+
+fn is_path_comment(comment: &str, path: &str) -> bool {
+ comment
+ .strip_prefix("// ")
+ .is_some_and(|text| text.trim_end_matches('\r') == path)
+}
+
+fn path_header(code: &str, source: &str, path: &str) -> Option<String> {
+ let mut remaining = code;
+ while let Some((text, tail)) = comment(remaining.trim_start()) {
+ if is_path_comment(text, path) {
+ return None;
+ }
+ remaining = tail;
+ }
+
+ let ending = if source
+ .split_once('\n')
+ .is_some_and(|(line, _)| line.ends_with('\r'))
+ {
+ "\r\n"
+ } else {
+ "\n"
+ };
+ let code_offset = source.len() - code.len();
+ let separation = if code_offset > 0 && !source[..code_offset].ends_with(['\n', '\u{feff}']) {
+ ending
+ } else {
+ ""
+ };
+ Some(format!("{separation}// {path}{ending}"))
+}
+
+fn observes_position(stream: TokenStream) -> bool {
+ let mut tokens = stream.into_iter().peekable();
+ while let Some(token) = tokens.next() {
+ match token {
+ TokenTree::Group(group) if observes_position(group.stream()) => return true,
+ TokenTree::Ident(ident) if ident == "line" || ident == "column" => {
+ if matches!(tokens.peek(), Some(TokenTree::Punct(punct)) if punct.as_char() == '!')
+ {
+ return true;
+ }
+ }
+ _ => {}
+ }
+ }
+ false
+}
+
+pub fn analyze<'source>(
+ source: &'source str,
+ path: &str,
+ settings: &Effective,
+ naming: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+ let code = code_after_header(source);
+ let header = source.len() - code.len();
+ let tokens: TokenStream = code
+ .parse()
+ .map_err(|error: proc_macro2::LexError| Diagnostic {
+ offset: header + error.span().byte_range().start,
+ rule: "syntax",
+ message: error.to_string(),
+ })?;
+ let file = syn::parse2::<syn::File>(tokens.clone()).map_err(|error| Diagnostic {
+ offset: header + error.span().byte_range().start,
+ rule: "syntax",
+ message: error.to_string(),
+ })?;
+
+ let preserve_position = observes_position(tokens.clone());
+ let mut rules = Rules {
+ source: code,
+ line_starts: std::iter::once(0)
+ .chain(code.match_indices('\n').map(|(offset, _)| offset + 1))
+ .collect(),
+ settings,
+ naming,
+ newline_size: if preserve_position {
+ 0
+ } else {
+ settings.newline_size()
+ },
+ protected: Vec::new(),
+ edits: Vec::new(),
+ issues: Vec::new(),
+ };
+
+ rules.visit_file(&file);
+
+ if !preserve_position && settings.indent_size() != 0 {
+ rules
+ .protected
+ .sort_unstable_by_key(|range| (range.start, range.end));
+ // AST traversal collects disjoint macro and attribute ranges.
+ rules.indent_tokens(tokens, 0, None);
+ }
+
+ let file_comment = if settings.file_path_header() && !preserve_position {
+ path_header(code, source, path)
+ } else {
+ None
+ };
+
+ let mut formatted = Cow::Borrowed(source);
+ if file_comment.is_some() || !rules.edits.is_empty() {
+ rules
+ .edits
+ .sort_unstable_by_key(|edit| (edit.range.start, edit.range.end));
+ rules
+ .edits
+ .dedup_by(|left, right| left.range == right.range);
+ let mut output = String::with_capacity(source.len());
+ output.push_str(&source[..header]);
+ if let Some(comment) = file_comment {
+ output.push_str(&comment);
+ rules.issues.push(Diagnostic {
+ offset: 0,
+ rule: FILE_HEADER,
+ message: format!("Expected file path header // {path}"),
+ });
+ }
+
+ let mut last = 0;
+ for edit in rules.edits {
+ debug_assert!(edit.range.start >= last);
+ output.push_str(&code[last..edit.range.start]);
+ output.push_str(&edit.replacement);
+ last = edit.range.end;
+ rules.issues.push(edit.issue);
+ }
+ output.push_str(&code[last..]);
+ formatted = Cow::Owned(output);
+ }
+
+ for issue in &mut rules.issues {
+ issue.offset += header;
+ }
+ rules.issues.sort_by_key(|issue| issue.offset);
+ Ok(Analysis {
+ formatted,
+ issues: rules.issues,
+ })
+}
diff --git a/src/terminal.rs b/src/terminal.rs
new file mode 100644
index 0000000..dad9a94
--- /dev/null
+++ b/src/terminal.rs
@@ -0,0 +1,123 @@
+// src/terminal.rs
+
+use std::env;
+use std::io::{self, IsTerminal};
+
+#[derive(Debug, Clone, Copy)]
+enum Palette {
+ Standard,
+ Pastel,
+ Catppuccin,
+ RedGreen,
+ BlueYellow,
+ Monochrome,
+ Plain,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct Theme {
+ pub name: &'static str,
+ palette: Palette,
+}
+
+const THEMES: &[Theme] = &[
+ Theme::new("default", Palette::Standard),
+ Theme::new("normal", Palette::Standard),
+ Theme::new("pastel", Palette::Pastel),
+ Theme::new("catppuccin", Palette::Catppuccin),
+ Theme::new("protanopia", Palette::RedGreen),
+ Theme::new("protanomaly", Palette::RedGreen),
+ Theme::new("deuteranopia", Palette::RedGreen),
+ Theme::new("deuteranomaly", Palette::RedGreen),
+ Theme::new("tritanopia", Palette::BlueYellow),
+ Theme::new("tritanomaly", Palette::BlueYellow),
+ Theme::new("achromatopsia", Palette::Monochrome),
+ Theme::new("blue-cone-monochromacy", Palette::Monochrome),
+ Theme::new("monochrome", Palette::Monochrome),
+ Theme::new("plain", Palette::Plain),
+];
+
+pub enum Tone {
+ Success,
+ Notice,
+ Error,
+}
+
+impl Theme {
+ const fn new(name: &'static str, palette: Palette) -> Self {
+ Self { name, palette }
+ }
+
+ pub fn parse(name: &str) -> Option<Self> {
+ THEMES.iter().copied().find(|entry| entry.name == name)
+ }
+
+ pub fn names() -> impl Iterator<Item = &'static str> {
+ THEMES.iter().map(|entry| entry.name)
+ }
+
+ fn style(self, tone: Tone) -> &'static str {
+ let styles = match self.palette {
+ Palette::Standard => ["32", "33", "1;31"],
+ Palette::Pastel => ["38;2;150;224;210", "38;2;209;190;255", "1;38;2;255;171;188"],
+ Palette::Catppuccin => ["38;2;166;227;161", "38;2;249;226;175", "1;38;2;243;139;168"],
+ Palette::RedGreen => ["38;2;125;190;255", "38;2;255;220;128", "1;38;2;255;179;85"],
+ Palette::BlueYellow => ["38;2;152;223;154", "38;2;255;188;203", "1;38;2;255;138;173"],
+ Palette::Monochrome => ["1", "4", "1;4"],
+ Palette::Plain => return "",
+ };
+
+ match tone {
+ Tone::Success => styles[0],
+ Tone::Notice => styles[1],
+ Tone::Error => styles[2],
+ }
+ }
+
+ pub fn stdout(self) -> Terminal {
+ let enabled = io::stdout().is_terminal()
+ && env::var_os("NO_COLOR").is_none_or(|value| value.is_empty())
+ && env::var_os("TERM").is_none_or(|value| value != "dumb");
+ Terminal { theme: self, enabled }
+ }
+}
+
+pub struct Terminal {
+ theme: Theme,
+ enabled: bool,
+}
+
+impl Terminal {
+ pub fn paint(&self, tone: Tone, label: &str) -> String {
+ let style = self.theme.style(tone);
+
+ if self.enabled && !style.is_empty() {
+ format!("\x1b[{style}m{label}\x1b[0m")
+ } else {
+ label.to_owned()
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn themes_preserve_labels_and_reset_terminal_styles() {
+ for theme in THEMES {
+ let terminal = Terminal {
+ theme: *theme,
+ enabled: true,
+ };
+ let label = terminal.paint(Tone::Error, "syntax");
+
+ if theme.name == "plain" {
+ assert_eq!(label, "syntax");
+ } else {
+ assert!(label.starts_with("\x1b["));
+ assert!(label.ends_with("msyntax\x1b[0m"));
+ }
+ }
+ }
+}
diff --git a/tests/cli.rs b/tests/cli.rs
new file mode 100644
index 0000000..b9164bc
--- /dev/null
+++ b/tests/cli.rs
@@ -0,0 +1,557 @@
+// tests/cli.rs
+
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+
+use serde_json::Value;
+use tempfile::TempDir;
+
+struct Workspace {
+ _root: TempDir,
+ home: PathBuf,
+ project: PathBuf,
+}
+
+impl Workspace {
+ fn new() -> Self {
+ let root = tempfile::tempdir().unwrap();
+ let home = root.path().join("home");
+ let project = root.path().join("project");
+ fs::create_dir(&home).unwrap();
+ fs::create_dir(&project).unwrap();
+
+ Self {
+ _root: root,
+ home,
+ project,
+ }
+ }
+
+ fn write(&self, path: &str, source: impl AsRef<[u8]>) {
+ write(self.project.join(path), source);
+ }
+
+ fn read(&self, path: &str) -> String {
+ fs::read_to_string(self.project.join(path)).unwrap()
+ }
+
+ fn cli(&self, arguments: &[&str], expected: i32) -> Output {
+ let output = Command::new(env!("CARGO_BIN_EXE_c4d"))
+ .args(arguments)
+ .current_dir(&self.project)
+ .env("HOME", &self.home)
+ .env("USERPROFILE", &self.home)
+ .output()
+ .unwrap();
+
+ assert_eq!(
+ output.status.code(),
+ Some(expected),
+ "{arguments:?}\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ output
+ }
+
+ fn config(&self, arguments: &[&str]) -> Value {
+ let mut command = vec!["config", "show"];
+ command.extend(arguments);
+ serde_json::from_slice(&self.cli(&command, 0).stdout).unwrap()
+ }
+}
+
+fn write(path: impl AsRef<Path>, source: impl AsRef<[u8]>) {
+ let path = path.as_ref();
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, source).unwrap();
+}
+
+#[test]
+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");
+
+ write(
+ workspace.home.join(".c4d/config.jp"),
+ "
+[formatting]
+indentSize: 8
+newLineSize: 5
+[cases]
+classes: PascalCase
+functions: flatcase
+[overrides.rust.formatting]
+indentSize: 6
+[overrides.rust.cases]
+functions: camelCase
+variables: snake_case
+",
+ );
+
+ workspace.write(
+ ".c4d/config.jp",
+ "
+[formatting]
+indentSize: 0
+[cases]
+functions: disabled
+[overrides.rust.formatting]
+newLineSize: 3
+[overrides.typescript.cases]
+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"];
+ 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]")
+ );
+ assert_eq!(
+ settings["languages"]["typescript"]["cases"]["functions"],
+ "PascalCase"
+ );
+
+ workspace.write("src/nested/.c4d/config.jp", "[cases]\nclasses: flatcase\n");
+ let nested = workspace.config(&["src/nested", "--language", "rust"]);
+ assert_eq!(nested["formatting"]["indentSize"], 6);
+ assert_eq!(nested["cases"]["classes"], "flatcase");
+}
+
+#[test]
+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);
+
+ for invalid in [
+ "[formatting",
+ "[formatting]\nindentSize: disabled",
+ "[formatting]\nindentSize: 1.5",
+ "[formatting]\nnewLineSize:",
+ "[cases]\nfunctions: 0",
+ "[cases]\nfunctions: typo",
+ "[cases]\nmethods: camelCase",
+ "[formatting]\nindentSize: 3\nindentSize: 4",
+ ] {
+ workspace.write(".c4d/config.jp", invalid);
+ let result = workspace.cli(&["config", "show"], 2);
+ assert!(String::from_utf8_lossy(&result.stderr).contains("config.jp"));
+ }
+
+ write(workspace.home.join(".c4d/config.jp"), "[cases");
+ let result = workspace.cli(&["config", "show"], 2);
+ assert!(String::from_utf8_lossy(&result.stderr).contains("config.jp:1:1"));
+}
+
+#[test]
+fn check_and_dry_run_do_not_write_and_syntax_errors_are_reported() {
+ let workspace = Workspace::new();
+ let source = "fn BadName() {\nlet BadVariable = 1;\n}\nstruct bad_type;\n";
+ workspace.write("main.rs", source);
+ workspace.write(
+ ".c4d/config.jp",
+ "[cases]\nfunctions: snake_case\nvariables: snake_case\nclasses: PascalCase\n",
+ );
+
+ let check = workspace.cli(&["check", "."], 1);
+ let diagnostics = String::from_utf8_lossy(&check.stdout);
+
+ for expected in [
+ "main.rs:1:4 cases.functions",
+ "main.rs:2:1 formatting.indentSize",
+ "main.rs:2:5 cases.variables",
+ "main.rs:4:8 cases.classes",
+ ] {
+ assert!(diagnostics.contains(expected), "{diagnostics}");
+ }
+
+ assert_eq!(workspace.read("main.rs"), source);
+
+ let dry_run = workspace.cli(&["format", "--check", "main.rs"], 1);
+ assert_eq!(
+ String::from_utf8_lossy(&dry_run.stdout).trim(),
+ "main.rs: would format"
+ );
+ assert_eq!(workspace.read("main.rs"), source);
+
+ workspace.cli(&["format", ".", "main.rs"], 0);
+ workspace.cli(&["format", "--check", "."], 0);
+ workspace.cli(&["check", "."], 1);
+ assert_eq!(
+ workspace.read("main.rs"),
+ "fn BadName() {\n let BadVariable = 1;\n}\n\nstruct bad_type;\n",
+ );
+
+ workspace.write("broken.rs", "fn broken() { let value = ; }\n");
+ let broken = workspace.cli(&["format", "."], 2);
+ assert!(String::from_utf8_lossy(&broken.stdout).contains("broken.rs:1:"));
+ assert_eq!(
+ workspace.read("broken.rs"),
+ "fn broken() { let value = ; }\n"
+ );
+ workspace.cli(&["check", "--check"], 2);
+ workspace.cli(&["--help"], 0);
+}
+
+#[test]
+fn zero_values_independently_disable_formatting_rules() {
+ let workspace = Workspace::new();
+ let source = "fn BadName() {\n1;\n}\nstruct thing;\n";
+
+ for (configuration, expected) in [
+ ("indentSize: 0", "fn BadName() {\n1;\n}\n\nstruct thing;\n"),
+ (
+ "newLineSize: 0",
+ "fn BadName() {\n 1;\n}\nstruct thing;\n",
+ ),
+ ("indentSize: 0\nnewLineSize: 0", source),
+ ] {
+ workspace.write("main.rs", source);
+ workspace.write(".c4d/config.jp", format!("[formatting]\n{configuration}\n"));
+ workspace.cli(&["format", "."], 0);
+ assert_eq!(workspace.read("main.rs"), expected);
+ workspace.cli(&["check", "."], 0);
+ }
+}
+
+#[test]
+fn formatting_preserves_literals_comments_crlf_and_macro_token_spacing() {
+ let workspace = Workspace::new();
+ let source = concat!(
+ "\u{feff}#!/usr/bin/env rust-script\r\n",
+ "/// Documentation for main.\r\n",
+ "fn main() {\r\n",
+ "\t/* A comment\r\n",
+ " inside the block. */\r\n",
+ "let привет = r#\"first\r\n",
+ " second\"#;\r\n",
+ "let escaped = \"first\\\r\n",
+ " second\";\r\n",
+ "let tokens = stringify!(\r\n",
+ " α + β\r\n",
+ ");\r\n",
+ "println!(\"{}:{}:{}\", привет, escaped, tokens);\r\n",
+ "}\r\n",
+ "fn unused() {}\r\n",
+ );
+ workspace.write("main.rs", source);
+ workspace.cli(&["format", "."], 0);
+ let formatted = workspace.read("main.rs");
+ assert!(formatted.starts_with("\u{feff}#!/usr/bin/env rust-script\r\n"));
+ assert!(formatted.contains("\r\n let привет = r#\"first\r\n second\"#;"));
+ assert!(formatted.contains("\t/* A comment\r\n inside the block. */"));
+ assert!(formatted.contains("\"first\\\r\n second\""));
+ assert!(formatted.contains("stringify!(\r\n α + β\r\n)"));
+ assert!(formatted.contains("}\r\n\r\nfn unused"));
+ assert!(!formatted.replace("\r\n", "").contains('\n'));
+ workspace.cli(&["format", "--check", "."], 0);
+
+ let runs = [source, &formatted].map(|variant| {
+ // rustc expects the BOM and shebang to be removed by its caller for this fixture.
+ let (_, code) = variant.split_once("\r\n").unwrap();
+ workspace.write("main.rs", code);
+ let executable = workspace.project.join(if cfg!(windows) {
+ "fixture.exe"
+ } else {
+ "fixture"
+ });
+ let build = Command::new("rustc")
+ .arg(workspace.project.join("main.rs"))
+ .args(["--crate-name", "fixture", "-o"])
+ .arg(&executable)
+ .output()
+ .unwrap();
+ assert!(
+ build.status.success(),
+ "{}",
+ String::from_utf8_lossy(&build.stderr)
+ );
+ let run = Command::new(executable).output().unwrap();
+ assert!(run.status.success());
+ run.stdout
+ });
+ assert_eq!(runs[0], runs[1]);
+}
+
+#[test]
+fn location_macros_keep_source_positions_without_disabling_naming_diagnostics() {
+ let workspace = Workspace::new();
+ let source = "fn BadName() {\n let position = (line!(), std::column!());\n}\nfn other() {}\n";
+ workspace.write("main.rs", source);
+ workspace.write(".c4d/config.jp", "[cases]\nfunctions: snake_case");
+ workspace.cli(&["format", "."], 0);
+ assert_eq!(workspace.read("main.rs"), source);
+ let check = workspace.cli(&["check", "."], 1);
+ assert!(String::from_utf8_lossy(&check.stdout).contains("cases.functions"));
+}
+
+#[test]
+fn discovery_obeys_ignore_rules_and_skips_non_sources() {
+ let workspace = Workspace::new();
+ let source = " fn main() {}\n";
+ workspace.write(".git/hidden.rs", source);
+ workspace.write(
+ ".gitignore",
+ "*.ignored.rs\nignored/\n!keep.ignored.rs\n**/cache/*.rs\n[ab].rs\n",
+ );
+ workspace.write(".c4dignore", "/custom.rs\n\\!literal.rs\n");
+ workspace.write("nested/.gitignore", "!restored.ignored.rs\n/deep.rs\n");
+
+ let skipped = [
+ "a.rs",
+ "custom.rs",
+ "!literal.rs",
+ "z.ignored.rs",
+ "ignored/special.rs",
+ "nested/deep.rs",
+ "nested/cache/mod.rs",
+ "target/module.rs",
+ "node_modules/module.rs",
+ "file.generated.rs",
+ "code.ts",
+ "code.py",
+ ".git/hidden.rs",
+ "../external/outside.rs",
+ ];
+
+ for path in skipped {
+ workspace.write(path, source);
+ }
+
+ workspace.write("auto.rs", format!("// @generated\n{source}"));
+ workspace.write("binary.rs", [0xff, 0]);
+
+ for path in ["keep.ignored.rs", "nested/restored.ignored.rs", "z.rs"] {
+ workspace.write(path, source);
+ }
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::symlink;
+ symlink(
+ workspace.project.join("../external"),
+ workspace.project.join("link"),
+ )
+ .unwrap();
+ symlink(
+ workspace.project.join("../external/outside.rs"),
+ workspace.project.join("linked.rs"),
+ )
+ .unwrap();
+ let explicit = workspace.cli(&["format", "link/outside.rs", "linked.rs"], 0);
+ assert!(String::from_utf8_lossy(&explicit.stderr).contains("symbolic link"));
+ }
+
+ let output = workspace.cli(&["format", "."], 0);
+ let stdout = String::from_utf8_lossy(&output.stdout).replace('\\', "/");
+ assert_eq!(
+ stdout.lines().collect::<Vec<_>>(),
+ [
+ "keep.ignored.rs: formatted",
+ "nested/restored.ignored.rs: formatted",
+ "z.rs: formatted"
+ ],
+ );
+ assert!(String::from_utf8_lossy(&output.stderr).contains("binary or non-UTF-8"));
+
+ for path in skipped {
+ assert_eq!(workspace.read(path), source, "{path}");
+ }
+
+ assert!(workspace.read("auto.rs").ends_with(source));
+
+ let explicit = workspace.cli(
+ &[
+ "format",
+ "ignored/special.rs",
+ "code.ts",
+ "target/module.rs",
+ ],
+ 0,
+ );
+ let stderr = String::from_utf8_lossy(&explicit.stderr);
+ assert!(stderr.contains("ignored by project rules"));
+ assert!(stderr.contains("unsupported or generated file"));
+ assert!(stderr.contains("excluded directory"));
+}
+
+#[test]
+fn inner_attribute_after_trivia_keeps_the_file_header() {
+ let workspace = Workspace::new();
+ let source = "#! /* comment /* nested */ */ [allow(dead_code)]\n fn example() {}\n";
+ workspace.write("main.rs", source);
+ workspace.cli(&["format", "."], 0);
+ assert_eq!(workspace.read("main.rs"), source.replace(" fn", "fn"));
+ workspace.cli(&["format", "--check", "."], 0);
+}
+
+#[cfg(unix)]
+#[test]
+fn atomic_update_preserves_permissions_and_rejects_hard_links() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let workspace = Workspace::new();
+ let source = " fn example() {}\n";
+ workspace.write("script.rs", source);
+ let path = workspace.project.join("script.rs");
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o750)).unwrap();
+
+ let link = workspace.project.join("duplicate.rs");
+ fs::hard_link(&path, &link).unwrap();
+ let result = workspace.cli(&["format", "script.rs"], 2);
+ assert!(String::from_utf8_lossy(&result.stderr).contains("multiple hard links"));
+ assert_eq!(workspace.read("script.rs"), source);
+ assert_eq!(workspace.read("duplicate.rs"), source);
+
+ fs::remove_file(link).unwrap();
+ workspace.cli(&["format", "script.rs"], 0);
+ assert_eq!(workspace.read("script.rs"), source.trim_start());
+ assert_eq!(
+ fs::metadata(path).unwrap().permissions().mode() & 0o777,
+ 0o750
+ );
+}
+
+#[test]
+fn file_path_headers_are_opt_in_and_use_project_paths() {
+ let workspace = Workspace::new();
+ let source = concat!(
+ "\u{feff}#!/usr/bin/env rust-script\r\n",
+ "//! Existing module docs.\r\n",
+ "fn main() {}\r\n",
+ );
+ 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
+ );
+
+ workspace.write(
+ ".c4d/config.jp",
+ "[overrides.rust.formatting]\nfilePathHeader: true\n",
+ );
+ let check = workspace.cli(&["check", "src/main.rs"], 1);
+ assert!(String::from_utf8_lossy(&check.stdout).contains("formatting.filePathHeader"));
+ workspace.cli(&["format", "--check", "src/main.rs"], 1);
+ assert_eq!(workspace.read("src/main.rs"), source);
+
+ workspace.cli(&["format", "src/main.rs"], 0);
+ let formatted = workspace.read("src/main.rs");
+ assert_eq!(
+ formatted,
+ source.replace("//! Existing", "// src/main.rs\r\n//! Existing"),
+ );
+ workspace.cli(&["check", "src"], 0);
+ workspace.cli(&["format", "--check", "."], 0);
+
+ workspace.write("src/position.rs", "fn position() -> u32 { line!() }\n");
+ workspace.write("src/auto.rs", "// @generated\nfn generated() {}\n");
+ workspace.cli(&["format", "."], 0);
+ assert_eq!(
+ workspace.read("src/position.rs"),
+ "fn position() -> u32 { line!() }\n"
+ );
+ assert!(workspace.read("src/auto.rs").starts_with("// @generated"));
+}
+
+#[test]
+fn explicit_false_overrides_inherited_headers_and_existing_comments_remain() {
+ let workspace = Workspace::new();
+ write(
+ workspace.home.join(".c4d/config.jp"),
+ "[overrides.rust.formatting]\nfilePathHeader: true",
+ );
+ workspace.write(".c4d/config.jp", "[formatting]\nfilePathHeader: false");
+ workspace.write("main.rs", "fn main() {}\n");
+ workspace.cli(&["format", "--check", "."], 0);
+
+ workspace.write(".c4d/config.jp", "[formatting]\nfilePathHeader: true");
+ let existing = "// Copyright example\n// main.rs\nfn main() {}\n";
+ workspace.write("main.rs", existing);
+ workspace.cli(&["format", "--check", "."], 0);
+ assert_eq!(workspace.read("main.rs"), existing);
+
+ workspace.write(".c4d/config.jp", "[formatting]\nfilePathHeader: 1");
+ workspace.cli(&["config", "show"], 2);
+}
+
+#[test]
+fn unsupported_language_fixtures_are_preserved_byte_for_byte() {
+ let workspace = Workspace::new();
+ let examples: &[(&str, &[u8])] = &[
+ ("example.py", include_bytes!("fixtures/example.py")),
+ ("example.ts", include_bytes!("fixtures/example.ts")),
+ ("example.js", include_bytes!("fixtures/example.js")),
+ ("example.go", include_bytes!("fixtures/example.go")),
+ ];
+
+ workspace.write(
+ ".c4d/config.jp",
+ "[formatting]\nindentSize: 8\nnewLineSize: 3\nfilePathHeader: true\n",
+ );
+
+ for (name, source) in examples {
+ workspace.write(&format!("fixtures/{name}"), source);
+ }
+
+ assert!(workspace.cli(&["check", "fixtures"], 0).stdout.is_empty());
+ assert!(workspace.cli(&["format", "fixtures"], 0).stdout.is_empty());
+
+ for (name, source) in examples {
+ let relative = format!("fixtures/{name}");
+ let output = workspace.cli(&["format", &relative], 0);
+ assert!(String::from_utf8_lossy(&output.stderr).contains("unsupported"));
+ assert_eq!(fs::read(workspace.project.join(relative)).unwrap(), *source);
+ }
+}
+
+#[test]
+fn version_command_and_flags_report_the_build_version() {
+ let workspace = Workspace::new();
+ workspace.write(".c4d/config.jp", "[invalid");
+ let expected = format!("c4d {}\n", env!("CARGO_PKG_VERSION"));
+
+ for argument in ["version", "-V", "--version"] {
+ let result = workspace.cli(&[argument], 0);
+ assert_eq!(result.stdout, expected.as_bytes());
+ assert!(result.stderr.is_empty());
+ }
+}
+
+#[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");
+ 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");
+ let preview = workspace.cli(&["format", "--check", "."], 1);
+ assert_eq!(preview.stdout, b"main.rs: would format\n");
+
+ workspace.write(".c4d/config.jp", "[terminal]\ncolor: unknown");
+ let invalid = workspace.cli(&["config", "show"], 2);
+ assert!(String::from_utf8_lossy(&invalid.stderr).contains("terminal.color"));
+}
diff --git a/tests/fixtures/example.go b/tests/fixtures/example.go
new file mode 100644
index 0000000..e8c5175
--- /dev/null
+++ b/tests/fixtures/example.go
@@ -0,0 +1,10 @@
+// tests/fixtures/example.go
+
+package fixture
+
+func DescribeStatus(ready bool) string {
+ if ready {
+ return "ready"
+ }
+ return "waiting"
+}
diff --git a/tests/fixtures/example.js b/tests/fixtures/example.js
new file mode 100644
index 0000000..2378341
--- /dev/null
+++ b/tests/fixtures/example.js
@@ -0,0 +1,5 @@
+/* tests/fixtures/example.js */
+
+export function describeStatus(ready) {
+ return `Status: ${ready ? "ready" : "waiting"}`;
+}
diff --git a/tests/fixtures/example.py b/tests/fixtures/example.py
new file mode 100644
index 0000000..bba3d13
--- /dev/null
+++ b/tests/fixtures/example.py
@@ -0,0 +1,6 @@
+# tests/fixtures/example.py
+
+def describe_status(ready):
+ if ready:
+ return "ready"
+ return "waiting"
diff --git a/tests/fixtures/example.ts b/tests/fixtures/example.ts
new file mode 100644
index 0000000..57fe12a
--- /dev/null
+++ b/tests/fixtures/example.ts
@@ -0,0 +1,7 @@
+/* tests/fixtures/example.ts */
+
+export type Status = "ready" | "waiting";
+
+export function describeStatus(ready: boolean): Status {
+ return ready ? "ready" : "waiting";
+}