ruff_python_formatter 0.0.5

This is an internal component crate of Ruff
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use std::fmt;
use std::path::Path;
use std::str::FromStr;

use ruff_formatter::printer::{LineEnding, PrinterOptions, SourceMapGeneration};
use ruff_formatter::{FormatOptions, IndentStyle, IndentWidth, LineWidth};
use ruff_macros::CacheKey;
use ruff_python_ast::{self as ast, PySourceType};

/// Resolved options for formatting one individual file. The difference to `FormatterSettings`
/// is that `FormatterSettings` stores the settings for multiple files (the entire project, a subdirectory, ..)
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct PyFormatOptions {
    /// Whether we're in a `.py` file or `.pyi` file, which have different rules.
    source_type: PySourceType,

    /// The (minimum) Python version used to run the formatted code. This is used
    /// to determine the supported Python syntax.
    target_version: ast::PythonVersion,

    /// Specifies the indent style:
    /// * Either a tab
    /// * or a specific amount of spaces
    #[cfg_attr(feature = "serde", serde(default = "default_indent_style"))]
    indent_style: IndentStyle,

    /// The preferred line width at which the formatter should wrap lines.
    #[cfg_attr(feature = "serde", serde(default = "default_line_width"))]
    line_width: LineWidth,

    /// The visual width of a tab character.
    #[cfg_attr(feature = "serde", serde(default = "default_indent_width"))]
    indent_width: IndentWidth,

    line_ending: LineEnding,

    /// The preferred quote style to use (single vs double quotes).
    quote_style: QuoteStyle,

    /// Whether to expand lists or elements if they have a trailing comma such as `(a, b,)`.
    magic_trailing_comma: MagicTrailingComma,

    /// Should the formatter generate a source map that allows mapping source positions to positions
    /// in the formatted document.
    source_map_generation: SourceMapGeneration,

    /// Whether to format code snippets in docstrings or not.
    ///
    /// By default this is disabled (opt-in), but the plan is to make this
    /// enabled by default (opt-out) in the future.
    docstring_code: DocstringCode,

    /// The preferred line width at which the formatter should wrap lines in
    /// docstring code examples. This only has an impact when `docstring_code`
    /// is enabled.
    docstring_code_line_width: DocstringCodeLineWidth,

    /// Whether preview style formatting is enabled or not
    preview: PreviewMode,

    /// Controls the quote style for nested strings in Python 3.12+.
    ///
    /// When set to `alternating` (default), Ruff will alternate quote styles for nested strings
    /// inside interpolated string expressions. When set to `preferred`, Ruff will use
    /// the configured `quote-style`.
    nested_string_quote_style: NestedStringQuoteStyle,
}

fn default_line_width() -> LineWidth {
    LineWidth::try_from(88).unwrap()
}

fn default_indent_style() -> IndentStyle {
    IndentStyle::Space
}

fn default_indent_width() -> IndentWidth {
    IndentWidth::try_from(4).unwrap()
}

impl Default for PyFormatOptions {
    fn default() -> Self {
        Self {
            source_type: PySourceType::default(),
            target_version: ast::PythonVersion::default(),
            indent_style: default_indent_style(),
            line_width: default_line_width(),
            indent_width: default_indent_width(),
            quote_style: QuoteStyle::default(),
            line_ending: LineEnding::default(),
            magic_trailing_comma: MagicTrailingComma::default(),
            source_map_generation: SourceMapGeneration::default(),
            docstring_code: DocstringCode::default(),
            docstring_code_line_width: DocstringCodeLineWidth::default(),
            preview: PreviewMode::default(),
            nested_string_quote_style: NestedStringQuoteStyle::default(),
        }
    }
}

impl PyFormatOptions {
    /// Otherwise sets the defaults. Returns none if the extension is unknown
    pub fn from_extension(path: &Path) -> Self {
        Self::from_source_type(PySourceType::from(path))
    }

    pub fn from_source_type(source_type: PySourceType) -> Self {
        Self {
            source_type,
            ..Self::default()
        }
    }

    pub const fn target_version(&self) -> ast::PythonVersion {
        self.target_version
    }

    pub const fn magic_trailing_comma(&self) -> MagicTrailingComma {
        self.magic_trailing_comma
    }

    pub const fn quote_style(&self) -> QuoteStyle {
        self.quote_style
    }

    pub const fn source_type(&self) -> PySourceType {
        self.source_type
    }

    pub const fn source_map_generation(&self) -> SourceMapGeneration {
        self.source_map_generation
    }

    pub const fn line_ending(&self) -> LineEnding {
        self.line_ending
    }

    pub const fn docstring_code(&self) -> DocstringCode {
        self.docstring_code
    }

    pub const fn docstring_code_line_width(&self) -> DocstringCodeLineWidth {
        self.docstring_code_line_width
    }

    pub const fn preview(&self) -> PreviewMode {
        self.preview
    }

    pub const fn nested_string_quote_style(&self) -> NestedStringQuoteStyle {
        self.nested_string_quote_style
    }

    #[must_use]
    pub fn with_target_version(mut self, target_version: ast::PythonVersion) -> Self {
        self.target_version = target_version;
        self
    }

    #[must_use]
    pub fn with_indent_width(mut self, indent_width: IndentWidth) -> Self {
        self.indent_width = indent_width;
        self
    }

    #[must_use]
    pub fn with_quote_style(mut self, style: QuoteStyle) -> Self {
        self.quote_style = style;
        self
    }

    #[must_use]
    pub fn with_magic_trailing_comma(mut self, trailing_comma: MagicTrailingComma) -> Self {
        self.magic_trailing_comma = trailing_comma;
        self
    }

    #[must_use]
    pub fn with_indent_style(mut self, indent_style: IndentStyle) -> Self {
        self.indent_style = indent_style;
        self
    }

    #[must_use]
    pub fn with_line_width(mut self, line_width: LineWidth) -> Self {
        self.line_width = line_width;
        self
    }

    #[must_use]
    pub fn with_line_ending(mut self, line_ending: LineEnding) -> Self {
        self.line_ending = line_ending;
        self
    }

    #[must_use]
    pub fn with_docstring_code(mut self, docstring_code: DocstringCode) -> Self {
        self.docstring_code = docstring_code;
        self
    }

    #[must_use]
    pub fn with_docstring_code_line_width(mut self, line_width: DocstringCodeLineWidth) -> Self {
        self.docstring_code_line_width = line_width;
        self
    }

    #[must_use]
    pub fn with_preview(mut self, preview: PreviewMode) -> Self {
        self.preview = preview;
        self
    }

    #[must_use]
    pub fn with_nested_string_quote_style(
        mut self,
        nested_string_quote_style: NestedStringQuoteStyle,
    ) -> Self {
        self.nested_string_quote_style = nested_string_quote_style;
        self
    }

    #[must_use]
    pub fn with_source_map_generation(mut self, source_map: SourceMapGeneration) -> Self {
        self.source_map_generation = source_map;
        self
    }
}

impl FormatOptions for PyFormatOptions {
    fn indent_style(&self) -> IndentStyle {
        self.indent_style
    }

    fn indent_width(&self) -> IndentWidth {
        self.indent_width
    }

    fn line_width(&self) -> LineWidth {
        self.line_width
    }

    fn as_print_options(&self) -> PrinterOptions {
        PrinterOptions {
            indent_width: self.indent_width,
            line_width: self.line_width,
            line_ending: self.line_ending,
            indent_style: self.indent_style,
        }
    }
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, CacheKey)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum QuoteStyle {
    Single,
    #[default]
    Double,
    Preserve,
}

impl QuoteStyle {
    pub const fn is_preserve(self) -> bool {
        matches!(self, QuoteStyle::Preserve)
    }

    /// Returns the string representation of the quote style.
    pub const fn as_str(&self) -> &'static str {
        match self {
            QuoteStyle::Single => "single",
            QuoteStyle::Double => "double",
            QuoteStyle::Preserve => "preserve",
        }
    }
}

impl fmt::Display for QuoteStyle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for QuoteStyle {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "\"" | "double" | "Double" => Ok(Self::Double),
            "'" | "single" | "Single" => Ok(Self::Single),
            "preserve" | "Preserve" => Ok(Self::Preserve),
            // TODO: replace this error with a diagnostic
            _ => Err("Value not supported for QuoteStyle"),
        }
    }
}

#[derive(Copy, Clone, Debug, Default, CacheKey)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
pub enum MagicTrailingComma {
    #[default]
    Respect,
    Ignore,
}

impl MagicTrailingComma {
    pub const fn is_respect(self) -> bool {
        matches!(self, Self::Respect)
    }

    pub const fn is_ignore(self) -> bool {
        matches!(self, Self::Ignore)
    }
}

impl fmt::Display for MagicTrailingComma {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            MagicTrailingComma::Respect => "respect",
            MagicTrailingComma::Ignore => "ignore",
        })
    }
}

impl FromStr for MagicTrailingComma {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "respect" | "Respect" => Ok(Self::Respect),
            "ignore" | "Ignore" => Ok(Self::Ignore),
            // TODO: replace this error with a diagnostic
            _ => Err("Value not supported for MagicTrailingComma"),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, CacheKey)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum PreviewMode {
    #[default]
    Disabled,

    Enabled,
}

impl PreviewMode {
    pub const fn is_enabled(self) -> bool {
        matches!(self, PreviewMode::Enabled)
    }
}

impl fmt::Display for PreviewMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Disabled => write!(f, "disabled"),
            Self::Enabled => write!(f, "enabled"),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, CacheKey)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum NestedStringQuoteStyle {
    #[default]
    Alternating,
    Preferred,
}

impl NestedStringQuoteStyle {
    pub const fn is_preferred(self) -> bool {
        matches!(self, NestedStringQuoteStyle::Preferred)
    }
}

impl fmt::Display for NestedStringQuoteStyle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Alternating => write!(f, "alternating"),
            Self::Preferred => write!(f, "preferred"),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Default, CacheKey)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum DocstringCode {
    #[default]
    Disabled,

    Enabled,
}

impl DocstringCode {
    pub const fn is_enabled(self) -> bool {
        matches!(self, DocstringCode::Enabled)
    }
}

impl fmt::Display for DocstringCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Disabled => write!(f, "disabled"),
            Self::Enabled => write!(f, "enabled"),
        }
    }
}

#[derive(Copy, Clone, Default, Eq, PartialEq, CacheKey)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(untagged, rename_all = "lowercase")
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum DocstringCodeLineWidth {
    /// Wrap docstring code examples at a fixed line width.
    #[cfg_attr(feature = "schemars", schemars(schema_with = "schema::fixed"))]
    Fixed(LineWidth),

    /// Respect the line length limit setting for the surrounding Python code.
    #[default]
    #[cfg_attr(
        feature = "serde",
        serde(deserialize_with = "deserialize_docstring_code_line_width_dynamic")
    )]
    #[cfg_attr(feature = "schemars", schemars(schema_with = "schema::dynamic"))]
    Dynamic,
}

#[cfg(feature = "schemars")]
mod schema {
    use ruff_formatter::LineWidth;
    use schemars::{Schema, SchemaGenerator};
    use serde_json::Value;

    /// A dummy type that is used to generate a schema for `DocstringCodeLineWidth::Dynamic`.
    pub(super) fn dynamic(_: &mut SchemaGenerator) -> Schema {
        schemars::json_schema!({ "const": "dynamic" })
    }

    // We use a manual schema for `fixed` even thought it isn't strictly necessary according to the
    // JSON schema specification to work around a bug in Even Better TOML with `allOf`.
    // https://github.com/astral-sh/ruff/issues/15978#issuecomment-2639547101
    //
    // The only difference to the automatically derived schema is that we use `oneOf` instead of
    // `allOf`. There's no semantic difference between `allOf` and `oneOf` for single element lists.
    pub(super) fn fixed(generator: &mut SchemaGenerator) -> Schema {
        let schema = generator.subschema_for::<LineWidth>();
        let mut schema_object = Schema::default();
        let map = schema_object.ensure_object();
        map.insert(
            "description".to_string(),
            Value::String("Wrap docstring code examples at a fixed line width.".to_string()),
        );
        map.insert("oneOf".to_string(), Value::Array(vec![schema.into()]));
        schema_object
    }
}

impl fmt::Debug for DocstringCodeLineWidth {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DocstringCodeLineWidth::Fixed(v) => v.value().fmt(f),
            DocstringCodeLineWidth::Dynamic => "dynamic".fmt(f),
        }
    }
}

impl fmt::Display for DocstringCodeLineWidth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Fixed(width) => width.fmt(f),
            Self::Dynamic => write!(f, "dynamic"),
        }
    }
}

/// Responsible for deserializing the `DocstringCodeLineWidth::Dynamic`
/// variant.
fn deserialize_docstring_code_line_width_dynamic<'de, D>(d: D) -> Result<(), D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::{Deserialize, de::Error};

    let value = String::deserialize(d)?;
    match &*value {
        "dynamic" => Ok(()),
        s => Err(D::Error::invalid_value(
            serde::de::Unexpected::Str(s),
            &"dynamic",
        )),
    }
}