Skip to content

Commit

Permalink
Rename *-length options to -width
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Oct 17, 2023
1 parent 366d2be commit ba61b69
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 35 deletions.
22 changes: 17 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions crates/flake8_to_ruff/src/converter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ pub(crate) fn convert(
options.builtins = Some(parser::parse_strings(value.as_ref()));
}
"max-line-length" | "max_line_length" => match LineLength::from_str(value) {
Ok(line_length) => options.line_length = Some(line_length),
Ok(line_length) => options.line_width = Some(line_length),
Err(e) => {
warn_user!("Unable to parse '{key}' property: {e}");
}
Expand Down Expand Up @@ -401,7 +401,7 @@ pub(crate) fn convert(
// Extract any settings from the existing `pyproject.toml`.
if let Some(black) = &external_config.black {
if let Some(line_length) = &black.line_length {
options.line_length = Some(*line_length);
options.line_width = Some(*line_length);
}

if let Some(target_version) = &black.target_version {
Expand Down Expand Up @@ -523,7 +523,7 @@ mod tests {
Some(vec![]),
);
let expected = Pyproject::new(Options {
line_length: Some(LineLength::try_from(100).unwrap()),
line_width: Some(LineLength::try_from(100).unwrap()),
lint: Some(LintOptions {
common: lint_default_options([]),
..LintOptions::default()
Expand All @@ -544,7 +544,7 @@ mod tests {
Some(vec![]),
);
let expected = Pyproject::new(Options {
line_length: Some(LineLength::try_from(100).unwrap()),
line_width: Some(LineLength::try_from(100).unwrap()),
lint: Some(LintOptions {
common: lint_default_options([]),
..LintOptions::default()
Expand Down
15 changes: 15 additions & 0 deletions crates/ruff_dev/src/generate_options.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Generate a Markdown-compatible listing of configuration options for `pyproject.toml`.
//!
//! Used for <https://docs.astral.sh/ruff/settings/>.
use itertools::Itertools;
use std::fmt::Write;

use ruff_workspace::options::Options;
Expand Down Expand Up @@ -107,6 +108,20 @@ fn emit_field(output: &mut String, name: &str, field: &OptionField, parent_set:
output.push('\n');
output.push_str(&format!("**Type**: `{}`\n", field.value_type));
output.push('\n');

if !field.aliases.is_empty() {
let title = if field.aliases.len() == 1 {
"Alias"
} else {
"Aliases"
};
output.push_str(&format!(
"**{title}**: `{}`\n",
field.aliases.iter().join(",")
));
output.push('\n');
}

output.push_str(&format!(
"**Example usage**:\n\n```toml\n[tool.ruff{}]\n{}\n```\n",
if let Some(set_name) = parent_set.name() {
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ doctest = false

[dependencies]
ruff_python_trivia = { path = "../ruff_python_trivia" }
serde_derive_internals = "0.29.0"

proc-macro2 = { workspace = true }
quote = { workspace = true }
Expand Down
46 changes: 27 additions & 19 deletions crates/ruff_macros/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use proc_macro2::TokenTree;
use quote::{quote, quote_spanned};
use serde_derive_internals::Ctxt;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::{
AngleBracketedGenericArguments, Attribute, Data, DataStruct, DeriveInput, ExprLit, Field,
Fields, Lit, LitStr, Meta, Path, PathArguments, PathSegment, Token, Type, TypePath,
Fields, Lit, LitStr, Path, PathArguments, PathSegment, Token, Type, TypePath,
};

use ruff_python_trivia::textwrap::dedent;
Expand Down Expand Up @@ -38,25 +38,14 @@ pub(crate) fn derive_impl(input: DeriveInput) -> syn::Result<proc_macro2::TokenS
.any(|attr| attr.path().is_ident("option_group"))
{
output.push(handle_option_group(field)?);
} else if let Some(serde) = field
.attrs
.iter()
.find(|attr| attr.path().is_ident("serde"))
{
} else if let Type::Path(ty) = &field.ty {
let serde_field = serde_field_metadata(field)?;

// If a field has the `serde(flatten)` attribute, flatten the options into the parent
// by calling `Type::record` instead of `visitor.visit_set`
if let (Type::Path(ty), Meta::List(list)) = (&field.ty, &serde.meta) {
for token in list.tokens.clone() {
if let TokenTree::Ident(ident) = token {
if ident == "flatten" {
let ty_name = ty.path.require_ident()?;
output.push(quote_spanned!(
ident.span() => (#ty_name::record(visit))
));
break;
}
}
}
if serde_field.flatten() {
let ty_name = ty.path.require_ident()?;
output.push(quote_spanned!(ident.span() => (#ty_name::record(visit))));
}
}
}
Expand Down Expand Up @@ -193,13 +182,18 @@ fn handle_option(field: &Field, attr: &Attribute) -> syn::Result<proc_macro2::To
} = attr.parse_args::<FieldAttributes>()?;
let kebab_name = LitStr::new(&ident.to_string().replace('_', "-"), ident.span());

let serde_field = serde_field_metadata(field)?;
let attributed_aliases = serde_field.aliases();
let aliases = quote!(BTreeSet::from_iter([#(#attributed_aliases),*]));

Ok(quote_spanned!(
ident.span() => {
visit.record_field(#kebab_name, crate::options_base::OptionField{
doc: &#doc,
default: &#default,
value_type: &#value_type,
example: &#example,
aliases: #aliases
})
}
))
Expand Down Expand Up @@ -248,3 +242,17 @@ fn _parse_key_value(input: ParseStream, name: &str) -> syn::Result<String> {
_ => Err(syn::Error::new(value.span(), "Expected literal string")),
}
}

fn serde_field_metadata(field: &Field) -> syn::Result<serde_derive_internals::attr::Field> {
let context = Ctxt::new();
let field = serde_derive_internals::attr::Field::from_ast(
&context,
0,
&field,
None,
&serde_derive_internals::attr::Default::None,
);
context.check()?;

Ok(field)
}
2 changes: 1 addition & 1 deletion crates/ruff_wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ impl Workspace {
// Propagate defaults.
builtins: Some(Vec::default()),

line_length: Some(LineLength::default()),
line_width: Some(LineLength::default()),

tab_size: Some(TabSize::default()),
target_version: Some(PythonVersion::default()),
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_workspace/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ impl Configuration {
unsafe_fixes: options.unsafe_fixes.map(UnsafeFixes::from),
output_format: options.output_format,
force_exclude: options.force_exclude,
line_length: options.line_length,
line_length: options.line_width,
tab_size: options.tab_size,
namespace_packages: options
.namespace_packages
Expand Down
7 changes: 4 additions & 3 deletions crates/ruff_workspace/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,17 +351,18 @@ pub struct Options {
pub src: Option<Vec<String>>,

// Global Formatting options
/// The line length to use when enforcing long-lines violations (like
/// The line width to use when enforcing long-lines violations (like
/// `E501`). Must be greater than `0` and less than or equal to `320`.
#[option(
default = "88",
value_type = "int",
example = r#"
# Allow lines to be as long as 120 characters.
line-length = 120
line-width = 120
"#
)]
pub line_length: Option<LineLength>,
#[serde(alias = "line-length")]
pub line_width: Option<LineLength>,

/// The number of spaces a tab is equal to when enforcing long-line violations (like `E501`)
/// or formatting code with the formatter.
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff_workspace/src/options_base.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::BTreeSet;
use std::fmt::{Debug, Display, Formatter};

/// Visits [`OptionsMetadata`].
Expand Down Expand Up @@ -307,6 +308,7 @@ pub struct OptionField {
pub doc: &'static str,
pub default: &'static str,
pub value_type: &'static str,
pub aliases: BTreeSet<&'static str>,
pub example: &'static str,
}

Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_workspace/src/pyproject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ line-length = 79
pyproject.tool,
Some(Tools {
ruff: Some(Options {
line_length: Some(LineLength::try_from(79).unwrap()),
line_width: Some(LineLength::try_from(79).unwrap()),
..Options::default()
})
})
Expand Down Expand Up @@ -308,7 +308,7 @@ other-attribute = 1
assert_eq!(
config,
Options {
line_length: Some(LineLength::try_from(88).unwrap()),
line_width: Some(LineLength::try_from(88).unwrap()),
extend_exclude: Some(vec![
"excluded_file.py".to_string(),
"migrations".to_string(),
Expand Down

0 comments on commit ba61b69

Please sign in to comment.