spacify 0.2.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.4.0](https://github.com/avanserv/spacify/compare/v0.3.0...v0.4.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * Keep paragraphs between simple statements ([#19](https://github.com/avanserv/spacify/issues/19)) ([90ad405](https://github.com/avanserv/spacify/commit/90ad40534c6024e97624acb3c9b500f044d0aa66))
9
+
10
+ ## [0.3.0](https://github.com/avanserv/spacify/compare/v0.2.1...v0.3.0) (2026-10-27)
11
+
12
+
13
+ ### Features
14
+
15
+ * Format Rust code ([#14](https://github.com/avanserv/spacify/issues/14)) ([9f9755a](https://github.com/avanserv/spacify/commit/9f9755a0873b6f4a2ba103a39790e76c03047e12))
16
+
3
17
  ## [0.2.1](https://github.com/avanserv/spacify/compare/v0.2.0...v0.2.1) (2026-10-27)
4
18
 
5
19
 
@@ -26,7 +26,8 @@ make check
26
26
  ```
27
27
 
28
28
  runs everything CI runs except the security scan: format (rustfmt), lint (clippy, zizmor), the
29
- tests, and the ruff round trip over the fixtures and CPython's `Lib`. `make help` lists the
29
+ tests, and the formatter round trips: ruff over the fixtures and CPython's `Lib`, rustfmt over the
30
+ fixtures, ripgrep and tokio. `make help` lists the
30
31
  individual targets. `make format` is the one that fixes, where `make check` only reports.
31
32
 
32
33
  The git hooks run the same Rust checks, plus a few that only make sense there: secrets (gitleaks),
@@ -35,20 +36,27 @@ hooks` runs all of them over the whole tree.
35
36
 
36
37
  ## How the code is laid out
37
38
 
38
- `src/python/mod.rs` parses with tree-sitter and turns each pair of sibling statements into a `Gap`.
39
- `src/python/rules.rs` decides how many blank lines that gap should have, or that no rule has an
40
- opinion. `src/edit.rs` rewrites only those blank-line runs, so a rule can never change a byte inside
41
- a statement. `src/main.rs` and `src/walk.rs` are the command line and the file walk.
39
+ Each language has a module, `src/python/mod.rs` and `src/rust/mod.rs`, that parses with tree-sitter,
40
+ finds the statements of every block and classifies them. `src/gaps.rs` turns each pair of sibling
41
+ statements into a `Gap`: where it runs, which comments belong to the next statement, and which
42
+ regions are switched off. `src/rules.rs` decides how many blank lines that gap should have, or that no
43
+ rule has an opinion. `src/edit.rs` rewrites only those blank-line runs, so a rule can never change a
44
+ byte inside a statement. `src/language.rs` maps file extensions to languages, and `src/main.rs` and
45
+ `src/walk.rs` are the command line and the file walk.
42
46
 
43
- A rule must hold the promise in the README: it never moves a blank-line count outside what `ruff
44
- format` keeps. Check `ruff format --isolated` on a sample before writing a rule, because ruff owns
45
- more gaps than it looks like it does (those next to a `def` or a `class`, after an import, after a
46
- docstring).
47
+ A new language needs a module like those two, a variant in `src/language.rs`, a `[<language>.rules]`
48
+ table in `src/config.rs`, fixtures, a round-trip script against its formatter, and a corpus of real
49
+ code in the `Makefile`.
50
+
51
+ A rule must hold the promise in the README: it never moves a blank-line count outside what the
52
+ language's formatter keeps. Check `ruff format --isolated` or `rustfmt` on a sample before writing a
53
+ rule, because a formatter owns more gaps than it looks like it does (in Python, those next to a `def`
54
+ or a `class`, after an import, after a docstring).
47
55
 
48
56
  ## Tests
49
57
 
50
- A rule change comes with a fixture: `tests/fixtures/<name>.py` and the `<name>.expected.py` it must
51
- format to. The test also checks that the expected file is a fixed point. To rewrite the expected
58
+ A rule change comes with a fixture: `tests/fixtures/<name>.<ext>` and the `<name>.expected.<ext>` it
59
+ must format to. The test also checks that the expected file is a fixed point. To rewrite the expected
52
60
  files from the current output, then review the diff:
53
61
 
54
62
  ```bash
@@ -57,9 +65,11 @@ SPACIFY_BLESS=1 cargo test --test fixtures
57
65
 
58
66
  Unit tests for a module's internals sit in a `tests` module at the bottom of its file.
59
67
 
60
- `make compat` is the check that matters for ruff: both orders, over the fixtures and CPython's `Lib`
61
- (the Makefile's `CPYTHON_SKIP` lists the files left out, and why). It also formats a copy with
62
- spacify alone and runs `scripts/ast-equal.py` to prove every file kept its AST. `make bench` times a
68
+ `make compat` is the check that matters for the formatters. `scripts/ruff-compat.sh` runs both
69
+ orders against ruff over the fixtures and CPython's `Lib` (the Makefile's `CPYTHON_SKIP` lists the
70
+ files left out, and why), then formats a copy with spacify alone and runs `scripts/ast-equal.py` to
71
+ prove every file kept its AST. `scripts/rustfmt-compat.sh` does the same against rustfmt over the
72
+ fixtures, ripgrep and tokio, with `examples/tokens_equal.rs` proving every file kept its tokens. `make bench` times a
63
73
  check over CPython's `Lib` with hyperfine.
64
74
 
65
75
  ## Commits and pull requests
@@ -229,9 +229,9 @@ dependencies = [
229
229
 
230
230
  [[package]]
231
231
  name = "globset"
232
- version = "0.4.20"
232
+ version = "0.4.21"
233
233
  source = "registry+https://github.com/rust-lang/crates.io-index"
234
- checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"
234
+ checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d"
235
235
  dependencies = [
236
236
  "aho-corasick",
237
237
  "bstr",
@@ -254,9 +254,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
254
254
 
255
255
  [[package]]
256
256
  name = "ignore"
257
- version = "0.4.33"
257
+ version = "0.4.34"
258
258
  source = "registry+https://github.com/rust-lang/crates.io-index"
259
- checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f"
259
+ checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7"
260
260
  dependencies = [
261
261
  "crossbeam-deque",
262
262
  "globset",
@@ -493,22 +493,23 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
493
493
 
494
494
  [[package]]
495
495
  name = "similar"
496
- version = "3.2.0"
496
+ version = "3.2.1"
497
497
  source = "registry+https://github.com/rust-lang/crates.io-index"
498
- checksum = "4f66ca1f7aca2474dc10c942eb22feffc897735f54cd1db90138c2fddb490987"
498
+ checksum = "d2f8bec09ae8fae0f4f265a4559a9334be3929d8504e9b536df0a41302bd1733"
499
499
  dependencies = [
500
500
  "bstr",
501
501
  ]
502
502
 
503
503
  [[package]]
504
504
  name = "spacify"
505
- version = "0.2.1"
505
+ version = "0.4.0"
506
506
  dependencies = [
507
507
  "anyhow",
508
508
  "clap",
509
509
  "globset",
510
510
  "ignore",
511
511
  "pretty_assertions",
512
+ "proc-macro2",
512
513
  "rayon",
513
514
  "serde",
514
515
  "similar",
@@ -516,6 +517,7 @@ dependencies = [
516
517
  "toml",
517
518
  "tree-sitter",
518
519
  "tree-sitter-python",
520
+ "tree-sitter-rust",
519
521
  ]
520
522
 
521
523
  [[package]]
@@ -556,9 +558,9 @@ dependencies = [
556
558
 
557
559
  [[package]]
558
560
  name = "toml"
559
- version = "1.1.8+spec-1.1.0"
561
+ version = "1.2.0+spec-1.1.0"
560
562
  source = "registry+https://github.com/rust-lang/crates.io-index"
561
- checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"
563
+ checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561"
562
564
  dependencies = [
563
565
  "indexmap",
564
566
  "serde_core",
@@ -589,9 +591,9 @@ dependencies = [
589
591
 
590
592
  [[package]]
591
593
  name = "toml_writer"
592
- version = "1.1.3+spec-1.1.0"
594
+ version = "1.2.0+spec-1.1.0"
593
595
  source = "registry+https://github.com/rust-lang/crates.io-index"
594
- checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
596
+ checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
595
597
 
596
598
  [[package]]
597
599
  name = "tree-sitter"
@@ -622,6 +624,16 @@ dependencies = [
622
624
  "tree-sitter-language",
623
625
  ]
624
626
 
627
+ [[package]]
628
+ name = "tree-sitter-rust"
629
+ version = "0.24.2"
630
+ source = "registry+https://github.com/rust-lang/crates.io-index"
631
+ checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"
632
+ dependencies = [
633
+ "cc",
634
+ "tree-sitter-language",
635
+ ]
636
+
625
637
  [[package]]
626
638
  name = "unicode-ident"
627
639
  version = "1.0.27"
@@ -1,13 +1,13 @@
1
1
  [package]
2
2
  name = "spacify"
3
- version = "0.2.1"
3
+ version = "0.4.0"
4
4
  edition = "2024"
5
5
  rust-version = "1.85"
6
- description = "A fast formatter for the vertical rhythm of Python code, complementary to ruff"
6
+ description = "A fast formatter for the vertical rhythm of Python and Rust code, complementary to ruff and rustfmt"
7
7
  license = "MIT"
8
8
  repository = "https://github.com/avanserv/spacify"
9
9
  readme = "README.md"
10
- keywords = ["python", "formatter", "blank-lines", "ruff"]
10
+ keywords = ["python", "rust", "formatter", "blank-lines", "rustfmt"]
11
11
  categories = ["command-line-utilities", "development-tools"]
12
12
  # The fixtures are test data, and the Python packaging files belong to the wheel, not the crate.
13
13
  exclude = ["tests/fixtures/", ".github/", "pyproject.toml"]
@@ -31,9 +31,11 @@ similar = "3.2.0"
31
31
  toml = "1.1.8"
32
32
  tree-sitter = "0.27.1"
33
33
  tree-sitter-python = "0.25.0"
34
+ tree-sitter-rust = "0.24.2"
34
35
 
35
36
  [dev-dependencies]
36
37
  pretty_assertions = "1.4.1"
38
+ proc-macro2 = "1.0.107"
37
39
  tempfile = "3.27.0"
38
40
 
39
41
  [profile.release]
spacify-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: spacify
3
+ Version: 0.4.0
4
+ Classifier: Development Status :: 3 - Alpha
5
+ Classifier: Environment :: Console
6
+ Classifier: Intended Audience :: Developers
7
+ Classifier: Programming Language :: Python
8
+ Classifier: Programming Language :: Rust
9
+ Classifier: Topic :: Software Development :: Quality Assurance
10
+ License-File: LICENSE
11
+ Summary: A fast formatter for the vertical rhythm of Python and Rust code, complementary to ruff and rustfmt
12
+ Keywords: python,rust,formatter,blank-lines,ruff,rustfmt,pre-commit
13
+ License-Expression: MIT
14
+ Requires-Python: >=3.7
15
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
16
+ Project-URL: Changelog, https://github.com/avanserv/spacify/blob/main/CHANGELOG.md
17
+ Project-URL: Repository, https://github.com/avanserv/spacify
18
+
19
+ # spacify
20
+
21
+ [![CI](https://github.com/avanserv/spacify/actions/workflows/ci.yml/badge.svg)](https://github.com/avanserv/spacify/actions/workflows/ci.yml)
22
+ [![PyPI](https://img.shields.io/pypi/v/spacify)](https://pypi.org/project/spacify/)
23
+
24
+ A fast formatter for the vertical rhythm of Python and Rust code. `ruff format` and rustfmt decide
25
+ how a statement is laid out, but leave most of the blank lines between statements up to you. spacify
26
+ fills that gap: it puts air around logical blocks and tightens runs of related statements, and it
27
+ only touches the blank lines between statements.
28
+
29
+ Before:
30
+
31
+ ```python
32
+ def load(paths):
33
+ seen = set()
34
+ for path in paths:
35
+ if path in seen:
36
+ continue
37
+ seen.add(path)
38
+ total = len(seen)
39
+ count = 0
40
+ log(total)
41
+ return total
42
+ ```
43
+
44
+ After `spacify`:
45
+
46
+ ```python
47
+ def load(paths):
48
+ seen = set()
49
+
50
+ for path in paths:
51
+ if path in seen:
52
+ continue
53
+
54
+ seen.add(path)
55
+
56
+ total = len(seen)
57
+ count = 0
58
+ log(total)
59
+
60
+ return total
61
+ ```
62
+
63
+ spacify never fights your formatter. Every rule stays inside the blank-line bounds `ruff format` and
64
+ rustfmt keep, and CI runs spacify and the formatter over CPython's standard library, ripgrep and
65
+ tokio in both orders to check they reach a fixed point. It also checks that spacify leaves every
66
+ Python file's AST, and every Rust file's tokens, unchanged. Checking CPython's `Lib`, without its
67
+ tests, takes under half a second on 8 cores.
68
+
69
+ ## Install
70
+
71
+ ```bash
72
+ uv tool install spacify # or: pipx install spacify, pip install spacify
73
+ ```
74
+
75
+ ## Use with prek or pre-commit
76
+
77
+ Put the hook after your formatter's (`ruff-format`, or a `cargo fmt` hook), so spacify sees its
78
+ line wrapping:
79
+
80
+ ```yaml
81
+ repos:
82
+ - repo: https://github.com/astral-sh/ruff-pre-commit
83
+ rev: v0.16.9
84
+ hooks:
85
+ - id: ruff-format
86
+ - repo: https://github.com/avanserv/spacify-pre-commit
87
+ rev: v0.1.0
88
+ hooks:
89
+ - id: spacify
90
+ ```
91
+
92
+ The hook installs the prebuilt wheel from PyPI, so you don't need a Rust toolchain.
93
+
94
+ ## Command line
95
+
96
+ ```bash
97
+ spacify # format every Python and Rust file under the current directory
98
+ spacify src/ tests/a.py # format these paths
99
+ spacify --check # write nothing; exit 1 if any file would change
100
+ spacify --diff # write nothing; print a unified diff
101
+ spacify - < a.py # read stdin, write stdout (--stdin-filename names it)
102
+ ```
103
+
104
+ The exit code is 0 on success, 1 when `--check` or `--diff` found changes, and 2 on an error such as
105
+ a syntax error, in which case the file is left untouched. Directory walks respect `.gitignore` and
106
+ skip the directories ruff skips by default. A file you name explicitly is always formatted, unless
107
+ you also pass `--force-exclude`, which is what the hook does.
108
+
109
+ ## Languages
110
+
111
+ spacify formats every language it supports by default: Python (`.py`, `.pyi`) and Rust (`.rs`). To
112
+ format only some, list them in the configuration, for example `languages = ["python"]`. Files in
113
+ other languages are skipped, even when you name them, and stdin takes its language from
114
+ `--stdin-filename` (Python without one).
115
+
116
+ ## Known limits
117
+
118
+ In Python, spacify parses with tree-sitter-python, which rejects a few valid constructs: type parameter
119
+ defaults (`def f[T = int]()`, PEP 696), a parenthesised starred subscript (`a[*(b)]`), and an
120
+ attribute access broken after its dot onto a line indented less than the statement. A file using one
121
+ exits 2 and is left untouched. Files must be UTF-8, as for ruff, and line endings that are a bare
122
+ `\r` are refused the same way. Python 2 `print` and `exec` statements are not rejected, since
123
+ tree-sitter cannot tell some of them from valid Python 3 such as `print >>f, x`.
124
+
125
+ In Rust, tree-sitter-rust refuses some nightly-only syntax, and such a file exits 2 untouched.
126
+ spacify assumes rustfmt's default ceiling of one blank line, so it does not support a
127
+ `blank_lines_upper_bound` above 1.
128
+
129
+ ## Rules
130
+
131
+ Each rule can be turned on or off. They all apply to sibling statements in the same block.
132
+
133
+ | Rule | Effect |
134
+ | --- | --- |
135
+ | `blank-before-block` | At least one blank line before a block statement when another statement comes before it. |
136
+ | `blank-after-block` | At least one blank line after a block statement, before the next statement. |
137
+ | `blank-before-exit` | At least one blank line before an exit, in blocks of `exit-min-block-statements` (default 3) or more statements. |
138
+ | `keep-paragraphs` | Exactly one blank line between two simple statements the author separated with any. |
139
+ | `collapse-groups` | No blank line between two single-line statements of the same kind. Acts only with `keep-paragraphs` off. |
140
+
141
+ The added blank lines take priority over the other two rules, and `keep-paragraphs` over
142
+ `collapse-groups`. Even with `keep-paragraphs` off, blank lines that have a comment in the gap are
143
+ kept, because a comment marks a paragraph you meant. When a rule does add a blank line, it goes above the comments and attributes that belong to the next statement. What each term means
144
+ depends on the language:
145
+
146
+ | | Python | Rust |
147
+ | --- | --- | --- |
148
+ | Block statements | `if`, `for`, `while`, `try`, `with`, `match`, and their `async` forms | `if`, `match`, `for`, `while`, `loop`, and bare, `unsafe`, `async` and `const` blocks |
149
+ | Exits | `return`, `raise`, `break`, `continue`, a bare `yield` | `return`, `break`, `continue`, and a function body's tail expression |
150
+ | Simple statements, by kind | assignments, augmented assignments, calls, `del`, `assert`, `global`/`nonlocal`, module constants | `let` and assignments, compound assignments, calls (macros, `.await` and `?` included) |
151
+ | Never touched | gaps next to a `def` or `class`, after an `import`, after a docstring | gaps next to an item (`fn`, `struct`, `use`, `const`, ...) |
152
+ | Switched off by | `# fmt: off`/`# fmt: on`, `# spacify: off`/`# spacify: on`, `# fmt: skip` | `// spacify: off`/`// spacify: on`, `#[rustfmt::skip]` |
153
+ | Most blank lines in a row | 2 at module level (1 in a `.pyi` stub), 1 in a nested block | 1 |
154
+
155
+ In Python, an assignment outside every function and class whose target names all have an uppercase
156
+ letter and no lowercase one (`MAX = 3`, `T = TypeVar("T")`, `A, *REST = items`) is a constant, a kind
157
+ apart from other assignments. Imports are never collapsed, because ruff's isort rules separate
158
+ import sections with blank lines. In Rust, the tail expression of a closure, a match arm or a
159
+ `let x = { ... }` block is a value rather than a return, so it stays tight.
160
+
161
+ ## Configuration
162
+
163
+ spacify reads `[tool.spacify]` from `pyproject.toml`, or the top level of a `spacify.toml` or
164
+ `.spacify.toml`, which is the place for a Rust project. It uses the first one it finds walking up from the current directory, or the file
165
+ you pass with `--config`.
166
+
167
+ ```toml
168
+ [tool.spacify]
169
+ extend-exclude = ["generated", "migrations/*.py"] # `exclude = [...]` replaces the defaults
170
+
171
+ languages = ["python", "rust"] # the default: every supported language
172
+
173
+ [tool.spacify.rules]
174
+ blank-before-block = true
175
+ blank-after-block = true
176
+ blank-before-exit = true
177
+ exit-min-block-statements = 3
178
+ keep-paragraphs = true
179
+ collapse-groups = true
180
+
181
+ [tool.spacify.rust.rules] # overrides the shared rules for Rust only
182
+ exit-min-block-statements = 4
183
+ ```
184
+
185
+ An exclude pattern containing a `/` matches the path relative to the config file. Any other pattern
186
+ matches a single file or directory name.
187
+
188
+ ## Contributing
189
+
190
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
191
+
@@ -0,0 +1,172 @@
1
+ # spacify
2
+
3
+ [![CI](https://github.com/avanserv/spacify/actions/workflows/ci.yml/badge.svg)](https://github.com/avanserv/spacify/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/spacify)](https://pypi.org/project/spacify/)
5
+
6
+ A fast formatter for the vertical rhythm of Python and Rust code. `ruff format` and rustfmt decide
7
+ how a statement is laid out, but leave most of the blank lines between statements up to you. spacify
8
+ fills that gap: it puts air around logical blocks and tightens runs of related statements, and it
9
+ only touches the blank lines between statements.
10
+
11
+ Before:
12
+
13
+ ```python
14
+ def load(paths):
15
+ seen = set()
16
+ for path in paths:
17
+ if path in seen:
18
+ continue
19
+ seen.add(path)
20
+ total = len(seen)
21
+ count = 0
22
+ log(total)
23
+ return total
24
+ ```
25
+
26
+ After `spacify`:
27
+
28
+ ```python
29
+ def load(paths):
30
+ seen = set()
31
+
32
+ for path in paths:
33
+ if path in seen:
34
+ continue
35
+
36
+ seen.add(path)
37
+
38
+ total = len(seen)
39
+ count = 0
40
+ log(total)
41
+
42
+ return total
43
+ ```
44
+
45
+ spacify never fights your formatter. Every rule stays inside the blank-line bounds `ruff format` and
46
+ rustfmt keep, and CI runs spacify and the formatter over CPython's standard library, ripgrep and
47
+ tokio in both orders to check they reach a fixed point. It also checks that spacify leaves every
48
+ Python file's AST, and every Rust file's tokens, unchanged. Checking CPython's `Lib`, without its
49
+ tests, takes under half a second on 8 cores.
50
+
51
+ ## Install
52
+
53
+ ```bash
54
+ uv tool install spacify # or: pipx install spacify, pip install spacify
55
+ ```
56
+
57
+ ## Use with prek or pre-commit
58
+
59
+ Put the hook after your formatter's (`ruff-format`, or a `cargo fmt` hook), so spacify sees its
60
+ line wrapping:
61
+
62
+ ```yaml
63
+ repos:
64
+ - repo: https://github.com/astral-sh/ruff-pre-commit
65
+ rev: v0.16.9
66
+ hooks:
67
+ - id: ruff-format
68
+ - repo: https://github.com/avanserv/spacify-pre-commit
69
+ rev: v0.1.0
70
+ hooks:
71
+ - id: spacify
72
+ ```
73
+
74
+ The hook installs the prebuilt wheel from PyPI, so you don't need a Rust toolchain.
75
+
76
+ ## Command line
77
+
78
+ ```bash
79
+ spacify # format every Python and Rust file under the current directory
80
+ spacify src/ tests/a.py # format these paths
81
+ spacify --check # write nothing; exit 1 if any file would change
82
+ spacify --diff # write nothing; print a unified diff
83
+ spacify - < a.py # read stdin, write stdout (--stdin-filename names it)
84
+ ```
85
+
86
+ The exit code is 0 on success, 1 when `--check` or `--diff` found changes, and 2 on an error such as
87
+ a syntax error, in which case the file is left untouched. Directory walks respect `.gitignore` and
88
+ skip the directories ruff skips by default. A file you name explicitly is always formatted, unless
89
+ you also pass `--force-exclude`, which is what the hook does.
90
+
91
+ ## Languages
92
+
93
+ spacify formats every language it supports by default: Python (`.py`, `.pyi`) and Rust (`.rs`). To
94
+ format only some, list them in the configuration, for example `languages = ["python"]`. Files in
95
+ other languages are skipped, even when you name them, and stdin takes its language from
96
+ `--stdin-filename` (Python without one).
97
+
98
+ ## Known limits
99
+
100
+ In Python, spacify parses with tree-sitter-python, which rejects a few valid constructs: type parameter
101
+ defaults (`def f[T = int]()`, PEP 696), a parenthesised starred subscript (`a[*(b)]`), and an
102
+ attribute access broken after its dot onto a line indented less than the statement. A file using one
103
+ exits 2 and is left untouched. Files must be UTF-8, as for ruff, and line endings that are a bare
104
+ `\r` are refused the same way. Python 2 `print` and `exec` statements are not rejected, since
105
+ tree-sitter cannot tell some of them from valid Python 3 such as `print >>f, x`.
106
+
107
+ In Rust, tree-sitter-rust refuses some nightly-only syntax, and such a file exits 2 untouched.
108
+ spacify assumes rustfmt's default ceiling of one blank line, so it does not support a
109
+ `blank_lines_upper_bound` above 1.
110
+
111
+ ## Rules
112
+
113
+ Each rule can be turned on or off. They all apply to sibling statements in the same block.
114
+
115
+ | Rule | Effect |
116
+ | --- | --- |
117
+ | `blank-before-block` | At least one blank line before a block statement when another statement comes before it. |
118
+ | `blank-after-block` | At least one blank line after a block statement, before the next statement. |
119
+ | `blank-before-exit` | At least one blank line before an exit, in blocks of `exit-min-block-statements` (default 3) or more statements. |
120
+ | `keep-paragraphs` | Exactly one blank line between two simple statements the author separated with any. |
121
+ | `collapse-groups` | No blank line between two single-line statements of the same kind. Acts only with `keep-paragraphs` off. |
122
+
123
+ The added blank lines take priority over the other two rules, and `keep-paragraphs` over
124
+ `collapse-groups`. Even with `keep-paragraphs` off, blank lines that have a comment in the gap are
125
+ kept, because a comment marks a paragraph you meant. When a rule does add a blank line, it goes above the comments and attributes that belong to the next statement. What each term means
126
+ depends on the language:
127
+
128
+ | | Python | Rust |
129
+ | --- | --- | --- |
130
+ | Block statements | `if`, `for`, `while`, `try`, `with`, `match`, and their `async` forms | `if`, `match`, `for`, `while`, `loop`, and bare, `unsafe`, `async` and `const` blocks |
131
+ | Exits | `return`, `raise`, `break`, `continue`, a bare `yield` | `return`, `break`, `continue`, and a function body's tail expression |
132
+ | Simple statements, by kind | assignments, augmented assignments, calls, `del`, `assert`, `global`/`nonlocal`, module constants | `let` and assignments, compound assignments, calls (macros, `.await` and `?` included) |
133
+ | Never touched | gaps next to a `def` or `class`, after an `import`, after a docstring | gaps next to an item (`fn`, `struct`, `use`, `const`, ...) |
134
+ | Switched off by | `# fmt: off`/`# fmt: on`, `# spacify: off`/`# spacify: on`, `# fmt: skip` | `// spacify: off`/`// spacify: on`, `#[rustfmt::skip]` |
135
+ | Most blank lines in a row | 2 at module level (1 in a `.pyi` stub), 1 in a nested block | 1 |
136
+
137
+ In Python, an assignment outside every function and class whose target names all have an uppercase
138
+ letter and no lowercase one (`MAX = 3`, `T = TypeVar("T")`, `A, *REST = items`) is a constant, a kind
139
+ apart from other assignments. Imports are never collapsed, because ruff's isort rules separate
140
+ import sections with blank lines. In Rust, the tail expression of a closure, a match arm or a
141
+ `let x = { ... }` block is a value rather than a return, so it stays tight.
142
+
143
+ ## Configuration
144
+
145
+ spacify reads `[tool.spacify]` from `pyproject.toml`, or the top level of a `spacify.toml` or
146
+ `.spacify.toml`, which is the place for a Rust project. It uses the first one it finds walking up from the current directory, or the file
147
+ you pass with `--config`.
148
+
149
+ ```toml
150
+ [tool.spacify]
151
+ extend-exclude = ["generated", "migrations/*.py"] # `exclude = [...]` replaces the defaults
152
+
153
+ languages = ["python", "rust"] # the default: every supported language
154
+
155
+ [tool.spacify.rules]
156
+ blank-before-block = true
157
+ blank-after-block = true
158
+ blank-before-exit = true
159
+ exit-min-block-statements = 3
160
+ keep-paragraphs = true
161
+ collapse-groups = true
162
+
163
+ [tool.spacify.rust.rules] # overrides the shared rules for Rust only
164
+ exit-min-block-statements = 4
165
+ ```
166
+
167
+ An exclude pattern containing a `/` matches the path relative to the config file. Any other pattern
168
+ matches a single file or directory name.
169
+
170
+ ## Contributing
171
+
172
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -0,0 +1,67 @@
1
+ //! Proves spacify preserved meaning: every `.rs` file under <original> has the same token stream as
2
+ //! its copy under <formatted>. A token stream leaves out whitespace and plain comments but keeps
3
+ //! literals and doc comments, which is everything a blank line could change. A file that does not
4
+ //! tokenize must come back byte for byte, since spacify refuses it.
5
+ //!
6
+ //! Usage: cargo run --release --example `tokens_equal` -- <original dir> <formatted dir>
7
+
8
+ use std::path::{Path, PathBuf};
9
+ use std::process::ExitCode;
10
+ use std::{env, fs};
11
+
12
+ use proc_macro2::TokenStream;
13
+
14
+ fn main() -> ExitCode {
15
+ let args: Vec<PathBuf> = env::args_os().skip(1).map(PathBuf::from).collect();
16
+ let [original, formatted] = args.as_slice() else {
17
+ eprintln!("usage: tokens_equal <original dir> <formatted dir>");
18
+ return ExitCode::from(2);
19
+ };
20
+
21
+ let mut files = Vec::new();
22
+ rust_files(original, &mut files);
23
+ files.sort();
24
+
25
+ let mut failures = 0;
26
+ let mut checked = 0;
27
+ for path in &files {
28
+ let relative = path.strip_prefix(original).expect("walked from the original directory");
29
+ let before = fs::read(path).expect("readable original");
30
+ let after = fs::read(formatted.join(relative)).expect("readable formatted copy");
31
+ match (tokens(&before), tokens(&after)) {
32
+ (Some(before), Some(after)) if before == after => checked += 1,
33
+ (None, _) if before == after => {}
34
+ (None, _) => {
35
+ eprintln!("spacify rewrote a file that does not tokenize: {}", relative.display());
36
+ failures += 1;
37
+ }
38
+ _ => {
39
+ eprintln!("spacify changed the tokens of {}", relative.display());
40
+ failures += 1;
41
+ }
42
+ }
43
+ }
44
+
45
+ if failures > 0 {
46
+ return ExitCode::FAILURE;
47
+ }
48
+ println!("spacify kept the tokens of {checked} files");
49
+ ExitCode::SUCCESS
50
+ }
51
+
52
+ fn rust_files(dir: &Path, files: &mut Vec<PathBuf>) {
53
+ for entry in fs::read_dir(dir).expect("readable directory") {
54
+ let path = entry.expect("readable entry").path();
55
+ if path.is_dir() {
56
+ rust_files(&path, files);
57
+ } else if path.extension().is_some_and(|ext| ext == "rs") {
58
+ files.push(path);
59
+ }
60
+ }
61
+ }
62
+
63
+ fn tokens(source: &[u8]) -> Option<String> {
64
+ let source = std::str::from_utf8(source).ok()?;
65
+ let stream: TokenStream = source.parse().ok()?;
66
+ Some(stream.to_string())
67
+ }
@@ -6,12 +6,12 @@ build-backend = "maturin"
6
6
 
7
7
  [project]
8
8
  name = "spacify"
9
- description = "A fast formatter for the vertical rhythm of Python code, complementary to ruff"
9
+ description = "A fast formatter for the vertical rhythm of Python and Rust code, complementary to ruff and rustfmt"
10
10
  readme = "README.md"
11
11
  license = "MIT"
12
12
  license-files = ["LICENSE"]
13
13
  requires-python = ">=3.7"
14
- keywords = ["python", "formatter", "blank-lines", "ruff", "pre-commit"]
14
+ keywords = ["python", "rust", "formatter", "blank-lines", "ruff", "rustfmt", "pre-commit"]
15
15
  classifiers = [
16
16
  "Development Status :: 3 - Alpha",
17
17
  "Environment :: Console",