spacify 0.2.0__tar.gz → 0.2.1__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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.1](https://github.com/avanserv/spacify/compare/v0.2.0...v0.2.1) (2026-10-27)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * Report bare carriage return line endings honestly ([#9](https://github.com/avanserv/spacify/issues/9)) ([b84f9a7](https://github.com/avanserv/spacify/commit/b84f9a78c9f0555563bc52e293d7151a346aa786))
9
+
3
10
  ## [0.2.0](https://github.com/avanserv/spacify/compare/v0.1.1...v0.2.0) (2026-10-19)
4
11
 
5
12
 
@@ -55,8 +55,12 @@ files from the current output, then review the diff:
55
55
  SPACIFY_BLESS=1 cargo test --test fixtures
56
56
  ```
57
57
 
58
- `make compat` is the check that matters for ruff: both orders, over the fixtures and CPython.
59
- `make bench` times a check over CPython's `Lib` with hyperfine.
58
+ Unit tests for a module's internals sit in a `tests` module at the bottom of its file.
59
+
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
63
+ check over CPython's `Lib` with hyperfine.
60
64
 
61
65
  ## Commits and pull requests
62
66
 
@@ -502,7 +502,7 @@ dependencies = [
502
502
 
503
503
  [[package]]
504
504
  name = "spacify"
505
- version = "0.2.0"
505
+ version = "0.2.1"
506
506
  dependencies = [
507
507
  "anyhow",
508
508
  "clap",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "spacify"
3
- version = "0.2.0"
3
+ version = "0.2.1"
4
4
  edition = "2024"
5
5
  rust-version = "1.85"
6
6
  description = "A fast formatter for the vertical rhythm of Python code, complementary to ruff"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spacify
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Environment :: Console
6
6
  Classifier: Intended Audience :: Developers
@@ -61,9 +61,10 @@ def load(paths):
61
61
  return total
62
62
  ```
63
63
 
64
- spacify never fights ruff. Every rule stays inside the blank-line bounds `ruff format` keeps, and
65
- CI runs both tools over CPython's standard library in both orders to check they reach a fixed point.
66
- Checking all of CPython's `Lib` takes under half a second on 8 cores.
64
+ spacify never fights ruff. Every rule stays inside the blank-line bounds `ruff format` keeps, and CI
65
+ runs both tools over CPython's standard library in both orders to check they reach a fixed point. It
66
+ also checks that spacify leaves the AST of every file unchanged. Checking CPython's `Lib`, without
67
+ its tests, takes under half a second on 8 cores.
67
68
 
68
69
  ## Install
69
70
 
@@ -104,6 +105,15 @@ a syntax error, in which case the file is left untouched. Directory walks respec
104
105
  skip the directories ruff skips by default. A file you name explicitly is always formatted, unless
105
106
  you also pass `--force-exclude`, which is what the hook does.
106
107
 
108
+ ## Known limits
109
+
110
+ spacify parses with tree-sitter-python, which rejects a few valid constructs: type parameter
111
+ defaults (`def f[T = int]()`, PEP 696), a parenthesised starred subscript (`a[*(b)]`), and an
112
+ attribute access broken after its dot onto a line indented less than the statement. A file using one
113
+ exits 2 and is left untouched. Files must be UTF-8, as for ruff, and line endings that are a bare
114
+ `\r` are refused the same way. Python 2 `print` and `exec` statements are not rejected, since
115
+ tree-sitter cannot tell some of them from valid Python 3 such as `print >>f, x`.
116
+
107
117
  ## Rules
108
118
 
109
119
  Each rule can be turned on or off. They all apply to sibling statements in the same block.
@@ -43,9 +43,10 @@ def load(paths):
43
43
  return total
44
44
  ```
45
45
 
46
- spacify never fights ruff. Every rule stays inside the blank-line bounds `ruff format` keeps, and
47
- CI runs both tools over CPython's standard library in both orders to check they reach a fixed point.
48
- Checking all of CPython's `Lib` takes under half a second on 8 cores.
46
+ spacify never fights ruff. Every rule stays inside the blank-line bounds `ruff format` keeps, and CI
47
+ runs both tools over CPython's standard library in both orders to check they reach a fixed point. It
48
+ also checks that spacify leaves the AST of every file unchanged. Checking CPython's `Lib`, without
49
+ its tests, takes under half a second on 8 cores.
49
50
 
50
51
  ## Install
51
52
 
@@ -86,6 +87,15 @@ a syntax error, in which case the file is left untouched. Directory walks respec
86
87
  skip the directories ruff skips by default. A file you name explicitly is always formatted, unless
87
88
  you also pass `--force-exclude`, which is what the hook does.
88
89
 
90
+ ## Known limits
91
+
92
+ spacify parses with tree-sitter-python, which rejects a few valid constructs: type parameter
93
+ defaults (`def f[T = int]()`, PEP 696), a parenthesised starred subscript (`a[*(b)]`), and an
94
+ attribute access broken after its dot onto a line indented less than the statement. A file using one
95
+ exits 2 and is left untouched. Files must be UTF-8, as for ruff, and line endings that are a bare
96
+ `\r` are refused the same way. Python 2 `print` and `exec` statements are not rejected, since
97
+ tree-sitter cannot tell some of them from valid Python 3 such as `print >>f, x`.
98
+
89
99
  ## Rules
90
100
 
91
101
  Each rule can be turned on or off. They all apply to sibling statements in the same block.
@@ -37,3 +37,44 @@ pub fn apply(source: &str, edits: &mut [Edit]) -> String {
37
37
 
38
38
  out
39
39
  }
40
+
41
+ #[cfg(test)]
42
+ mod tests {
43
+ use super::*;
44
+
45
+ fn edit(row: usize, current: usize, desired: usize) -> Edit {
46
+ Edit { row, current, desired }
47
+ }
48
+
49
+ #[test]
50
+ fn inserts_into_an_empty_run() {
51
+ assert_eq!(apply("a\nb\n", &mut [edit(1, 0, 1)]), "a\n\nb\n");
52
+ }
53
+
54
+ #[test]
55
+ fn shrinks_a_run_to_nothing() {
56
+ assert_eq!(apply("a\n\n\nb\n", &mut [edit(3, 2, 0)]), "a\nb\n");
57
+ }
58
+
59
+ #[test]
60
+ fn shrinks_a_run_from_its_top() {
61
+ assert_eq!(apply("a\n\n \nb\n", &mut [edit(3, 2, 1)]), "a\n \nb\n");
62
+ }
63
+
64
+ #[test]
65
+ fn applies_edits_given_out_of_order() {
66
+ let mut edits = [edit(4, 1, 0), edit(1, 0, 1)];
67
+ assert_eq!(apply("a\nb\nc\n\nd\n", &mut edits), "a\n\nb\nc\nd\n");
68
+ }
69
+
70
+ #[test]
71
+ fn inserts_crlf_into_a_crlf_file() {
72
+ assert_eq!(apply("a\r\nb\r\n", &mut [edit(1, 0, 2)]), "a\r\n\r\n\r\nb\r\n");
73
+ }
74
+
75
+ #[test]
76
+ fn edits_above_a_last_line_without_a_newline() {
77
+ assert_eq!(apply("a\n\n\nb", &mut [edit(3, 2, 1)]), "a\n\nb");
78
+ assert_eq!(apply("a\nb", &mut [edit(1, 0, 1)]), "a\n\nb");
79
+ }
80
+ }
@@ -23,6 +23,8 @@ thread_local! {
23
23
  pub enum FormatError {
24
24
  /// One-based line of the first syntax error.
25
25
  Syntax(usize),
26
+ /// A line ending that is a `\r` alone, which Python accepts and the parser does not.
27
+ LoneCarriageReturn,
26
28
  Parse,
27
29
  }
28
30
 
@@ -30,6 +32,9 @@ impl fmt::Display for FormatError {
30
32
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31
33
  match self {
32
34
  Self::Syntax(line) => write!(f, "syntax error on line {line}"),
35
+ Self::LoneCarriageReturn => f.write_str(
36
+ "line endings that are a bare carriage return are not supported: convert the file to \\n or \\r\\n",
37
+ ),
33
38
  Self::Parse => f.write_str("the parser gave up on this file"),
34
39
  }
35
40
  }
@@ -40,6 +45,10 @@ impl std::error::Error for FormatError {}
40
45
  /// Formats Python `source`, returning `None` when it is already formatted. A `stub` (`.pyi`) gets
41
46
  /// ruff's stub ceiling of one blank line at module level.
42
47
  pub fn format_source(source: &str, rules: &Rules, stub: bool) -> Result<Option<String>, FormatError> {
48
+ if source.split("\r\n").any(|part| part.contains('\r')) {
49
+ return Err(FormatError::LoneCarriageReturn);
50
+ }
51
+
43
52
  let tree = PARSER
44
53
  .with_borrow_mut(|parser| parser.parse(source, None))
45
54
  .ok_or(FormatError::Parse)?;
@@ -321,3 +330,52 @@ fn disabled_prefix(lines: &[&str]) -> Vec<u32> {
321
330
  prefix.push(total);
322
331
  prefix
323
332
  }
333
+
334
+ #[cfg(test)]
335
+ mod tests {
336
+ use super::*;
337
+
338
+ #[test]
339
+ fn constant_names_have_an_uppercase_letter_and_no_lowercase_one() {
340
+ for name in ["MAX", "_A1", "ÉTÉ", "T", "__ALL__"] {
341
+ assert!(is_constant_name(name), "{name}");
342
+ }
343
+ for name in ["_", "_1", "Max", "__all__", "maxValue"] {
344
+ assert!(!is_constant_name(name), "{name}");
345
+ }
346
+ }
347
+
348
+ #[test]
349
+ fn fmt_skip_is_found_in_any_spacing_and_after_other_comments() {
350
+ assert!(has_fmt_skip("x = 1 # fmt: skip\n"));
351
+ assert!(has_fmt_skip("x = 1 #fmt:skip\n"));
352
+ assert!(has_fmt_skip("x = 1 # noqa: E501 # fmt: skip\n"));
353
+ assert!(!has_fmt_skip("x = 1 # fmt: off\n"));
354
+ assert!(!has_fmt_skip("x = 1\n"));
355
+ }
356
+
357
+ #[test]
358
+ fn directives_ignore_whitespace() {
359
+ assert_eq!(directive(" # fmt: off\n").as_deref(), Some("fmt:off"));
360
+ assert_eq!(directive("#spacify:on").as_deref(), Some("spacify:on"));
361
+ assert_eq!(directive("x = 1 # fmt: off\n"), None);
362
+ }
363
+
364
+ #[test]
365
+ fn disabled_regions_count_their_markers() {
366
+ let lines = ["a\n", "# fmt: off\n", "b\n", "# fmt: on\n", "c\n"];
367
+ assert_eq!(disabled_prefix(&lines), [0, 0, 1, 2, 3, 3, 3]);
368
+ }
369
+
370
+ #[test]
371
+ fn an_unterminated_region_runs_to_the_end() {
372
+ let lines = ["a\n", "# spacify: off\n", "b\n"];
373
+ assert_eq!(disabled_prefix(&lines), [0, 0, 1, 2, 2]);
374
+ }
375
+
376
+ #[test]
377
+ fn an_on_marker_alone_disables_only_itself() {
378
+ let lines = ["a\n", "# fmt: on\n", "b\n"];
379
+ assert_eq!(disabled_prefix(&lines), [0, 0, 1, 1, 1]);
380
+ }
381
+ }
@@ -0,0 +1,241 @@
1
+ use crate::config::Rules;
2
+
3
+ /// What a statement is, as far as vertical rhythm cares.
4
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
+ pub enum Kind {
6
+ /// `if`, `for`, `while`, `try`, `with`, `match`, in their `async` forms too.
7
+ Compound,
8
+ /// `def` and `class`, decorated or not. Ruff owns every gap around these.
9
+ Definition,
10
+ /// `return`, `raise`, `break`, `continue` and a bare `yield`.
11
+ Exit,
12
+ /// Never collapsed: ruff's isort rules separate import sections with blank lines.
13
+ Import,
14
+ Simple(Group),
15
+ Other,
16
+ }
17
+
18
+ /// Simple statements that read as one paragraph when they follow each other.
19
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20
+ pub enum Group {
21
+ Assign,
22
+ /// An assignment to `UPPER_CASE` names outside every function and class: configuration, which
23
+ /// reads apart from the statements setting the module up, such as `logger = getLogger(__name__)`.
24
+ Constant,
25
+ AugAssign,
26
+ Call,
27
+ Del,
28
+ Assert,
29
+ Scope,
30
+ }
31
+
32
+ /// The space between two sibling statements of one block.
33
+ #[derive(Debug, Clone, Copy)]
34
+ pub struct Gap {
35
+ pub prev: Kind,
36
+ pub next: Kind,
37
+ /// Blank lines directly above the next statement and the comments attached to it.
38
+ pub blank: usize,
39
+ pub has_comment: bool,
40
+ pub both_single_line: bool,
41
+ pub block_len: usize,
42
+ /// Ruff's ceiling for this level: 2 at module level (1 in a stub), 1 in a nested block.
43
+ pub max: usize,
44
+ }
45
+
46
+ /// The blank-line count `gap` should have, or `None` when no rule has an opinion on it. Rules that
47
+ /// add a line win over the one that removes lines, and nothing ever exceeds ruff's ceiling.
48
+ pub fn desired(gap: &Gap, rules: &Rules) -> Option<usize> {
49
+ if blank_before_block(gap, rules) || blank_after_block(gap, rules) || blank_before_exit(gap, rules) {
50
+ return Some(gap.blank.clamp(1, gap.max));
51
+ }
52
+
53
+ if collapse_groups(gap, rules) {
54
+ return Some(0);
55
+ }
56
+
57
+ None
58
+ }
59
+
60
+ fn blank_before_block(gap: &Gap, rules: &Rules) -> bool {
61
+ rules.blank_before_block && gap.next == Kind::Compound
62
+ }
63
+
64
+ fn blank_after_block(gap: &Gap, rules: &Rules) -> bool {
65
+ rules.blank_after_block && gap.prev == Kind::Compound
66
+ }
67
+
68
+ fn blank_before_exit(gap: &Gap, rules: &Rules) -> bool {
69
+ rules.blank_before_exit && gap.next == Kind::Exit && gap.block_len >= rules.exit_min_block_statements
70
+ }
71
+
72
+ /// A comment in the gap marks a paragraph the author meant, and a multi-line statement reads
73
+ /// better with air around it, so both keep their blank line.
74
+ fn collapse_groups(gap: &Gap, rules: &Rules) -> bool {
75
+ rules.collapse_groups
76
+ && gap.blank > 0
77
+ && !gap.has_comment
78
+ && gap.both_single_line
79
+ && matches!((gap.prev, gap.next), (Kind::Simple(a), Kind::Simple(b)) if a == b)
80
+ }
81
+
82
+ #[cfg(test)]
83
+ mod tests {
84
+ use super::*;
85
+
86
+ /// Two single-line assignments in a nested block, two blank lines apart: a gap each rule can
87
+ /// be pointed at by changing a field or two.
88
+ fn gap() -> Gap {
89
+ Gap {
90
+ prev: Kind::Simple(Group::Assign),
91
+ next: Kind::Simple(Group::Assign),
92
+ blank: 2,
93
+ has_comment: false,
94
+ both_single_line: true,
95
+ block_len: 5,
96
+ max: 1,
97
+ }
98
+ }
99
+
100
+ fn desired_default(gap: &Gap) -> Option<usize> {
101
+ desired(gap, &Rules::default())
102
+ }
103
+
104
+ #[test]
105
+ fn added_lines_stay_between_one_and_the_ceiling() {
106
+ let before_block = |blank, max| {
107
+ desired_default(&Gap {
108
+ next: Kind::Compound,
109
+ blank,
110
+ max,
111
+ ..gap()
112
+ })
113
+ };
114
+ assert_eq!(before_block(0, 1), Some(1));
115
+ assert_eq!(before_block(3, 1), Some(1));
116
+ assert_eq!(before_block(0, 2), Some(1));
117
+ assert_eq!(before_block(2, 2), Some(2));
118
+ assert_eq!(before_block(5, 2), Some(2));
119
+ }
120
+
121
+ #[test]
122
+ fn blank_after_block_follows_any_compound() {
123
+ let after = Gap {
124
+ prev: Kind::Compound,
125
+ next: Kind::Other,
126
+ blank: 0,
127
+ ..gap()
128
+ };
129
+ assert_eq!(desired_default(&after), Some(1));
130
+ }
131
+
132
+ #[test]
133
+ fn blank_before_exit_starts_at_the_threshold() {
134
+ let exit = |block_len| {
135
+ desired_default(&Gap {
136
+ next: Kind::Exit,
137
+ blank: 0,
138
+ block_len,
139
+ ..gap()
140
+ })
141
+ };
142
+ assert_eq!(exit(2), None);
143
+ assert_eq!(exit(3), Some(1));
144
+ }
145
+
146
+ #[test]
147
+ fn collapse_needs_every_condition() {
148
+ assert_eq!(desired_default(&gap()), Some(0));
149
+ assert_eq!(desired_default(&Gap { blank: 0, ..gap() }), None);
150
+ assert_eq!(
151
+ desired_default(&Gap {
152
+ has_comment: true,
153
+ ..gap()
154
+ }),
155
+ None
156
+ );
157
+ assert_eq!(
158
+ desired_default(&Gap {
159
+ both_single_line: false,
160
+ ..gap()
161
+ }),
162
+ None
163
+ );
164
+ assert_eq!(
165
+ desired_default(&Gap {
166
+ next: Kind::Simple(Group::Call),
167
+ ..gap()
168
+ }),
169
+ None
170
+ );
171
+ }
172
+
173
+ #[test]
174
+ fn constants_do_not_collapse_into_assignments() {
175
+ let constant_then_assign = Gap {
176
+ prev: Kind::Simple(Group::Constant),
177
+ ..gap()
178
+ };
179
+ assert_eq!(desired_default(&constant_then_assign), None);
180
+ let constants = Gap {
181
+ prev: Kind::Simple(Group::Constant),
182
+ next: Kind::Simple(Group::Constant),
183
+ ..gap()
184
+ };
185
+ assert_eq!(desired_default(&constants), Some(0));
186
+ }
187
+
188
+ #[test]
189
+ fn definitions_imports_and_others_get_no_opinion() {
190
+ for kind in [Kind::Definition, Kind::Import, Kind::Other] {
191
+ assert_eq!(
192
+ desired_default(&Gap {
193
+ prev: kind,
194
+ next: kind,
195
+ ..gap()
196
+ }),
197
+ None,
198
+ "{kind:?}"
199
+ );
200
+ }
201
+ }
202
+
203
+ #[test]
204
+ fn each_toggle_disables_only_its_rule() {
205
+ let before_block = Gap {
206
+ next: Kind::Compound,
207
+ blank: 0,
208
+ ..gap()
209
+ };
210
+ let after_block = Gap {
211
+ prev: Kind::Compound,
212
+ blank: 0,
213
+ ..gap()
214
+ };
215
+ let before_exit = Gap {
216
+ next: Kind::Exit,
217
+ blank: 0,
218
+ ..gap()
219
+ };
220
+ let collapse = gap();
221
+ let all = [before_block, after_block, before_exit, collapse];
222
+ let toggles: [fn(&mut Rules); 4] = [
223
+ |rules| rules.blank_before_block = false,
224
+ |rules| rules.blank_after_block = false,
225
+ |rules| rules.blank_before_exit = false,
226
+ |rules| rules.collapse_groups = false,
227
+ ];
228
+
229
+ for (off, toggle) in toggles.iter().enumerate() {
230
+ let mut rules = Rules::default();
231
+ toggle(&mut rules);
232
+ for (index, gap) in all.iter().enumerate() {
233
+ assert_eq!(
234
+ desired(gap, &rules).is_none(),
235
+ index == off,
236
+ "toggle {off} on gap {index}"
237
+ );
238
+ }
239
+ }
240
+ }
241
+ }
@@ -81,6 +81,16 @@ fn syntax_error_exits_2() {
81
81
  assert!(String::from_utf8_lossy(&output.stderr).contains("syntax error on line 1"));
82
82
  }
83
83
 
84
+ #[test]
85
+ fn lone_carriage_returns_exit_2_untouched() {
86
+ let source = "x = 1\rif x:\r pass\r";
87
+ let dir = project(&[("a.py", source)]);
88
+ let output = spacify(&dir, &[], None);
89
+ assert_eq!(output.status.code(), Some(2));
90
+ assert!(String::from_utf8_lossy(&output.stderr).contains("bare carriage return"));
91
+ assert_eq!(fs::read_to_string(dir.path().join("a.py")).unwrap(), source);
92
+ }
93
+
84
94
  #[test]
85
95
  fn skips_default_excludes_when_walking() {
86
96
  let dir = project(&[(".venv/lib/a.py", UNFORMATTED), ("build/b.py", UNFORMATTED)]);
@@ -96,3 +96,75 @@ fn exit_threshold_is_configurable() {
96
96
  let formatted = format_source(source, &rules, false).unwrap().unwrap();
97
97
  assert_eq!(formatted, "def f(x):\n x = 1\n\n return x\n");
98
98
  }
99
+
100
+ #[test]
101
+ fn keeps_a_byte_order_mark() {
102
+ let source = "\u{feff}x = 1\nif x:\n pass\n";
103
+ let formatted = format_source(source, &Rules::default(), false).unwrap().unwrap();
104
+ assert_eq!(formatted, "\u{feff}x = 1\n\nif x:\n pass\n");
105
+ }
106
+
107
+ #[test]
108
+ fn indents_with_tabs() {
109
+ let source = "def f(x):\n\ty = 1\n\tif y:\n\t\tpass\n\treturn y\n";
110
+ let formatted = format_source(source, &Rules::default(), false).unwrap().unwrap();
111
+ assert_eq!(formatted, "def f(x):\n\ty = 1\n\n\tif y:\n\t\tpass\n\n\treturn y\n");
112
+ }
113
+
114
+ /// Ruff drops a form feed and keeps its line as a blank one, so spacify counts it as blank too.
115
+ #[test]
116
+ fn counts_a_form_feed_line_as_blank() {
117
+ let source = "x = 1\n\x0c\nif x:\n pass\n";
118
+ assert_eq!(format_source(source, &Rules::default(), false).unwrap(), None);
119
+ let source = "x = 1\n\x0cif x:\n pass\n";
120
+ let formatted = format_source(source, &Rules::default(), false).unwrap().unwrap();
121
+ assert_eq!(formatted, "x = 1\n\n\x0cif x:\n pass\n");
122
+ }
123
+
124
+ #[test]
125
+ fn leaves_empty_and_comment_only_files_alone() {
126
+ for source in ["", "\n", "# a\n\n\n# b\n"] {
127
+ assert_eq!(
128
+ format_source(source, &Rules::default(), false).unwrap(),
129
+ None,
130
+ "{source:?}"
131
+ );
132
+ }
133
+ }
134
+
135
+ /// Tree-sitter reads this as a Python 2 print statement, but it is a valid Python 3 tuple, so
136
+ /// spacify formats around it rather than refusing it.
137
+ #[test]
138
+ fn formats_around_a_print_chevron() {
139
+ let source = "print >>f, \"a\"\nif f:\n pass\n";
140
+ let formatted = format_source(source, &Rules::default(), false).unwrap().unwrap();
141
+ assert_eq!(formatted, "print >>f, \"a\"\n\nif f:\n pass\n");
142
+ }
143
+
144
+ /// Valid since Python 3.13 (PEP 696), but tree-sitter-python rejects it. A grammar upgrade that
145
+ /// fails this test lifts the limit: update `README.md` and the Makefile's `CPYTHON_SKIP`.
146
+ #[test]
147
+ fn refuses_type_parameter_defaults() {
148
+ for source in [
149
+ "def f[T = int](): pass\n",
150
+ "class C[T = int]: pass\n",
151
+ "type A[T = int] = T\n",
152
+ ] {
153
+ assert_eq!(
154
+ format_source(source, &Rules::default(), false),
155
+ Err(FormatError::Syntax(1)),
156
+ "{source:?}"
157
+ );
158
+ }
159
+ }
160
+
161
+ #[test]
162
+ fn refuses_lone_carriage_returns() {
163
+ for source in ["x = 1\rif x:\r pass\r", "x = 1\r\ny = '''\r'''\r\n"] {
164
+ assert_eq!(
165
+ format_source(source, &Rules::default(), false),
166
+ Err(FormatError::LoneCarriageReturn),
167
+ "{source:?}"
168
+ );
169
+ }
170
+ }
@@ -1,80 +0,0 @@
1
- use crate::config::Rules;
2
-
3
- /// What a statement is, as far as vertical rhythm cares.
4
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
- pub enum Kind {
6
- /// `if`, `for`, `while`, `try`, `with`, `match`, in their `async` forms too.
7
- Compound,
8
- /// `def` and `class`, decorated or not. Ruff owns every gap around these.
9
- Definition,
10
- /// `return`, `raise`, `break`, `continue` and a bare `yield`.
11
- Exit,
12
- /// Never collapsed: ruff's isort rules separate import sections with blank lines.
13
- Import,
14
- Simple(Group),
15
- Other,
16
- }
17
-
18
- /// Simple statements that read as one paragraph when they follow each other.
19
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20
- pub enum Group {
21
- Assign,
22
- /// An assignment to `UPPER_CASE` names outside every function and class: configuration, which
23
- /// reads apart from the statements setting the module up, such as `logger = getLogger(__name__)`.
24
- Constant,
25
- AugAssign,
26
- Call,
27
- Del,
28
- Assert,
29
- Scope,
30
- }
31
-
32
- /// The space between two sibling statements of one block.
33
- #[derive(Debug, Clone, Copy)]
34
- pub struct Gap {
35
- pub prev: Kind,
36
- pub next: Kind,
37
- /// Blank lines directly above the next statement and the comments attached to it.
38
- pub blank: usize,
39
- pub has_comment: bool,
40
- pub both_single_line: bool,
41
- pub block_len: usize,
42
- /// Ruff's ceiling for this level: 2 at module level (1 in a stub), 1 in a nested block.
43
- pub max: usize,
44
- }
45
-
46
- /// The blank-line count `gap` should have, or `None` when no rule has an opinion on it. Rules that
47
- /// add a line win over the one that removes lines, and nothing ever exceeds ruff's ceiling.
48
- pub fn desired(gap: &Gap, rules: &Rules) -> Option<usize> {
49
- if blank_before_block(gap, rules) || blank_after_block(gap, rules) || blank_before_exit(gap, rules) {
50
- return Some(gap.blank.clamp(1, gap.max));
51
- }
52
-
53
- if collapse_groups(gap, rules) {
54
- return Some(0);
55
- }
56
-
57
- None
58
- }
59
-
60
- fn blank_before_block(gap: &Gap, rules: &Rules) -> bool {
61
- rules.blank_before_block && gap.next == Kind::Compound
62
- }
63
-
64
- fn blank_after_block(gap: &Gap, rules: &Rules) -> bool {
65
- rules.blank_after_block && gap.prev == Kind::Compound
66
- }
67
-
68
- fn blank_before_exit(gap: &Gap, rules: &Rules) -> bool {
69
- rules.blank_before_exit && gap.next == Kind::Exit && gap.block_len >= rules.exit_min_block_statements
70
- }
71
-
72
- /// A comment in the gap marks a paragraph the author meant, and a multi-line statement reads
73
- /// better with air around it, so both keep their blank line.
74
- fn collapse_groups(gap: &Gap, rules: &Rules) -> bool {
75
- rules.collapse_groups
76
- && gap.blank > 0
77
- && !gap.has_comment
78
- && gap.both_single_line
79
- && matches!((gap.prev, gap.next), (Kind::Simple(a), Kind::Simple(b)) if a == b)
80
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes