Skip to content

Commit

Permalink
Rename tab-size to indent-width (#8082)
Browse files Browse the repository at this point in the history
## Summary

This PR renames the `tab-size` configuration option to `indent-width` to
express that the formatter uses the option to determine the indentation
width AND as tab width.

I first preferred naming the option `tab-width` but then decided to go
with `indent-width` because:

* It aligns with the `indent-style` option
* It would allow us to write a lint rule that asserts that each
indentation uses `indent-width` spaces.

 Closes #7643

## Test Plan

Added integration test
  • Loading branch information
MichaReiser authored Oct 24, 2023
1 parent c3dabc1 commit 84979f9
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 49 deletions.
37 changes: 36 additions & 1 deletion crates/ruff_cli/tests/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ fn format_options() -> Result<()> {
fs::write(
&ruff_toml,
r#"
tab-size = 8
indent-width = 8
line-length = 84
[format]
Expand Down Expand Up @@ -278,6 +278,41 @@ if condition:
Ok(())
}

#[test]
fn deprecated_options() -> Result<()> {
let tempdir = TempDir::new()?;
let ruff_toml = tempdir.path().join("ruff.toml");
fs::write(
&ruff_toml,
r#"
tab-size = 2
"#,
)?;

insta::with_settings!({filters => vec![
(&*regex::escape(ruff_toml.to_str().unwrap()), "[RUFF-TOML-PATH]"),
]}, {
assert_cmd_snapshot!(Command::new(get_cargo_bin(BIN_NAME))
.args(["format", "--config"])
.arg(&ruff_toml)
.arg("-")
.pass_stdin(r#"
if True:
pass
"#), @r###"
success: true
exit_code: 0
----- stdout -----
if True:
pass
----- stderr -----
warning: The `tab-size` option has been renamed to `indent-width` to emphasize that it configures the indentation used by the formatter as well as the tab width. Please update your configuration to use `indent-width = <value>` instead.
"###);
});
Ok(())
}

/// Since 0.1.0 the legacy format option is no longer supported
#[test]
fn legacy_format_option() -> Result<()> {
Expand Down
8 changes: 4 additions & 4 deletions crates/ruff_linter/src/fix/edits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use ruff_source_file::{Locator, NewlineWithTrailingNewline, UniversalNewlines};
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};

use crate::fix::codemods;
use crate::line_width::{LineLength, LineWidthBuilder, TabSize};
use crate::line_width::{IndentWidth, LineLength, LineWidthBuilder};

/// Return the `Fix` to use when deleting a `Stmt`.
///
Expand Down Expand Up @@ -293,7 +293,7 @@ pub(crate) fn fits(
node: AnyNodeRef,
locator: &Locator,
line_length: LineLength,
tab_size: TabSize,
tab_size: IndentWidth,
) -> bool {
all_lines_fit(fix, node, locator, line_length.value() as usize, tab_size)
}
Expand All @@ -305,7 +305,7 @@ pub(crate) fn fits_or_shrinks(
node: AnyNodeRef,
locator: &Locator,
line_length: LineLength,
tab_size: TabSize,
tab_size: IndentWidth,
) -> bool {
// Use the larger of the line length limit, or the longest line in the existing AST node.
let line_length = std::iter::once(line_length.value() as usize)
Expand All @@ -327,7 +327,7 @@ fn all_lines_fit(
node: AnyNodeRef,
locator: &Locator,
line_length: usize,
tab_size: TabSize,
tab_size: IndentWidth,
) -> bool {
let prefix = locator.slice(TextRange::new(
locator.line_start(node.start()),
Expand Down
18 changes: 9 additions & 9 deletions crates/ruff_linter/src/line_width.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ pub struct LineWidthBuilder {
/// This is used to calculate the width of tabs.
column: usize,
/// The tab size to use when calculating the width of tabs.
tab_size: TabSize,
tab_size: IndentWidth,
}

impl Default for LineWidthBuilder {
fn default() -> Self {
Self::new(TabSize::default())
Self::new(IndentWidth::default())
}
}

Expand Down Expand Up @@ -164,7 +164,7 @@ impl LineWidthBuilder {
}

/// Creates a new `LineWidth` with the given tab size.
pub fn new(tab_size: TabSize) -> Self {
pub fn new(tab_size: IndentWidth) -> Self {
LineWidthBuilder {
width: 0,
column: 0,
Expand Down Expand Up @@ -234,28 +234,28 @@ impl PartialOrd<LineLength> for LineWidthBuilder {
/// The size of a tab.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, CacheKey)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct TabSize(NonZeroU8);
pub struct IndentWidth(NonZeroU8);

impl TabSize {
impl IndentWidth {
pub(crate) fn as_usize(self) -> usize {
self.0.get() as usize
}
}

impl Default for TabSize {
impl Default for IndentWidth {
fn default() -> Self {
Self(NonZeroU8::new(4).unwrap())
}
}

impl From<NonZeroU8> for TabSize {
impl From<NonZeroU8> for IndentWidth {
fn from(tab_size: NonZeroU8) -> Self {
Self(tab_size)
}
}

impl From<TabSize> for NonZeroU8 {
fn from(value: TabSize) -> Self {
impl From<IndentWidth> for NonZeroU8 {
fn from(value: IndentWidth) -> Self {
value.0
}
}
4 changes: 2 additions & 2 deletions crates/ruff_linter/src/message/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use ruff_source_file::{OneIndexed, SourceLocation};
use ruff_text_size::{Ranged, TextRange, TextSize};

use crate::fs::relativize_path;
use crate::line_width::{LineWidthBuilder, TabSize};
use crate::line_width::{IndentWidth, LineWidthBuilder};
use crate::message::diff::Diff;
use crate::message::{Emitter, EmitterContext, Message};
use crate::registry::AsRule;
Expand Down Expand Up @@ -300,7 +300,7 @@ fn replace_whitespace(source: &str, annotation_range: TextRange) -> SourceCode {
let mut result = String::new();
let mut last_end = 0;
let mut range = annotation_range;
let mut line_width = LineWidthBuilder::new(TabSize::default());
let mut line_width = LineWidthBuilder::new(IndentWidth::default());

for (index, c) in source.char_indices() {
let old_width = line_width.get();
Expand Down
6 changes: 3 additions & 3 deletions crates/ruff_linter/src/rules/pycodestyle/overlong.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ruff_python_trivia::is_pragma_comment;
use ruff_source_file::Line;
use ruff_text_size::{TextLen, TextRange};

use crate::line_width::{LineLength, LineWidthBuilder, TabSize};
use crate::line_width::{IndentWidth, LineLength, LineWidthBuilder};

#[derive(Debug)]
pub(super) struct Overlong {
Expand All @@ -23,7 +23,7 @@ impl Overlong {
indexer: &Indexer,
limit: LineLength,
task_tags: &[String],
tab_size: TabSize,
tab_size: IndentWidth,
) -> Option<Self> {
// The maximum width of the line is the number of bytes multiplied by the tab size (the
// worst-case scenario is that the line is all tabs). If the maximum width is less than the
Expand Down Expand Up @@ -158,7 +158,7 @@ impl<'a> Deref for StrippedLine<'a> {
}

/// Returns the width of a given string, accounting for the tab size.
fn measure(s: &str, tab_size: TabSize) -> LineWidthBuilder {
fn measure(s: &str, tab_size: IndentWidth) -> LineWidthBuilder {
let mut width = LineWidthBuilder::new(tab_size);
width = width.add_str(s);
width
Expand Down
6 changes: 3 additions & 3 deletions crates/ruff_linter/src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::rules::{
use crate::settings::types::{FilePatternSet, PerFileIgnore, PythonVersion};
use crate::{codes, RuleSelector};

use super::line_width::TabSize;
use super::line_width::IndentWidth;

use self::rule_table::RuleTable;
use self::types::PreviewMode;
Expand Down Expand Up @@ -59,7 +59,7 @@ pub struct LinterSettings {
pub logger_objects: Vec<String>,
pub namespace_packages: Vec<PathBuf>,
pub src: Vec<PathBuf>,
pub tab_size: TabSize,
pub tab_size: IndentWidth,
pub task_tags: Vec<String>,
pub typing_modules: Vec<String>,

Expand Down Expand Up @@ -155,7 +155,7 @@ impl LinterSettings {

src: vec![path_dedot::CWD.clone()],
// Needs duplicating
tab_size: TabSize::default(),
tab_size: IndentWidth::default(),

task_tags: TASK_TAGS.iter().map(ToString::to_string).collect(),
typing_modules: vec![],
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use wasm_bindgen::prelude::*;

use ruff_formatter::{FormatResult, Formatted, IndentStyle};
use ruff_linter::directives;
use ruff_linter::line_width::{LineLength, TabSize};
use ruff_linter::line_width::{IndentWidth, LineLength};
use ruff_linter::linter::{check_path, LinterResult};
use ruff_linter::registry::AsRule;
use ruff_linter::settings::types::PythonVersion;
Expand Down Expand Up @@ -126,7 +126,7 @@ impl Workspace {

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

tab_size: Some(TabSize::default()),
indent_width: Some(IndentWidth::default()),
target_version: Some(PythonVersion::default()),

lint: Some(LintOptions {
Expand Down
27 changes: 18 additions & 9 deletions crates/ruff_workspace/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use shellexpand::LookupError;
use strum::IntoEnumIterator;

use ruff_cache::cache_dir;
use ruff_formatter::{IndentStyle, IndentWidth, LineWidth};
use ruff_linter::line_width::{LineLength, TabSize};
use ruff_formatter::IndentStyle;
use ruff_linter::line_width::{IndentWidth, LineLength};
use ruff_linter::registry::RuleNamespace;
use ruff_linter::registry::{Rule, RuleSet, INCOMPATIBLE_CODES};
use ruff_linter::rule_selector::{PreviewOptions, Specificity};
Expand Down Expand Up @@ -133,7 +133,7 @@ pub struct Configuration {

// Global formatting options
pub line_length: Option<LineLength>,
pub tab_size: Option<TabSize>,
pub indent_width: Option<IndentWidth>,

pub lint: LintConfiguration,
pub format: FormatConfiguration,
Expand Down Expand Up @@ -166,14 +166,14 @@ impl Configuration {
line_width: self
.line_length
.map_or(format_defaults.line_width, |length| {
LineWidth::from(NonZeroU16::from(length))
ruff_formatter::LineWidth::from(NonZeroU16::from(length))
}),
line_ending: format.line_ending.unwrap_or(format_defaults.line_ending),
indent_style: format.indent_style.unwrap_or(format_defaults.indent_style),
indent_width: self
.tab_size
.indent_width
.map_or(format_defaults.indent_width, |tab_size| {
IndentWidth::from(NonZeroU8::from(tab_size))
ruff_formatter::IndentWidth::from(NonZeroU8::from(tab_size))
}),
quote_style: format.quote_style.unwrap_or(format_defaults.quote_style),
magic_trailing_comma: format
Expand Down Expand Up @@ -228,7 +228,7 @@ impl Configuration {
.unwrap_or_else(|| DUMMY_VARIABLE_RGX.clone()),
external: FxHashSet::from_iter(lint.external.unwrap_or_default()),
ignore_init_module_imports: lint.ignore_init_module_imports.unwrap_or_default(),
tab_size: self.tab_size.unwrap_or_default(),
tab_size: self.indent_width.unwrap_or_default(),
namespace_packages: self.namespace_packages.unwrap_or_default(),
per_file_ignores: resolve_per_file_ignores(
lint.per_file_ignores
Expand Down Expand Up @@ -389,6 +389,15 @@ impl Configuration {
}
};

#[allow(deprecated)]
let indent_width = {
if options.tab_size.is_some() {
warn_user_once!("The `tab-size` option has been renamed to `indent-width` to emphasize that it configures the indentation used by the formatter as well as the tab width. Please update your configuration to use `indent-width = <value>` instead.");
}

options.indent_width.or(options.tab_size)
};

Ok(Self {
builtins: options.builtins,
cache_dir: options
Expand Down Expand Up @@ -456,7 +465,7 @@ impl Configuration {
output_format: options.output_format,
force_exclude: options.force_exclude,
line_length: options.line_length,
tab_size: options.tab_size,
indent_width,
namespace_packages: options
.namespace_packages
.map(|namespace_package| resolve_src(&namespace_package, project_root))
Expand Down Expand Up @@ -504,7 +513,7 @@ impl Configuration {
output_format: self.output_format.or(config.output_format),
force_exclude: self.force_exclude.or(config.force_exclude),
line_length: self.line_length.or(config.line_length),
tab_size: self.tab_size.or(config.tab_size),
indent_width: self.indent_width.or(config.indent_width),
namespace_packages: self.namespace_packages.or(config.namespace_packages),
required_version: self.required_version.or(config.required_version),
respect_gitignore: self.respect_gitignore.or(config.respect_gitignore),
Expand Down
Loading

0 comments on commit 84979f9

Please sign in to comment.