Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add brace_spacing option #628

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/cli/opt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use clap::{ArgEnum, StructOpt};
use std::path::PathBuf;
use stylua_lib::{CallParenType, CollapseSimpleStatement, IndentType, LineEndings, QuoteStyle};
use stylua_lib::{
BraceSpacing, CallParenType, CollapseSimpleStatement, IndentType, LineEndings, QuoteStyle,
};

lazy_static::lazy_static! {
static ref NUM_CPUS: String = num_cpus::get().to_string();
Expand Down Expand Up @@ -169,6 +171,9 @@ pub struct FormatOpts {
/// Specify whether to collapse simple statements.
#[structopt(long, arg_enum, ignore_case = true)]
pub collapse_simple_statement: Option<ArgCollapseSimpleStatement>,
/// Specify whether to add spacing inside the curly brackets around the content of a table literal.
#[structopt(long, arg_enum, ignore_case = true)]
pub brace_spacing: Option<ArgBraceSpacing>,
}

// Convert [`stylua_lib::Config`] enums into clap-friendly enums
Expand Down Expand Up @@ -235,6 +240,11 @@ convert_enum!(CollapseSimpleStatement, ArgCollapseSimpleStatement, {
Always,
});

convert_enum!(BraceSpacing, ArgBraceSpacing, {
Never,
Always,
});

#[cfg(test)]
mod tests {
use super::Opt;
Expand Down
8 changes: 6 additions & 2 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
shape::Shape, CallParenType, CollapseSimpleStatement, Config, IndentType, LineEndings,
Range as FormatRange,
shape::Shape, BraceSpacing, CallParenType, CollapseSimpleStatement, Config, IndentType,
LineEndings, Range as FormatRange,
};
use full_moon::{
node::Node,
Expand Down Expand Up @@ -152,6 +152,10 @@ impl Context {
CollapseSimpleStatement::ConditionalOnly | CollapseSimpleStatement::Always
)
}

pub fn should_add_brace_spacing(&self) -> bool {
matches!(self.config().brace_spacing(), BraceSpacing::Always)
}
}

/// Returns the relevant line ending string from the [`LineEndings`] enum
Expand Down
15 changes: 11 additions & 4 deletions src/formatters/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,17 @@ pub fn create_table_braces(
ContainedSpan::new(start_brace_token, end_brace_token)
}

TableType::SingleLine => ContainedSpan::new(
fmt_symbol!(ctx, start_brace, "{ ", shape),
fmt_symbol!(ctx, end_brace, " }", shape),
),
TableType::SingleLine => {
let (start_, end_) = if ctx.should_add_brace_spacing() {
("{ ", " }")
} else {
("{", "}")
};
ContainedSpan::new(
fmt_symbol!(ctx, start_brace, start_, shape),
fmt_symbol!(ctx, end_brace, end_, shape),
)
}

TableType::Empty => {
let start_brace = fmt_symbol!(ctx, start_brace, "{", shape);
Expand Down
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,24 @@ impl Default for CollapseSimpleStatement {
}
}

/// Whether we add spacing inside the curly brackets around the content of a table literal.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)]
#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen"), wasm_bindgen)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "fromstr", derive(strum::EnumString))]
pub enum BraceSpacing {
/// Never add spaces around content in a table literal
Never,
/// Always add spaces around content in a table literal
Always,
}

impl Default for BraceSpacing {
fn default() -> Self {
BraceSpacing::Always
}
}

/// An optional formatting range.
/// If provided, only content within these boundaries (inclusive) will be formatted.
/// Both boundaries are optional, and are given as byte offsets from the beginning of the file.
Expand Down Expand Up @@ -168,6 +186,8 @@ pub struct Config {
/// if set to [`CollapseSimpleStatement::None`] structures are never collapsed.
/// if set to [`CollapseSimpleStatement::FunctionOnly`] then simple functions (i.e., functions with a single laststmt) can be collapsed
collapse_simple_statement: CollapseSimpleStatement,
/// Whether we add spacing inside the curly brackets around the content of a table literal.
brace_spacing: BraceSpacing,
}

#[cfg_attr(all(target_arch = "wasm32", feature = "wasm-bindgen"), wasm_bindgen)]
Expand Down Expand Up @@ -211,6 +231,10 @@ impl Config {
self.collapse_simple_statement
}

pub fn brace_spacing(&self) -> BraceSpacing {
self.brace_spacing
}

/// Returns a new config with the given column width
pub fn with_column_width(self, column_width: usize) -> Self {
Self {
Expand Down Expand Up @@ -275,6 +299,14 @@ impl Config {
..self
}
}

/// Returns a new config with the given bracket space configuration
pub fn with_brace_spacing(self, brace_spacing: BraceSpacing) -> Self {
Self {
brace_spacing,
..self
}
}
}

impl Default for Config {
Expand All @@ -288,6 +320,7 @@ impl Default for Config {
no_call_parentheses: false,
call_parentheses: CallParenType::default(),
collapse_simple_statement: CollapseSimpleStatement::default(),
brace_spacing: BraceSpacing::default(),
}
}
}
Expand Down
39 changes: 39 additions & 0 deletions tests/test_table_spaces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use stylua_lib::{format_code, BraceSpacing, Config, OutputVerification};

fn format(brace_spacing: BraceSpacing, input: &str) -> String {
format_code(
input,
Config::default().with_brace_spacing(brace_spacing),
None,
OutputVerification::None,
)
.unwrap()
}

#[test]
fn test_table_oneline_with_internal_spaces() {
insta::assert_snapshot!(
format(BraceSpacing::Always,
r###"
local foo = { "content" }
"###
),
@r###"
local foo = { "content" }
"###
);
}

#[test]
fn test_table_oneline_without_internal_spaces() {
insta::assert_snapshot!(
format(BraceSpacing::Never,
r###"
local foo = { "content" }
"###
),
@r###"
local foo = {"content"}
"###
);
}