From 3377af35261cd13a59204a13f21168948670e593 Mon Sep 17 00:00:00 2001 From: anqiang Date: Fri, 22 May 2026 19:10:58 +0800 Subject: [PATCH 1/9] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=96=B0?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MODIFICATIONS.md | 129 ++++++++ .../Options/ConfigurationFileOptions.cs | 4 + Src/CSharpier.Core/CSharp/CSharpFormatter.cs | 2 + .../SyntaxPrinter/ArgumentListLikeSyntax.cs | 37 +++ .../CSharp/SyntaxPrinter/AttributeLists.cs | 66 +++- .../CSharp/SyntaxPrinter/PrintingContext.cs | 1 + .../BaseFieldDeclaration.cs | 23 ++ .../SyntaxNodePrinters/BinaryExpression.cs | 12 +- .../SyntaxNodePrinters/DoStatement.cs | 8 +- .../SyntaxNodePrinters/IfStatement.cs | 8 +- .../SyntaxNodePrinters/SwitchStatement.cs | 7 +- .../SyntaxNodePrinters/WhileStatement.cs | 5 +- Src/CSharpier.Core/CodeFormatterOptions.cs | 2 + Src/CSharpier.Core/PrinterOptions.cs | 1 + Src/CSharpier.Core/PublicAPI.Unshipped.txt | 4 +- .../AllowFieldAttributeOnSameLineTests.cs | 146 +++++++++ .../TestFiles/cs/AssignmentExpressions.test | 12 +- .../TestFiles/cs/BinaryExpressions.test | 286 ++++++++---------- .../TestFiles/cs/CheckedStatements.test | 4 +- .../TestFiles/cs/ConditionalExpressions.test | 42 +-- .../cs/ConditionalExpressions_Tabs.test | 30 +- .../TestFiles/cs/Directives.test | 3 +- .../TestFiles/cs/DoStatements.test | 9 +- .../TestFiles/cs/ElseStatements.test | 6 +- .../TestFiles/cs/FieldDeclarations.test | 8 +- .../TestFiles/cs/ForStatements.test | 4 +- .../TestFiles/cs/IfStatements.test | 32 +- .../TestFiles/cs/InitializerExpressions.test | 2 +- .../cs/InterpolatedStringExpressions.test | 3 +- .../TestFiles/cs/IsPatternExpressions.test | 102 +++---- .../TestFiles/cs/MemberChains.test | 4 +- .../TestFiles/cs/ObnoxiousEdgeCases.test | 14 +- .../cs/ParenthesizedExpressions.test | 16 +- .../TestFiles/cs/QueryExpressions.test | 4 +- .../TestFiles/cs/ReturnStatements.test | 4 +- .../TestFiles/cs/SimpleLambdaExpressions.test | 4 +- .../TestFiles/cs/SwitchExpressions.test | 6 +- .../TestFiles/cs/SwitchExpressions_Tabs.test | 6 +- .../TestFiles/cs/SwitchStatements.test | 6 +- .../TestFiles/cs/TryStatements.test | 4 +- .../TestFiles/cs/UncheckedStatements.test | 4 +- .../TestFiles/cs/VariableDeclarations.test | 24 +- .../TestFiles/cs/WhileStatements.test | 18 +- docs/Configuration.md | 26 +- 44 files changed, 746 insertions(+), 392 deletions(-) create mode 100644 MODIFICATIONS.md create mode 100644 Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs diff --git a/MODIFICATIONS.md b/MODIFICATIONS.md new file mode 100644 index 000000000..2671bab19 --- /dev/null +++ b/MODIFICATIONS.md @@ -0,0 +1,129 @@ +# CSharpier-Flex 魔修改记录 + +本文档记录对 CSharpier 原版所做的所有定制化修改。 + +--- + +## 修改列表 + + + +### 2. 二元表达式操作符换行位置修改 + +**日期**:2026-05-22 + +**目的**:将二元表达式(`||`、`&&`、`+`、`==`、`??` 等)换行时操作符的位置从"下一行开头"改为"当前行末尾",使代码风格更符合 C# 社区常见习惯。 + +**修改前**(操作符在下一行开头): +```csharp +if ( + GameManager.Instance.gameMode == GameManager.GameMode.Classic + || GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge +) { } +``` + +**修改后**(操作符在当前行末尾): +```csharp +if (GameManager.Instance.gameMode == GameManager.GameMode.Classic || + GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge) +{ +``` + +**影响范围**: +- 所有使用二元操作符(`||`、`&&`、`+`、`-`、`==`、`!=`、`??` 等)且需要换行的表达式 +- 包括 `if` / `while` / `do-while` / `switch` 条件、变量赋值、`return` 语句、Lambda 表达式体等 + +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs` — 调整操作符与换行符的 Doc 顺序(操作符移到 `Doc.Line` 之前),同时同步修改 `??` 操作符的处理逻辑 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs` — 去掉条件前后的 `Doc.IfBreak(SoftLine)`,将 `)` 纳入同一 `Doc.Group`,使条件紧跟 `if (` +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs` — 同步修改,去掉内层 `Doc.Group` + `SoftLine`,与 `if` 保持一致 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs` — 同步修改 `do-while` 的条件括号风格 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs` — 同步修改,将 `(` `)` 移入 `Doc.GroupWithId` 内 +- 31 个测试快照文件 — 更新所有涉及二元表达式换行和括号风格变化的快照 + +--- + +### 1. 新增配置项 `allowFieldAttributeOnSameLine` + +**日期**:2026-05-22 + +**目的**:允许字段声明的属性(Attribute)与字段保持在同一行,而不是强制换行。适用于 Unity 项目中常见的 `[SerializeField] private Button _buttonQuit;` 风格。 + +**配置方式**(`.csharpierrc`): +```json +{ + "allowFieldAttributeOnSameLine": true +} +``` + +**行为**: +- `false`(默认):属性与字段之间强制换行(原版行为) + ```csharp + [SerializeField] + private Button _buttonQuit; + ``` +- `true`:属性与字段允许在同一行,按数量分级处理: + ```csharp + // 1-2 个属性 → 全部同行 + [SerializeField] private Button _buttonQuit; + [SerializeField] [HideInInspector] private Text _label; + // 3 个属性 → 属性同行,字段换行 + [SerializeField] [HideInInspector] [Header("Title")] + private Text _labelTitle; + // 4+ 个属性 → 全部换行(原版行为) + [SerializeField] + [HideInInspector] + [Header("Title")] + [Tooltip("tip")] + private Text _labelTitle; + ``` + +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs` — 字段声明时根据配置选择 `Doc.Line`(可同行)或 `Doc.HardLine`(强制换行) +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs` — 启用时用 `Doc.Group` 包裹整个字段声明,使 `Doc.Line` 能折叠为空格 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs` — `PrintingContextOptions` 新增属性 +- `Src/CSharpier.Core/PrinterOptions.cs` — 新增属性 +- `Src/CSharpier.Core/CodeFormatterOptions.cs` — 公共 API 新增属性 +- `Src/CSharpier.Core/CSharp/CSharpFormatter.cs` — 传递配置到 `PrintingContext` +- `Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs` — 配置文件解析新增字段 +- `Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs` — 测试用例 + + +--- + +### 3. 方法调用尾部 Lambda 参数格式化 + +**日期**:2026-05-22 + +**目的**:当方法调用的最后一个参数是带有代码块(block body)的 lambda 表达式时,非 lambda 参数保持在方法调用的同一行,仅 lambda 体换行。避免所有参数被打散到各自的新行。 + +**修改前**(所有参数各占一行): +```csharp +BindButton( + _buttonChallenge, + () => + { + var playBtn = _buttonChallenge.GetComponent(); + bool allowDiamond = playBtn != null && playBtn.AllowDiamond; + Presenter.HandleChallengeClicked(allowDiamond, CloseCT); + } +); +``` + +**修改后**(非 lambda 参数保持内联,`{` 与方法调用同级,`});` 紧跟): +```csharp +BindButton(_buttonChallenge, () => +{ + var playBtn = _buttonChallenge.GetComponent(); + bool allowDiamond = playBtn != null && playBtn.AllowDiamond; + Presenter.HandleChallengeClicked(allowDiamond, CloseCT); +}); +``` + +**触发条件**: +- 方法调用有 2 个及以上参数 +- 最后一个参数是 `ParenthesizedLambdaExpression`(`() => { ... }`)或 `SimpleLambdaExpression`(`x => { ... }`)且包含非空代码块 +- 不影响:单参数 lambda(已有专门处理)、表达式体 lambda(`() => expr`)、空 block lambda(`() => { }`) + +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs` — 在默认多参数分支前插入新分支,非 lambda 参数内联打印,lambda 的 Body 用 `Doc.Indent` 包裹实现缩进 \ No newline at end of file diff --git a/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs b/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs index 73b4c10d3..bd5f035fc 100644 --- a/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs +++ b/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs @@ -16,6 +16,8 @@ internal class ConfigurationFileOptions [JsonConverter(typeof(CaseInsensitiveEnumConverter))] public EndOfLine EndOfLine { get; init; } + public bool AllowFieldAttributeOnSameLine { get; init; } + public Override[] Overrides { get; init; } = []; public PrinterOptions? ConvertToPrinterOptions(string filePath) @@ -45,6 +47,7 @@ out var parsedFormatter UseTabs = matchingOverride.UseTabs, Width = matchingOverride.PrintWidth, EndOfLine = matchingOverride.EndOfLine, + AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, }; } @@ -61,6 +64,7 @@ out var parsedFormatter UseTabs = this.UseTabs, Width = this.PrintWidth, EndOfLine = this.EndOfLine, + AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, }; } diff --git a/Src/CSharpier.Core/CSharp/CSharpFormatter.cs b/Src/CSharpier.Core/CSharp/CSharpFormatter.cs index e4dc78093..d3ea30e19 100644 --- a/Src/CSharpier.Core/CSharp/CSharpFormatter.cs +++ b/Src/CSharpier.Core/CSharp/CSharpFormatter.cs @@ -157,6 +157,7 @@ bool TryGetCompilationFailure(out CodeFormatterResult compilationResult) IndentSize = printerOptions.IndentSize, UseTabs = printerOptions.UseTabs, XmlWhitespaceSensitivity = XmlWhitespaceSensitivity.Strict, + AllowFieldAttributeOnSameLine = printerOptions.AllowFieldAttributeOnSameLine, }, }; var document = Node.Print(rootNode, printingContext); @@ -185,6 +186,7 @@ bool TryGetCompilationFailure(out CodeFormatterResult compilationResult) IndentSize = printerOptions.IndentSize, UseTabs = printerOptions.UseTabs, XmlWhitespaceSensitivity = XmlWhitespaceSensitivity.Strict, + AllowFieldAttributeOnSameLine = printerOptions.AllowFieldAttributeOnSameLine, }, }; document = Node.Print( diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs index 9bdb318d5..96aecae89 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs @@ -1,5 +1,6 @@ using CSharpier.Core.CSharp.SyntaxPrinter.SyntaxNodePrinters; using CSharpier.Core.DocTypes; +using CSharpier.Core.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -78,6 +79,42 @@ lambda.Block is not null { args = SeparatedSyntaxList.Print(arguments, Argument.Print, Doc.Line, context); } + else if ( + arguments.Count >= 2 + && arguments[arguments.Count - 1].Expression + is ParenthesizedLambdaExpressionSyntax { Block.Statements.Count: > 0 } + or SimpleLambdaExpressionSyntax { Body: BlockSyntax { Statements.Count: > 0 } } + ) + { + var docs = new DocListBuilder(arguments.Count * 3 + 2); + + for (var i = 0; i < arguments.Count - 1; i++) + { + docs.Add(Argument.Print(arguments[i], context)); + if (i < arguments.SeparatorCount) + { + docs.Add(Token.Print(arguments.GetSeparator(i), context)); + docs.Add(" "); + } + } + + var lastArg = arguments[arguments.Count - 1]; + docs.Add(Argument.PrintModifiers(lastArg, context)); + + if (lastArg.Expression is ParenthesizedLambdaExpressionSyntax pLambda) + { + docs.Add(ParenthesizedLambdaExpression.PrintHead(pLambda, context)); + docs.Add(ParenthesizedLambdaExpression.PrintBody(pLambda, context)); + } + else if (lastArg.Expression is SimpleLambdaExpressionSyntax sLambda) + { + docs.Add(SimpleLambdaExpression.PrintHead(sLambda, context)); + docs.Add(SimpleLambdaExpression.PrintBody(sLambda, context)); + } + + args = Doc.Concat(ref docs); + docs.Dispose(); + } else if (arguments.Count > 0) { args = Doc.Concat( diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs index f0942a4de..dd2c5f644 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs @@ -2,12 +2,28 @@ using CSharpier.Core.DocTypes; using CSharpier.Core.Utilities; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace CSharpier.Core.CSharp.SyntaxPrinter; internal static class AttributeLists { + internal static int GetTotalAttributeCount(SyntaxList attributeLists) => + attributeLists.Sum(list => list.Attributes.Count); + + internal static bool HasOriginalLineBreaks(SyntaxList attributeLists) + { + for (var i = 0; i < attributeLists.Count - 1; i++) + { + if (attributeLists[i].GetTrailingTrivia().Any(SyntaxKind.EndOfLineTrivia)) + { + return true; + } + } + return false; + } + public static Doc Print( SyntaxNode node, SyntaxList attributeLists, @@ -19,6 +35,52 @@ PrintingContext context return Doc.Null; } + var isFieldSameLine = + node is BaseFieldDeclarationSyntax + && context.Options.AllowFieldAttributeOnSameLine; + + if (isFieldSameLine) + { + var totalAttrs = GetTotalAttributeCount(attributeLists); + if (totalAttrs == 3 && !HasOriginalLineBreaks(attributeLists)) + { + return Doc.Concat( + Doc.Group( + Doc.Join( + Doc.Line, + attributeLists.Select(o => AttributeList.Print(o, context)) + ) + ), + Doc.HardLine + ); + } + + if ( + totalAttrs <= 2 + && attributeLists.Count > 1 + && HasOriginalLineBreaks(attributeLists) + ) + { + var result = new DocListBuilder(attributeLists.Count * 2); + for (var i = 0; i < attributeLists.Count; i++) + { + result.Add(AttributeList.Print(attributeLists[i], context)); + if (i < attributeLists.Count - 1) + { + result.Add( + attributeLists[i] + .GetTrailingTrivia() + .Any(SyntaxKind.EndOfLineTrivia) + ? Doc.HardLine + : (Doc)" " + ); + } + } + result.Add(" "); + return Doc.Concat(ref result); + } + } + var docs = new DocListBuilder(2); Doc separator = node is TypeParameterSyntax @@ -26,7 +88,9 @@ or ParameterSyntax or ParenthesizedLambdaExpressionSyntax or AccessorDeclarationSyntax ? Doc.Line - : Doc.HardLine; + : isFieldSameLine && GetTotalAttributeCount(attributeLists) <= 2 + ? Doc.Line + : Doc.HardLine; docs.Add(Doc.Join(separator, attributeLists.Select(o => AttributeList.Print(o, context)))); diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs index b895605e7..b249626e4 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs @@ -38,6 +38,7 @@ public class PrintingContextOptions public required int IndentSize { get; init; } public required bool UseTabs { get; init; } public required XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; init; } + public bool AllowFieldAttributeOnSameLine { get; init; } } public class PrintingContextState diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs index 8fdab6a93..4609e2c87 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs @@ -8,6 +8,23 @@ internal static class BaseFieldDeclaration { public static Doc Print(BaseFieldDeclarationSyntax node, PrintingContext context) { + var canSameLine = + context.Options.AllowFieldAttributeOnSameLine + && node.AttributeLists.Count > 0 + && AttributeLists.GetTotalAttributeCount(node.AttributeLists) <= 2 + && !AttributeLists.HasOriginalLineBreaks(node.AttributeLists); + + Doc leadingTrivia = Doc.Null; + if (canSameLine) + { + var firstToken = node.AttributeLists[0].GetFirstToken(); + leadingTrivia = Token.PrintLeadingTrivia(firstToken, context); + if (leadingTrivia != Doc.Null) + { + context.State.SkipNextLeadingTrivia = true; + } + } + var docs = new DocListBuilder(5); docs.Add(AttributeLists.Print(node, node.AttributeLists, context)); docs.Add(Modifiers.PrintSorted(node.Modifiers, context)); @@ -20,6 +37,12 @@ public static Doc Print(BaseFieldDeclarationSyntax node, PrintingContext context VariableDeclaration.Print(node.Declaration, context), Token.Print(node.SemicolonToken, context) ); + + if (canSameLine) + { + return Doc.Concat(leadingTrivia, Doc.Group(docs.ToArray())); + } + return Doc.Concat(ref docs); } } diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs index 228f0c753..199887b3a 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs @@ -15,8 +15,8 @@ public static Doc Print(BinaryExpressionSyntax node, PrintingContext context) if (node.Parent is IfStatementSyntax) { - // avoid grouping here so that the ifBreaks in IfStatement can understand when - // this BinaryExpression breaks + // avoid grouping here so that the outer Group in IfStatement controls + // when all Doc.Line breaks in this BinaryExpression fire return Doc.Concat(docs); } @@ -90,9 +90,9 @@ private static List PrintBinaryExpression(SyntaxNode node, PrintingContext { docs.Add( Node.Print(binaryExpressionSyntax.Left, context), - Doc.Line, + " ", Token.Print(binaryExpressionSyntax.OperatorToken, context), - " " + Doc.Line ); } @@ -126,9 +126,9 @@ possibleBinary is BinaryExpressionSyntax childBinary } var right = Doc.Concat( - Doc.Line, - Token.Print(binaryExpressionSyntax.OperatorToken, context), " ", + Token.Print(binaryExpressionSyntax.OperatorToken, context), + Doc.Line, Node.Print(binaryExpressionSyntax.Right, context) ); diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs index 71aca2f2e..975f8663f 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs @@ -17,9 +17,11 @@ public static Doc Print(DoStatementSyntax node, PrintingContext context) Node.Print(node.Statement, context), node.Statement is BlockSyntax ? " " : Doc.HardLine, Token.PrintWithSuffix(node.WhileKeyword, " ", context), - Token.Print(node.OpenParenToken, context), - Doc.Group(Doc.Indent(Doc.SoftLine, Node.Print(node.Condition, context)), Doc.SoftLine), - Token.Print(node.CloseParenToken, context), + Doc.Group( + Token.Print(node.OpenParenToken, context), + Doc.Indent(Node.Print(node.Condition, context)), + Token.Print(node.CloseParenToken, context) + ), Token.Print(node.SemicolonToken, context) ); } diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs index 80d79f0f7..12f4ad251 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs @@ -19,13 +19,9 @@ public static Doc Print(IfStatementSyntax node, PrintingContext context) " ", Doc.Group( Token.Print(node.OpenParenToken, context), - Doc.Indent( - Doc.IfBreak(Doc.SoftLine, Doc.Null), - Node.Print(node.Condition, context) - ), - Doc.IfBreak(Doc.SoftLine, Doc.Null) + Doc.Indent(Node.Print(node.Condition, context)), + Token.Print(node.CloseParenToken, context) ), - Token.Print(node.CloseParenToken, context), OptionalBraces.Print(node.Statement, context) ); diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs index 23e6eeb6a..9dbd1c420 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs @@ -33,13 +33,12 @@ public static Doc Print(SwitchStatementSyntax node, PrintingContext context) Doc.Group( Token.PrintWithoutLeadingTrivia(node.SwitchKeyword, context), " ", - Token.Print(node.OpenParenToken, context), Doc.GroupWithId( groupId, - Doc.Indent(Doc.SoftLine, Node.Print(node.Expression, context)), - Doc.SoftLine + Token.Print(node.OpenParenToken, context), + Doc.Indent(Node.Print(node.Expression, context)), + Token.Print(node.CloseParenToken, context) ), - Token.Print(node.CloseParenToken, context), node.Sections.Count == 0 ? " " : Doc.Line, Token.Print(node.OpenBraceToken, context), sections, diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs index a9ba36a47..ae1b979ff 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs @@ -13,10 +13,7 @@ public static Doc Print(WhileStatementSyntax node, PrintingContext context) Token.Print(node.WhileKeyword, context), " ", Token.Print(node.OpenParenToken, context), - Doc.Group( - Doc.Indent(Doc.SoftLine, Node.Print(node.Condition, context)), - Doc.SoftLine - ), + Doc.Indent(Node.Print(node.Condition, context)), Token.Print(node.CloseParenToken, context) ), node.Statement switch diff --git a/Src/CSharpier.Core/CodeFormatterOptions.cs b/Src/CSharpier.Core/CodeFormatterOptions.cs index 5f123d9c8..9292aaa23 100644 --- a/Src/CSharpier.Core/CodeFormatterOptions.cs +++ b/Src/CSharpier.Core/CodeFormatterOptions.cs @@ -7,6 +7,7 @@ public class CodeFormatterOptions public int IndentSize { get; init; } = 4; public EndOfLine EndOfLine { get; init; } = EndOfLine.Auto; public bool IncludeGenerated { get; init; } + public bool AllowFieldAttributeOnSameLine { get; init; } public XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; init; } = XmlWhitespaceSensitivity.Strict; @@ -19,6 +20,7 @@ internal PrinterOptions ToPrinterOptions() IndentSize = this.IndentSize, EndOfLine = this.EndOfLine, IncludeGenerated = this.IncludeGenerated, + AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, }; } } diff --git a/Src/CSharpier.Core/PrinterOptions.cs b/Src/CSharpier.Core/PrinterOptions.cs index 6f31acb68..0e34750ec 100644 --- a/Src/CSharpier.Core/PrinterOptions.cs +++ b/Src/CSharpier.Core/PrinterOptions.cs @@ -29,6 +29,7 @@ public int IndentSize public EndOfLine EndOfLine { get; set; } = EndOfLine.Auto; public bool TrimInitialLines { get; init; } = true; public bool IncludeGenerated { get; set; } + public bool AllowFieldAttributeOnSameLine { get; set; } public Formatter Formatter { get; } = formatter; public XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; set; } = xmlWhitespaceSensitivity; diff --git a/Src/CSharpier.Core/PublicAPI.Unshipped.txt b/Src/CSharpier.Core/PublicAPI.Unshipped.txt index f02a42556..5ade7e860 100644 --- a/Src/CSharpier.Core/PublicAPI.Unshipped.txt +++ b/Src/CSharpier.Core/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ -CSharpier.Core.CodeFormatterOptions.XmlWhitespaceSensitivity.get -> CSharpier.Core.XmlWhitespaceSensitivity +CSharpier.Core.CodeFormatterOptions.AllowFieldAttributeOnSameLine.get -> bool +CSharpier.Core.CodeFormatterOptions.AllowFieldAttributeOnSameLine.init -> void +CSharpier.Core.CodeFormatterOptions.XmlWhitespaceSensitivity.get -> CSharpier.Core.XmlWhitespaceSensitivity CSharpier.Core.CodeFormatterOptions.XmlWhitespaceSensitivity.init -> void CSharpier.Core.XmlWhitespaceSensitivity CSharpier.Core.XmlWhitespaceSensitivity.Ignore = 1 -> CSharpier.Core.XmlWhitespaceSensitivity diff --git a/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs b/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs new file mode 100644 index 000000000..26a283f43 --- /dev/null +++ b/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs @@ -0,0 +1,146 @@ +using AwesomeAssertions; +using CSharpier.Core; +using CSharpier.Core.CSharp; + +namespace CSharpier.Tests; + +internal sealed class AllowFieldAttributeOnSameLineTests +{ + private static PrinterOptions CreateOptions(bool allowFieldAttributeOnSameLine) + { + return new PrinterOptions(Formatter.CSharp, XmlWhitespaceSensitivity.Strict) + { + Width = 100, + AllowFieldAttributeOnSameLine = allowFieldAttributeOnSameLine, + }; + } + + [Test] + public async Task Field_With_Single_Attribute_Stays_On_Same_Line_When_Enabled() + { + var code = "[SerializeField] private Button _buttonQuit;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[SerializeField] private Button _buttonQuit;"); + } + + [Test] + public async Task Field_With_Single_Attribute_Breaks_Line_When_Disabled() + { + var code = "[SerializeField] private Button _buttonQuit;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: false) + ); + result.Code.Should().Contain("[SerializeField]\n private Button _buttonQuit;"); + } + + [Test] + public async Task Field_With_Long_Attribute_Breaks_When_Exceeds_Width() + { + var code = + "[VeryLongAttributeName(SomeFlag.SomeValue, SomeOtherFlag.SomeOtherLongValue)] private Button _buttonQuit;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("]\n private Button _buttonQuit;"); + } + + [Test] + public async Task Field_With_Two_Attributes_Stays_On_Same_Line_When_Enabled() + { + var code = "[SerializeField] [HideInInspector] private Button _buttonQuit;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[SerializeField] [HideInInspector] private Button _buttonQuit;"); + } + + [Test] + public async Task Field_With_Two_Attributes_On_Separate_Lines_Preserves_Breaks_When_Enabled() + { + var code = "[Header(\"Title\")]\n [SerializeField] private Button _buttonQuit;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[Header(\"Title\")]\n [SerializeField] private Button _buttonQuit;"); + } + + [Test] + public async Task Field_With_Three_Attributes_Groups_Attrs_Then_Breaks_Field_When_Enabled() + { + var code = "[SerializeField] [HideInInspector] [Header(\"Title\")] private Text _labelTitle;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[SerializeField] [HideInInspector] [Header(\"Title\")]\n private Text _labelTitle;"); + } + + [Test] + public async Task Field_With_More_Than_Three_Attributes_Breaks_Lines_When_Enabled() + { + var code = + "[SerializeField]\n [HideInInspector]\n [Header(\"Title\")]\n [Tooltip(\"tip\")]\n private Text _labelTitle;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[SerializeField]\n [HideInInspector]\n [Header(\"Title\")]\n [Tooltip(\"tip\")]\n private Text _labelTitle;"); + } + + [Test] + public async Task Field_With_Three_Comma_Separated_Attrs_Breaks_Field_When_Enabled() + { + var code = "[Obsolete, NonSerialized, CLSCompliant(true)] private int _field;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("]\n private int _field;"); + } + + [Test] + public async Task Field_With_Mixed_Attrs_Totaling_Three_Breaks_Field_When_Enabled() + { + var code = "[Obsolete, NonSerialized]\n [Header(\"X\")]\n private int _field;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("]\n private int _field;"); + } + + [Test] + public async Task Field_With_Four_Comma_Separated_Attrs_Breaks_All_When_Enabled() + { + var code = + "[Obsolete, NonSerialized, CLSCompliant(true), Browsable(false)] private int _field;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("]\n private int _field;"); + } + + [Test] + public async Task Field_With_Two_Comma_Separated_Attrs_Stays_On_Same_Line_When_Enabled() + { + var code = "[Obsolete, NonSerialized] private int _field;\n"; + var result = await CSharpFormatter.FormatAsync( + WrapInClass(code), + CreateOptions(allowFieldAttributeOnSameLine: true) + ); + result.Code.Should().Contain("[Obsolete, NonSerialized] private int _field;"); + } + + private static string WrapInClass(string fieldCode) + { + return $"class TestClass\n{{\n {fieldCode}}}\n"; + } +} diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test index 562ba833f..4971044c9 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test @@ -17,8 +17,8 @@ class ClassName editAssignmentViewModel.InstructionalTextxxxxxxxxxx ?? string.Empty; value = - someLongValue__________________________________ - && someOtherValue__________________________________ + someLongValue__________________________________ && + someOtherValue__________________________________ ? trueValue : falseValue; @@ -71,8 +71,8 @@ class ClassName public SomeExpressionBodyMethod() => nonChainFormatting = anotherVariable1 = ( - someCondition________________________________ - || someOtherCondition___________________________ + someCondition________________________________ || + someOtherCondition___________________________ ); public SomeExpressionBodyMethod() => @@ -80,7 +80,7 @@ class ClassName anotherVariable1 = anotherVariable2 = ( - someCondition________________________________ - || someOtherCondition___________________________ + someCondition________________________________ || + someOtherCondition___________________________ ); } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test index 1c466035d..7487b952d 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test @@ -1,38 +1,38 @@ class TestClass { public string SomeProperty => - "someLongStringValue__________________________" - + "someOtherLongStringValue_______________________________"; + "someLongStringValue__________________________" + + "someOtherLongStringValue_______________________________"; void TestMethod() { var someVar = "a string" + thatIsJust(shortEnough) + "to not wrap"; var someLongVariableName = - "a long string with just concatenation" - + "will break this way" - + "because of reasons such as the fact it is too long"; + "a long string with just concatenation" + + "will break this way" + + "because of reasons such as the fact it is too long"; var someLongVariableName = - "a really loooooooooooooooong string" - + someMethodCall("with long args") - + "really long string"; + "a really loooooooooooooooong string" + + someMethodCall("with long args") + + "really long string"; var samePrecedenceAligns = - one_________________________________ - + two_______________________________ - - three_____________________________ - + four______________________________; + one_________________________________ + + two_______________________________ - + three_____________________________ + + four______________________________; var coalesceIsSpecial = - someValue_________________________ - ?? someOtherValue_______________________ - ?? someOtherValue_______________________; + someValue_________________________ ?? + someOtherValue_______________________ ?? + someOtherValue_______________________; coalesceIsSpecial ??= - someValue_________________________ - ?? someOtherValue_______________________ - ?? someOtherValue_______________________; + someValue_________________________ ?? + someOtherValue_______________________ ?? + someOtherValue_______________________; CallSomeLongMethodWithStringConcatenationThatShouldNotBreak( csharpDirectory + ".generated.cs", @@ -53,140 +53,116 @@ class TestClass true || false; var conditionalIndentation = someBoolean - ? someLongValue____________________________________ - + someLongValue____________________________________ - : someLongValue____________________________________ - + someLongValue____________________________________; + ? someLongValue____________________________________ + + someLongValue____________________________________ + : someLongValue____________________________________ + + someLongValue____________________________________; var someValue = - value1__________________ == value2_________________ - != (value3_______________________ == value4___________________); - - if ( - one == two - || someValue_______________ - == thisWillIndent_______________________________________________________________ - ) { } - - while ( - one == two - || someValue_______________ - == thisWillIndent_______________________________________________________________ - ) { } - - switch ( - one == two - || someValue_______________ - == thisWillIndent_______________________________________________________________ - ) { } + value1__________________ == value2_________________ != + (value3_______________________ == value4___________________); + + if (one == two || + someValue_______________ == + thisWillIndent_______________________________________________________________) { } + + while (one == two || + someValue_______________ == + thisWillIndent_______________________________________________________________) { } + + switch (one == two || + someValue_______________ == + thisWillIndent_______________________________________________________________) { } do { CallSomething(); - } while ( - one == two - || someValue_______________ - == thisWillIndent_______________________________________________________________ - ); + } while (one == two || + someValue_______________ == + thisWillIndent_______________________________________________________________); CallMethod( - "shouldIndentToMakeItClearWhereParametersAre" - + "someLongString_________________________________", + "shouldIndentToMakeItClearWhereParametersAre" + + "someLongString_________________________________", "SecondParameter" ); var y = someList.Where(o => - someLongValue_______________________ - && theseShouldNotIndent_________________ - && theseShouldNotIndent_________________ - > butThisOneShould_________________________________________ + someLongValue_______________________ && + theseShouldNotIndent_________________ && + theseShouldNotIndent_________________ > + butThisOneShould_________________________________________ ); var someVariable = CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) - && CallMethod() == someValue; + ) && + CallMethod() == someValue; var someValue = someLongThing___________________________.someLongThing_____________ ?? someOtherThing; - if ( - one - two == three - || one + two == three - || one * two == three - || one / two == three - || one % two == three - || one != three - || one < two - || one > two - || one <= two - || one >= two - || one is null - || one as Something == null - || one - two > three - || someLongThing - someOtherLongThing__________________________________ - > anotherLongThing - ) { } - - if ( - CallSomeMethod( + if (one - two == three || + one + two == three || + one * two == three || + one / two == three || + one % two == three || + one != three || + one < two || + one > two || + one <= two || + one >= two || + one is null || + one as Something == null || + one - two > three || + someLongThing - someOtherLongThing__________________________________ > anotherLongThing) + { } + + if (CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0 - ) { } + ) == 0) { } - if ( - someValue - && CallSomeMethod( + if (someValue && + CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0 - ) { } + ) == 0) { } - if ( - CallSomeMethod( + if (CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0 - && someValue - ) { } + ) == 0 && + someValue) { } - if ( - CallMethod( + if (CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) - && CallMethod( + ) && + CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) - ) { } + )) { } - if ( - CallMethod( + if (CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) || CallMethod(shortValue, "shortValue") - ) { } + ) || CallMethod(shortValue, "shortValue")) { } - if ( - CallMethod( + if (CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) - || CallMethod(shortValue, "shortValue") - || CallMethod(shortValue1, "shortValue1") - ) { } + ) || + CallMethod(shortValue, "shortValue") || + CallMethod(shortValue1, "shortValue1")) { } - if ( - CallSomeMethod(someParameter) - == someLongerValue_______________________________________________________________ - ) { } + if (CallSomeMethod(someParameter) == + someLongerValue_______________________________________________________________) { } - return someValue != someOtherValue - && someLongValue_____________________ == someOtherLongValue_____________________; + return someValue != someOtherValue && + someLongValue_____________________ == someOtherLongValue_____________________; var someValue = CallSomething( @@ -206,8 +182,8 @@ class TestClass .CallMethod( someLongValue__________________________________________, someLongValue__________________________________________ - ) - ?? someOtherValue; + ) ?? + someOtherValue; var x = someValue.CallMethod( @@ -264,8 +240,8 @@ class TestClass ) ) .CallMethod() - .CallMethod() - ?? someOtherValue; + .CallMethod() ?? + someOtherValue; var x = ( @@ -299,8 +275,8 @@ class TestClass ) ) .SomeProperty.CallMethod() - .CallMethod() - ?? someOtherValue; + .CallMethod() ?? + someOtherValue; var x = ( @@ -310,8 +286,8 @@ class TestClass ) ) ?.SomeProperty.CallMethod() - .CallMethod() - ?? someOtherValue; + .CallMethod() ?? + someOtherValue; var x = await CallMethodAsync( @@ -331,78 +307,78 @@ class TestClass .CallMethodAsync( someLongValue__________________________________________, someLongValue__________________________________________ - ) - ?? someOtherValue; + ) ?? + someOtherValue; var x = (IEnumerable?) - someValue.CallLongMethod____________________________________________________() - ?? someOtherValue; + someValue.CallLongMethod____________________________________________________() ?? + someOtherValue; var x = (IEnumerable?)( + someLongValue____________________________________________ ?? someLongValue____________________________________________ - ?? someLongValue____________________________________________ ) ?? someOtherValue; var x = someValue .Property.CallLongMethod_____________________________________() - .CallMethod__________() - ?? throw new Exception(); + .CallMethod__________() ?? + throw new Exception(); var x = someValue .Property.CallLongMethod_____________________________________() - .CallMethod__________(someParameter) - ?? throw new Exception(); + .CallMethod__________(someParameter) ?? + throw new Exception(); var x = someValue .Property.CallLongMethod_____________________________________() - .CallLongMethod___________________________________________________() - ?? throw new Exception(); + .CallLongMethod___________________________________________________() ?? + throw new Exception(); - return SomeObject.CallSomeMethod___________() - ?? SomeObject.CallSomeMethod___________() - ?? new SomeObject(); + return SomeObject.CallSomeMethod___________() ?? + SomeObject.CallSomeMethod___________() ?? + new SomeObject(); var storeObject = - entityType.GetSchemaQualifiedTableName() - ?? entityType.GetInsertStoredProcedure()?.GetSchemaQualifiedName() - ?? entityType.GetDeleteStoredProcedure()?.GetSchemaQualifiedName() - ?? entityType.GetUpdateStoredProcedure()?.GetSchemaQualifiedName(); + entityType.GetSchemaQualifiedTableName() ?? + entityType.GetInsertStoredProcedure()?.GetSchemaQualifiedName() ?? + entityType.GetDeleteStoredProcedure()?.GetSchemaQualifiedName() ?? + entityType.GetUpdateStoredProcedure()?.GetSchemaQualifiedName(); - return parameterDescriptor.BindingInfo.Binder - ?? Binders.GetBinder(parameterDescriptor.ParameterType); + return parameterDescriptor.BindingInfo.Binder ?? + Binders.GetBinder(parameterDescriptor.ParameterType); var x = - someValue.SomeCall()?.SomeCall().SomeProperty - ?? someValue.SomeCall()?.SomeCall().SomeProperty; + someValue.SomeCall()?.SomeCall().SomeProperty ?? + someValue.SomeCall()?.SomeCall().SomeProperty; var x = - someValue.SomeCall().SomeProperty.SomeProperty - ?? someValue.SomeCall().SomeProperty.SomeProperty; + someValue.SomeCall().SomeProperty.SomeProperty ?? + someValue.SomeCall().SomeProperty.SomeProperty; var x = - someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty - ?? someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty; + someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty ?? + someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty; var x = - someValue.SomeCall()?.SomeProperty_______________________ - ?? someValue.SomeCall()?.SomeProperty_______________________; + someValue.SomeCall()?.SomeProperty_______________________ ?? + someValue.SomeCall()?.SomeProperty_______________________; var x = - someValue.SomeCall().SomeProperty_______________________ - ?? someValue.SomeCall().SomeProperty_______________________; + someValue.SomeCall().SomeProperty_______________________ ?? + someValue.SomeCall().SomeProperty_______________________; var x = - someValue.SomeCall()?.A______().B______().C______() - ?? someValue.SomeCall()?.A______().B______().C______(); + someValue.SomeCall()?.A______().B______().C______() ?? + someValue.SomeCall()?.A______().B______().C______(); var x = - someValue.SomeCall().A_______.B_______.C_______ - ?? someValue.SomeCall().A_______.B_______.C_______; + someValue.SomeCall().A_______.B_______.C_______ ?? + someValue.SomeCall().A_______.B_______.C_______; var x = someValue switch @@ -418,10 +394,10 @@ class TestClass .Replace(someParameter_______________________, '.') + "."; UglyButConsistentWithPrettier( - someValue - == someLongThing__________________________________________________________________ - || someOtherValue - == someOtherLongThing________________________________________________, + someValue == + someLongThing__________________________________________________________________ || + someOtherValue == + someOtherLongThing________________________________________________, secondParameter ); diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test index 639df3cc7..f4a6cd5b2 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test @@ -13,8 +13,8 @@ class ClassName ); checked( - printsLikeInvocations - + whenItLongBreaks_______________________________________________ + printsLikeInvocations + + whenItLongBreaks_______________________________________________ ); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test index 1ceea30f0..654684c75 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test @@ -29,8 +29,8 @@ public class ClassName : someOtherThirdValue_______________________; var value = - someLongValue__________________________________ - && someOtherValue__________________________________ + someLongValue__________________________________ && + someOtherValue__________________________________ ? trueValue : falseValue; @@ -39,12 +39,12 @@ public class ClassName someCondition ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ - && someOtherCondition__________________________________ + someCondition_____________________________________ && + someOtherCondition__________________________________ ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ - && someOtherCondition__________________________________ + someCondition_____________________________________ && + someOtherCondition__________________________________ ); var fileContents = File.ReadAllText( @@ -68,28 +68,28 @@ public class ClassName : falseValue________________________________; return - someLongCondition____________________________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ && + someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ - is SomeLongType___________________________ + someLongCondition____________________________________ is + SomeLongType___________________________ ? trueValue________________________________ : falseValue_______________________________; return ( - someLongCondition____________________________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ && + someOtherLongCondition____________________________________ ) ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ - == someThingElse______________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ == + someThingElse______________________ && + someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; @@ -156,14 +156,14 @@ public class ClassName : "enUs"; var languageCode = - something____________________________________ - && someCondition______________________________________ + something____________________________________ && + someCondition______________________________________ ? something____________________________________ - : otherThing____________________________________ - && someCondition______________________________________ + : otherThing____________________________________ && + someCondition______________________________________ ? otherThing____________________________________ - : thingThing____________________________________ - && someCondition______________________________________ + : thingThing____________________________________ && + someCondition______________________________________ ? thingThing____________________________________ : "enUs"; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test index ed29d4f88..607980c9c 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test @@ -29,8 +29,8 @@ public class ClassName : someOtherThirdValue_______________________; var value = - someLongValue__________________________________ - && someOtherValue__________________________________ + someLongValue__________________________________ && + someOtherValue__________________________________ ? trueValue : falseValue; @@ -39,12 +39,12 @@ public class ClassName someCondition ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ - && someOtherCondition__________________________________ + someCondition_____________________________________ && + someOtherCondition__________________________________ ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ - && someOtherCondition__________________________________ + someCondition_____________________________________ && + someOtherCondition__________________________________ ); var fileContents = File.ReadAllText( @@ -68,28 +68,28 @@ public class ClassName : falseValue________________________________; return - someLongCondition____________________________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ && + someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ - is SomeLongType___________________________ + someLongCondition____________________________________ is + SomeLongType___________________________ ? trueValue________________________________ : falseValue_______________________________; return ( - someLongCondition____________________________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ && + someOtherLongCondition____________________________________ ) ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ - == someThingElse______________________ - && someOtherLongCondition____________________________________ + someLongCondition____________________________________ == + someThingElse______________________ && + someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test index a2368476e..2d92a7258 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test @@ -18,8 +18,7 @@ public class ClassName { public bool SomeProperty => #if !DEBUG - someValue - && // trailing comment with endif should work properly + someValue && // trailing comment with endif should work properly #endif someOtherValue; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test index 381879aae..7a0749b92 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test @@ -13,10 +13,9 @@ class ClassName do { return; - } while ( - initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) - && writeChildren - && reader.Read() - ); + } while (initialDepth - 1 < + reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) && + writeChildren && + reader.Read()); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test index 843096388..5019f77a2 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test @@ -24,10 +24,8 @@ public class ClassName { DoIf(); } - else if ( - jklasdfklalsdkfjlkasdflkaslkjfjsdkf - || kljadsfklaskldflkjasdfklaskjdfjklasdfjlkasdfjlkasdf - ) + else if (jklasdfklalsdkfjlkasdflkaslkjfjsdkf || + kljadsfklaskldflkjasdfklaskjdfjklasdfjlkasdfjlkasdf) { DoElse(); } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test index 62d29695e..a1204b518 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test @@ -8,10 +8,10 @@ public class ClassName private static readonly Regex FrontEndResourceRelativePathRegex = new Regex( @".*?/Themes/.*?/.*?/(.*)", - RegexOptions.Compiled - | RegexOptions.CultureInvariant - | RegexOptions.IgnoreCase - | RegexOptions.MakeThisBreak + RegexOptions.Compiled | + RegexOptions.CultureInvariant | + RegexOptions.IgnoreCase | + RegexOptions.MakeThisBreak ); private SomeObject SomeLongerName = new SomeObject( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test index ca1319ec8..31706ad37 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test @@ -53,8 +53,8 @@ class ClassName for ( var shorterName = 0; - someLongName____________ - < someOtherLongName__________________________________________________; + someLongName____________ < + someOtherLongName__________________________________________________; someLongishName_________________________++ ) { diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test index 7d9fdd7e9..5e390ab25 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test @@ -30,22 +30,18 @@ public class ClassName else DoSomeLongMethodCall________________________________________(); - if ( - longStatementName - && longerStatementName - && evenLongerStatementName - && superLongStatementName - ) + if (longStatementName && + longerStatementName && + evenLongerStatementName && + superLongStatementName) { return; } - if ( - longStatementName - && longerStatementName - && evenLongerStatementName - && superLongStatementName - ) + if (longStatementName && + longerStatementName && + evenLongerStatementName && + superLongStatementName) return; if (!true) { } @@ -67,18 +63,14 @@ public class ClassName // just fits } - if ( - someLongStatement == true - || someOtherStatement________________________________ == false - ) + if (someLongStatement == true || + someOtherStatement________________________________ == false) { // just too big } - if ( - someLongStatement == true - || someOtherStatement_________________________________ == false - ) + if (someLongStatement == true || + someOtherStatement_________________________________ == false) { // also too big } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test index 19cc7a121..69acd6bd1 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test @@ -190,8 +190,8 @@ class ClassName SomeOtherMethod(), this.CallSomeMethod________________________________________() .CallSomeMethod________________________________________(), + someLongCondition___________________________________ && someLongCondition___________________________________ - && someLongCondition___________________________________ ? one : two, }; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test index 1bac831c4..ed5f9b3cc 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test @@ -3,8 +3,7 @@ public class ClassName public string Test = $"test"; public string LeadingCommentWithInterpolatedString = - $"one" - + + $"one" + // comment stays on this line $"two"; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test index 20cf1704e..4b9bbbf87 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test @@ -25,13 +25,11 @@ if (expr is { Length: 5 }) return; } -if ( - expr is +if (expr is { SomeProperty: "someValue____________________", SomeOtherProperty: "someOtherValue__________________" - } -) + }) { return; } @@ -52,10 +50,8 @@ var useLine = ( or SyntaxKind.PlusToken ); -if ( - someRandomValue_______________________ is SomeRandomType someRandomType - && someRandomType.IsEnum -) +if (someRandomValue_______________________ is SomeRandomType someRandomType && + someRandomType.IsEnum) { return; } @@ -70,10 +66,8 @@ if (expr is { } noExtraSpaceBeforeOpenBrace) return; } -if ( - someValue_________________________ is SomeType_________________ someType - && someType.SomeProperty -) { } +if (someValue_________________________ is SomeType_________________ someType && + someType.SomeProperty) { } var value = someOtherValue is { Property: true }; @@ -110,8 +104,8 @@ var value = someOtherValue is SomeType___________________ or SomeOtherType___________________ - or SomeThirdType___________ - && someLongValue_________________; + or SomeThirdType___________ && + someLongValue_________________; var value = someOtherValue is @@ -143,135 +137,109 @@ if (someOtherValue is not (SomeType or SomeOtherType)) return; } -if ( - someOtherValue_________________ - is (SomeLongType_______________ or SomeOtherLongType_______________) -) +if (someOtherValue_________________ + is (SomeLongType_______________ or SomeOtherLongType_______________)) { return; } -if ( - someOtherValue_________________ - is not (SomeLongType_____________ or SomeOtherLongType_____________) -) +if (someOtherValue_________________ + is not (SomeLongType_____________ or SomeOtherLongType_____________)) { return; } -if ( - someOtherValue_____________ +if (someOtherValue_____________ is ( SomeLongType_____________________________________ or SomeLongType_____________________________________ - ) -) + )) { return; } -if ( - node is SomeType_______________________ +if (node is SomeType_______________________ { SomeProperty: SomeOtherType_____________________________ - } -) + }) { return; } -if ( - node is PrefixUnaryExpressionSyntax +if (node is PrefixUnaryExpressionSyntax { Operand: ParenthesizedExpressionSyntax { Expression: IsPatternExpressionSyntax or IsPatternExpressionSyntax }, - } -) + }) { return; } -if ( - node is PrefixUnaryExpressionSyntax +if (node is PrefixUnaryExpressionSyntax { Operand: { Expression: IsPatternExpressionSyntax or IsPatternExpressionSyntax______________________ }, - } -) + }) { return; } -if ( - !( +if (!( node is PrefixUnaryExpressionSyntax { Operand: ParenthesizedExpressionSyntax or IsPatternExpressionSyntax } - ) -) + )) { return; } -if ( - someLongName____________________________________________________ is - { } anotherLongName______________________ -) +if (someLongName____________________________________________________ is + { } anotherLongName______________________) { return; } -if ( - someLongVariableName____________ - is SomeLongTypeName______________________________ someOtherLongVariableName_____________ -) +if (someLongVariableName____________ + is SomeLongTypeName______________________________ someOtherLongVariableName_____________) { return; } -if ( - someArray[index] - is SomeLongTypeName______________________________ someOtherLongVariableName_____________ -) +if (someArray[index] + is SomeLongTypeName______________________________ someOtherLongVariableName_____________) { return; } -if ( - someLongName_____________________ +if (someLongName_____________________ is SomeObjectType or SomeOtherObjectType - or YetAnotherObjectType -) + or YetAnotherObjectType) { return; } -if ( - someCondition - && someLongName_____________ - is { Kind: SomeObjectType, Value: "___________________________________" } -) { } +if (someCondition && + someLongName_____________ + is { Kind: SomeObjectType, Value: "___________________________________" }) { } if (expr is { Property.Length: 5 }) { return; } -if ( - e is +if (e is #pragma warning disable CS0618 BadHttpRequestException #pragma warning restore CS0618 { Message: "______________________________________________________________________________________________________________" - } -) { } + }) { } var needsUpdatedRoslyn = y is y ? [] : z ?? []; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test index f0501989e..b3ad0932a 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test @@ -257,8 +257,8 @@ CallMethod( ); var someValue = - someValue - && o.Property.CallMethod_____________________________________________________() + someValue && + o.Property.CallMethod_____________________________________________________() .CallMethod_____________________________________________________(); o.Property.CallMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test index 7c0cce35b..cf2f7459f 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test @@ -112,9 +112,9 @@ class ClassName { get => _sourceType ??= - CustomMapExpression?.ReturnType - ?? CustomMapFunction?.ReturnType - ?? ( + CustomMapExpression?.ReturnType ?? + CustomMapFunction?.ReturnType ?? + ( _sourceMembers.Length > 0 ? _sourceMembers[_sourceMembers.Length - 1].GetMemberType() : Parameter.ParameterType @@ -138,14 +138,14 @@ class ClassName private bool VisitChildForCompare(Pair tuple, ref int result) { int r; - return 0 - != ( + return 0 != + ( result = (null == tuple.Item1) ? -1 : (null == tuple.Item2) ? +1 : 0 != (r = comparer.Compare(tuple.Item1.LocalName, tuple.Item2.LocalName)) ? r - : 0 - != (r = comparer.Compare(tuple.Item1.NamespaceURI, tuple.Item2.NamespaceURI)) + : 0 != + (r = comparer.Compare(tuple.Item1.NamespaceURI, tuple.Item2.NamespaceURI)) ? r : 0 ); diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test index 70ec26e76..fedba47a0 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test @@ -3,14 +3,14 @@ class ClassName void MethodName() { var x = - query - && ( - currentChar == '=' - || currentChar == '<' - || currentChar == '!' - || currentChar == '>' - || currentChar == '|' - || currentChar == '&' + query && + ( + currentChar == '=' || + currentChar == '<' || + currentChar == '!' || + currentChar == '>' || + currentChar == '|' || + currentChar == '&' ); var b2 = ( System.Environment.SpecialFolder.AdminTools diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test index 7bcacba8a..13107aa48 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test @@ -34,8 +34,8 @@ class ClassName var complexWhere = from c in customers where - c.Value == "true" - && someLongValueThatForcesABreak_________________________ != someOtherValue + c.Value == "true" && + someLongValueThatForcesABreak_________________________ != someOtherValue select d; var selectIntoQuery = from c in customers select c into d select d; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test index 2342b9aa6..24c99672e 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test @@ -12,8 +12,8 @@ class ClassName bool ReturnLongBinaryExpression() { - return someValueThatIsLongAndForcesALineBreak - || otherValueThatIsLongAndForcesALineBreak_____________________; + return someValueThatIsLongAndForcesALineBreak || + otherValueThatIsLongAndForcesALineBreak_____________________; } string LongMethodCallWithParameter() diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test index 3809d744d..53d2fab9d 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test @@ -109,8 +109,8 @@ public class ClassName ); this.Where(t => - t.SomeVeryLongColumn________________________________ - || t.OtherLongColumn________________________________ + t.SomeVeryLongColumn________________________________ || + t.OtherLongColumn________________________________ ); Select______________________________________(superLongName_________________________ => diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test index 0d2da16af..f807585e8 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test @@ -49,9 +49,9 @@ class ClassName SomeObject_______________________________________________ ) => "LongString_____________________________________________________________________", - OneMore => "someStrings" - + "moreStrings" - + "andMoreStrings_________________________________________", + OneMore => "someStrings" + + "moreStrings" + + "andMoreStrings_________________________________________", SomeOtherObject or AnotherObject or OrEvenSomeOtherObject_________________ => CallSomeMethod(someValue), SomeOtherObject { SomeProperty: SomeOtherProject } or AnotherObject => CallSomeMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test index 6951bd3a3..3ae27baf4 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test @@ -41,9 +41,9 @@ class ClassName ), VeryLongObject_______________________________________________________________ when count > 0 => CallSomeMethod(someValue), - OneMore => "someStrings" - + "moreStrings" - + "andMoreStrings_________________________________________", + OneMore => "someStrings" + + "moreStrings" + + "andMoreStrings_________________________________________", SomeOtherObject or AnotherObject or OrEvenSomeOtherObject_________________ => CallSomeMethod(someValue), SomeOtherObject { SomeProperty: SomeOtherProject } or AnotherObject => CallSomeMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test index 42ea00033..77dce0623 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test @@ -89,10 +89,8 @@ public class ClassName } } - switch ( - someLongValue - + someOtherLongValue_________________________________________________________ - ) + switch (someLongValue + + someOtherLongValue_________________________________________________________) { default: return; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test index e103d1cd1..d87a8b3b8 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test @@ -49,8 +49,8 @@ class ClassName throw new Exception(); } catch (Exception exception) - when (exception.Message.Contains("someLongValueThatMakesThisLineTooLong") - && someLongCondition == someOtherLongValue + when (exception.Message.Contains("someLongValueThatMakesThisLineTooLong") && + someLongCondition == someOtherLongValue ) { return; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test index 64b3564d0..4cf7c918c 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test @@ -13,8 +13,8 @@ class ClassName ); unchecked( - printsLikeInvocations - + whenItLongBreaks_______________________________________________ + printsLikeInvocations + + whenItLongBreaks_______________________________________________ ); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test index a9396cf94..d7043f4b0 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test @@ -54,8 +54,8 @@ class ClassName SqlParameterCollectionExtensions.DefaultValueColumnWidth + DefaultValueColumnWidth ]; var muchLongerOne_________________ = new byte[ - SqlParameterCollectionExtensions.DefaultValueColumnWidth - + SqlParameterCollectionExtensions.DefaultValueColumnWidth + SqlParameterCollectionExtensions.DefaultValueColumnWidth + + SqlParameterCollectionExtensions.DefaultValueColumnWidth ]; var elementAccessExpression1 = anArray[100]; @@ -72,8 +72,8 @@ class ClassName DefaultValueColumnWidth_________ + DefaultValueColumnWidth_______ ]; var shortOne______ = anArray[ - SqlParameterCollectionExtensions.DefaultValueColumnWidth - + SqlParameterCollectionExtensions.DefaultValueColumnWidth + SqlParameterCollectionExtensions.DefaultValueColumnWidth + + SqlParameterCollectionExtensions.DefaultValueColumnWidth ]; var someLongValue_________________ = memberAccessExpression[ @@ -94,17 +94,17 @@ class ClassName (ArrayType[])CallMethod(); var conditionalIndentation = someBoolean - ? someLongValue____________________________________ - + someLongValue____________________________________ - : someLongValue____________________________________ - + someLongValue____________________________________; + ? someLongValue____________________________________ + + someLongValue____________________________________ + : someLongValue____________________________________ + + someLongValue____________________________________; var longEnoughToMakeThisBreak = something == somethingElse ? shortValue__________ : otherShortValue; var value = - someLongValue__________________________________ - && someOtherValue__________________________________ + someLongValue__________________________________ && + someOtherValue__________________________________ ? trueValue : falseValue; @@ -175,8 +175,8 @@ withLineEnding" : someOtherValue; var someValue = - someLongCondition___________________________________ - && someOtheLongCondition___________________________________ + someLongCondition___________________________________ && + someOtheLongCondition___________________________________ ? someValue : someValue; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test index 6f979d467..221cc430d 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test @@ -12,11 +12,9 @@ class ClassName return; } - while ( - directoryInfo.Name != "Test" - && directoryInfo.Parent != null - && someLongCondition == "test" - ) + while (directoryInfo.Name != "Test" && + directoryInfo.Parent != null && + someLongCondition == "test") { directoryInfo = directoryInfo.Parent; } @@ -32,9 +30,8 @@ class ClassName return; } - while ( - justOver100 || moreTextToMakeItWork__________________________________________________ - ) + while (justOver100 || + moreTextToMakeItWork__________________________________________________) { return; } @@ -45,9 +42,8 @@ class ClassName while (someLongerStatement && someOtherLongerStatement________________) return someLongerValue; - while ( - someEvenLongerStatement && someOtherEvenLongerStatement________________________________ - ) + while (someEvenLongerStatement && + someOtherEvenLongerStatement________________________________) return someLongerValue; while (true) diff --git a/docs/Configuration.md b/docs/Configuration.md index 15832d7a0..9d57bb2f9 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -17,7 +17,8 @@ JSON "printWidth": 100, "useTabs": false, "indentSize": 4, - "endOfLine": "auto" + "endOfLine": "auto", + "allowFieldAttributeOnSameLine": false } ``` YAML @@ -26,6 +27,7 @@ printWidth: 100 useTabs: false indentSize: 4 endOfLine: auto +allowFieldAttributeOnSameLine: false ``` #### Print Width @@ -52,6 +54,28 @@ Valid options: Default `auto` +#### Allow Field Attribute On Same Line +When set to `true`, field attributes are allowed to stay on the same line, with tiered behavior based on attribute count. If the combined line exceeds the print width, it will also break. + +```csharp +// true (1-2 attrs): all on same line +// [SerializeField] private Button _buttonQuit; +// true (3 attrs): attributes on same line, field on new line +// [SerializeField] [HideInInspector] [Header("X")] +// private Text _label; +// true (4+ attrs): each on its own line +// [SerializeField] +// [HideInInspector] +// [Header("Title")] +// [Tooltip("tip")] +// private Text _labelTitle; +// false: always break (original behavior) +// [SerializeField] +// private Button _buttonQuit; +``` + +Default `false` + ### Configuration Overrides ### Overrides allows you to specify different configuration options based on glob patterns. This can be used to format non-standard extensions, or to change options based on file path. Top level options will apply to `**/*.{cs,csx}` From 3cf1f2bcbb5941aef55aa3c3c581d5652ed339f7 Mon Sep 17 00:00:00 2001 From: anqiang Date: Fri, 22 May 2026 19:47:35 +0800 Subject: [PATCH 2/9] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E6=96=B0?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E9=A3=8E=E6=A0=BC=20--=20resharper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MODIFICATIONS.md | 166 +++++----- .../Options/ConfigurationFileOptions.cs | 7 +- Src/CSharpier.Core/CSharp/CSharpFormatter.cs | 4 +- .../SyntaxPrinter/ArgumentListLikeSyntax.cs | 3 +- .../CSharp/SyntaxPrinter/AttributeLists.cs | 2 +- .../CSharp/SyntaxPrinter/PrintingContext.cs | 2 +- .../BaseFieldDeclaration.cs | 2 +- .../SyntaxNodePrinters/BinaryExpression.cs | 27 +- .../SyntaxNodePrinters/DoStatement.cs | 19 +- .../SyntaxNodePrinters/IfStatement.cs | 40 ++- .../SyntaxNodePrinters/SwitchStatement.cs | 25 +- .../SyntaxNodePrinters/WhileStatement.cs | 8 +- Src/CSharpier.Core/CodeFormatterOptions.cs | 4 +- Src/CSharpier.Core/PrinterOptions.cs | 8 +- Src/CSharpier.Core/PublicAPI.Unshipped.txt | 9 +- .../AllowFieldAttributeOnSameLineTests.cs | 4 +- .../TestFiles/cs/AssignmentExpressions.test | 12 +- .../TestFiles/cs/BinaryExpressions.test | 286 ++++++++++-------- .../TestFiles/cs/CheckedStatements.test | 4 +- .../TestFiles/cs/ConditionalExpressions.test | 42 +-- .../cs/ConditionalExpressions_Tabs.test | 30 +- .../TestFiles/cs/Directives.test | 3 +- .../TestFiles/cs/DoStatements.test | 9 +- .../TestFiles/cs/ElseStatements.test | 6 +- .../TestFiles/cs/FieldDeclarations.test | 8 +- .../TestFiles/cs/ForStatements.test | 4 +- .../TestFiles/cs/IfStatements.test | 32 +- .../TestFiles/cs/InitializerExpressions.test | 2 +- .../cs/InterpolatedStringExpressions.test | 3 +- .../TestFiles/cs/IsPatternExpressions.test | 102 ++++--- .../TestFiles/cs/MemberChains.test | 4 +- .../TestFiles/cs/ObnoxiousEdgeCases.test | 14 +- .../cs/ParenthesizedExpressions.test | 16 +- .../TestFiles/cs/QueryExpressions.test | 4 +- .../TestFiles/cs/ReturnStatements.test | 4 +- .../TestFiles/cs/SimpleLambdaExpressions.test | 4 +- .../TestFiles/cs/SwitchExpressions.test | 6 +- .../TestFiles/cs/SwitchExpressions_Tabs.test | 6 +- .../TestFiles/cs/SwitchStatements.test | 6 +- .../TestFiles/cs/TryStatements.test | 4 +- .../TestFiles/cs/UncheckedStatements.test | 4 +- .../TestFiles/cs/VariableDeclarations.test | 24 +- .../TestFiles/cs/WhileStatements.test | 18 +- 43 files changed, 568 insertions(+), 419 deletions(-) diff --git a/MODIFICATIONS.md b/MODIFICATIONS.md index 2671bab19..a1fb5e62c 100644 --- a/MODIFICATIONS.md +++ b/MODIFICATIONS.md @@ -1,95 +1,29 @@ -# CSharpier-Flex 魔修改记录 +# CSharpier-Flex 魔改记录 本文档记录对 CSharpier 原版所做的所有定制化修改。 --- -## 修改列表 - - - -### 2. 二元表达式操作符换行位置修改 - -**日期**:2026-05-22 - -**目的**:将二元表达式(`||`、`&&`、`+`、`==`、`??` 等)换行时操作符的位置从"下一行开头"改为"当前行末尾",使代码风格更符合 C# 社区常见习惯。 - -**修改前**(操作符在下一行开头): -```csharp -if ( - GameManager.Instance.gameMode == GameManager.GameMode.Classic - || GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge -) { } -``` - -**修改后**(操作符在当前行末尾): -```csharp -if (GameManager.Instance.gameMode == GameManager.GameMode.Classic || - GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge) -{ -``` - -**影响范围**: -- 所有使用二元操作符(`||`、`&&`、`+`、`-`、`==`、`!=`、`??` 等)且需要换行的表达式 -- 包括 `if` / `while` / `do-while` / `switch` 条件、变量赋值、`return` 语句、Lambda 表达式体等 - -**修改文件**: -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs` — 调整操作符与换行符的 Doc 顺序(操作符移到 `Doc.Line` 之前),同时同步修改 `??` 操作符的处理逻辑 -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs` — 去掉条件前后的 `Doc.IfBreak(SoftLine)`,将 `)` 纳入同一 `Doc.Group`,使条件紧跟 `if (` -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs` — 同步修改,去掉内层 `Doc.Group` + `SoftLine`,与 `if` 保持一致 -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs` — 同步修改 `do-while` 的条件括号风格 -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs` — 同步修改,将 `(` `)` 移入 `Doc.GroupWithId` 内 -- 31 个测试快照文件 — 更新所有涉及二元表达式换行和括号风格变化的快照 - ---- - -### 1. 新增配置项 `allowFieldAttributeOnSameLine` - -**日期**:2026-05-22 +## 配置方式 -**目的**:允许字段声明的属性(Attribute)与字段保持在同一行,而不是强制换行。适用于 Unity 项目中常见的 `[SerializeField] private Button _buttonQuit;` 风格。 +所有魔改行为统一由 `formattingStyle` 配置项控制: -**配置方式**(`.csharpierrc`): ```json +// .csharpierrc { - "allowFieldAttributeOnSameLine": true + "formattingStyle": "resharper", + "printWidth": 130 } ``` -**行为**: -- `false`(默认):属性与字段之间强制换行(原版行为) - ```csharp - [SerializeField] - private Button _buttonQuit; - ``` -- `true`:属性与字段允许在同一行,按数量分级处理: - ```csharp - // 1-2 个属性 → 全部同行 - [SerializeField] private Button _buttonQuit; - [SerializeField] [HideInInspector] private Text _label; - // 3 个属性 → 属性同行,字段换行 - [SerializeField] [HideInInspector] [Header("Title")] - private Text _labelTitle; - // 4+ 个属性 → 全部换行(原版行为) - [SerializeField] - [HideInInspector] - [Header("Title")] - [Tooltip("tip")] - private Text _labelTitle; - ``` +- `"default"`(默认,不写此项时):使用原版 CSharpier 格式化行为 +- `"resharper"`:启用下列所有修改 -**修改文件**: -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs` — 字段声明时根据配置选择 `Doc.Line`(可同行)或 `Doc.HardLine`(强制换行) -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs` — 启用时用 `Doc.Group` 包裹整个字段声明,使 `Doc.Line` 能折叠为空格 -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs` — `PrintingContextOptions` 新增属性 -- `Src/CSharpier.Core/PrinterOptions.cs` — 新增属性 -- `Src/CSharpier.Core/CodeFormatterOptions.cs` — 公共 API 新增属性 -- `Src/CSharpier.Core/CSharp/CSharpFormatter.cs` — 传递配置到 `PrintingContext` -- `Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs` — 配置文件解析新增字段 -- `Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs` — 测试用例 +--- +## 修改列表 ---- + ### 3. 方法调用尾部 Lambda 参数格式化 @@ -120,10 +54,78 @@ BindButton(_buttonChallenge, () => }); ``` -**触发条件**: -- 方法调用有 2 个及以上参数 -- 最后一个参数是 `ParenthesizedLambdaExpression`(`() => { ... }`)或 `SimpleLambdaExpression`(`x => { ... }`)且包含非空代码块 -- 不影响:单参数 lambda(已有专门处理)、表达式体 lambda(`() => expr`)、空 block lambda(`() => { }`) +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs` — 在默认多参数分支前插入新分支,非 lambda 参数内联打印,lambda 的 Body 直接跟在 Head 后 + +--- + +### 2. 二元表达式操作符换行位置 + 括号风格 + +**日期**:2026-05-22 + +**目的**:将二元表达式(`||`、`&&`、`+`、`==`、`??` 等)换行时操作符的位置从"下一行开头"改为"当前行末尾";同时统一 `if` / `while` / `do-while` / `switch` 的条件括号风格,使条件紧跟 `(`,`)` 紧跟最后一个条件。 + +**修改前**(操作符在下一行开头): +```csharp +if ( + GameManager.Instance.gameMode == GameManager.GameMode.Classic + || GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge +) { } +``` + +**修改后**(操作符在当前行末尾): +```csharp +if (GameManager.Instance.gameMode == GameManager.GameMode.Classic || + GameManager.Instance.gameMode == GameManager.GameMode.GroupChallenge) +{ +``` + +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs` — 条件化操作符与换行符的 Doc 顺序 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs` — 条件化括号风格 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs` — 同上 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs` — 同上 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs` — 同上 + +--- + +### 1. 字段属性同行 + +**日期**:2026-05-22 + +**目的**:允许字段声明的属性(Attribute)与字段保持在同一行,而不是强制换行。适用于 Unity 项目中常见的 `[SerializeField] private Button _buttonQuit;` 风格。 + +**行为**(`formattingStyle: "resharper"` 时生效): +```csharp +// 1-2 个属性 → 全部同行 +[SerializeField] private Button _buttonQuit; +[SerializeField] [HideInInspector] private Text _label; +// 3 个属性 → 属性同行,字段换行 +[SerializeField] [HideInInspector] [Header("Title")] +private Text _labelTitle; +// 4+ 个属性 → 全部换行(原版行为) +[SerializeField] +[HideInInspector] +[Header("Title")] +[Tooltip("tip")] +private Text _labelTitle; +``` + +**修改文件**: +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs` — 字段声明时根据 FormattingStyle 选择分隔符 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs` — 启用时用 `Doc.Group` 包裹 + +--- + +## 配置基础设施 + +**配置项 `formattingStyle`**(`"default"` / `"resharper"`)统一控制所有修改行为。 **修改文件**: -- `Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs` — 在默认多参数分支前插入新分支,非 lambda 参数内联打印,lambda 的 Body 用 `Doc.Indent` 包裹实现缩进 \ No newline at end of file +- `Src/CSharpier.Core/PrinterOptions.cs` — 新增 `FormattingStyle` 属性和 `public enum FormattingStyle` +- `Src/CSharpier.Core/CodeFormatterOptions.cs` — 公共 API 新增 `FormattingStyle` 属性 +- `Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs` — `PrintingContextOptions` 新增 `FormattingStyle` +- `Src/CSharpier.Core/CSharp/CSharpFormatter.cs` — 传递配置到 `PrintingContext` +- `Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs` — 配置文件解析新增字段 +- `Src/CSharpier.Core/PublicAPI.Unshipped.txt` — 更新公共 API 声明 +- `Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs` — 测试适配 diff --git a/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs b/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs index bd5f035fc..bab0d81f2 100644 --- a/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs +++ b/Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs @@ -16,7 +16,8 @@ internal class ConfigurationFileOptions [JsonConverter(typeof(CaseInsensitiveEnumConverter))] public EndOfLine EndOfLine { get; init; } - public bool AllowFieldAttributeOnSameLine { get; init; } + [JsonConverter(typeof(CaseInsensitiveEnumConverter))] + public FormattingStyle FormattingStyle { get; init; } public Override[] Overrides { get; init; } = []; @@ -47,7 +48,7 @@ out var parsedFormatter UseTabs = matchingOverride.UseTabs, Width = matchingOverride.PrintWidth, EndOfLine = matchingOverride.EndOfLine, - AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, + FormattingStyle = this.FormattingStyle, }; } @@ -64,7 +65,7 @@ out var parsedFormatter UseTabs = this.UseTabs, Width = this.PrintWidth, EndOfLine = this.EndOfLine, - AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, + FormattingStyle = this.FormattingStyle, }; } diff --git a/Src/CSharpier.Core/CSharp/CSharpFormatter.cs b/Src/CSharpier.Core/CSharp/CSharpFormatter.cs index d3ea30e19..ffaab7ccc 100644 --- a/Src/CSharpier.Core/CSharp/CSharpFormatter.cs +++ b/Src/CSharpier.Core/CSharp/CSharpFormatter.cs @@ -157,7 +157,7 @@ bool TryGetCompilationFailure(out CodeFormatterResult compilationResult) IndentSize = printerOptions.IndentSize, UseTabs = printerOptions.UseTabs, XmlWhitespaceSensitivity = XmlWhitespaceSensitivity.Strict, - AllowFieldAttributeOnSameLine = printerOptions.AllowFieldAttributeOnSameLine, + FormattingStyle = printerOptions.FormattingStyle, }, }; var document = Node.Print(rootNode, printingContext); @@ -186,7 +186,7 @@ bool TryGetCompilationFailure(out CodeFormatterResult compilationResult) IndentSize = printerOptions.IndentSize, UseTabs = printerOptions.UseTabs, XmlWhitespaceSensitivity = XmlWhitespaceSensitivity.Strict, - AllowFieldAttributeOnSameLine = printerOptions.AllowFieldAttributeOnSameLine, + FormattingStyle = printerOptions.FormattingStyle, }, }; document = Node.Print( diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs index 96aecae89..9492a6ea2 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/ArgumentListLikeSyntax.cs @@ -80,7 +80,8 @@ lambda.Block is not null args = SeparatedSyntaxList.Print(arguments, Argument.Print, Doc.Line, context); } else if ( - arguments.Count >= 2 + context.Options.FormattingStyle == FormattingStyle.Resharper + && arguments.Count >= 2 && arguments[arguments.Count - 1].Expression is ParenthesizedLambdaExpressionSyntax { Block.Statements.Count: > 0 } or SimpleLambdaExpressionSyntax { Body: BlockSyntax { Statements.Count: > 0 } } diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs index dd2c5f644..48898b5b6 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/AttributeLists.cs @@ -37,7 +37,7 @@ PrintingContext context var isFieldSameLine = node is BaseFieldDeclarationSyntax - && context.Options.AllowFieldAttributeOnSameLine; + && context.Options.FormattingStyle == FormattingStyle.Resharper; if (isFieldSameLine) { diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs index b249626e4..04db974db 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/PrintingContext.cs @@ -38,7 +38,7 @@ public class PrintingContextOptions public required int IndentSize { get; init; } public required bool UseTabs { get; init; } public required XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; init; } - public bool AllowFieldAttributeOnSameLine { get; init; } + public FormattingStyle FormattingStyle { get; init; } } public class PrintingContextState diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs index 4609e2c87..fc655e1f6 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BaseFieldDeclaration.cs @@ -9,7 +9,7 @@ internal static class BaseFieldDeclaration public static Doc Print(BaseFieldDeclarationSyntax node, PrintingContext context) { var canSameLine = - context.Options.AllowFieldAttributeOnSameLine + context.Options.FormattingStyle == FormattingStyle.Resharper && node.AttributeLists.Count > 0 && AttributeLists.GetTotalAttributeCount(node.AttributeLists) <= 2 && !AttributeLists.HasOriginalLineBreaks(node.AttributeLists); diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs index 199887b3a..ba63d33bb 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/BinaryExpression.cs @@ -88,11 +88,13 @@ private static List PrintBinaryExpression(SyntaxNode node, PrintingContext var binaryOnTheRight = binaryExpressionSyntax.Kind() == SyntaxKind.CoalesceExpression; if (binaryOnTheRight) { + var isResharper = + context.Options.FormattingStyle == FormattingStyle.Resharper; docs.Add( Node.Print(binaryExpressionSyntax.Left, context), - " ", + isResharper ? " " : Doc.Line, Token.Print(binaryExpressionSyntax.OperatorToken, context), - Doc.Line + isResharper ? Doc.Line : (Doc)" " ); } @@ -125,12 +127,21 @@ possibleBinary is BinaryExpressionSyntax childBinary return shouldGroup ? [docs[0], Doc.Group(docs.Skip(1).ToList())] : docs; } - var right = Doc.Concat( - " ", - Token.Print(binaryExpressionSyntax.OperatorToken, context), - Doc.Line, - Node.Print(binaryExpressionSyntax.Right, context) - ); + var isResharperStyle = + context.Options.FormattingStyle == FormattingStyle.Resharper; + var right = isResharperStyle + ? Doc.Concat( + " ", + Token.Print(binaryExpressionSyntax.OperatorToken, context), + Doc.Line, + Node.Print(binaryExpressionSyntax.Right, context) + ) + : Doc.Concat( + Doc.Line, + Token.Print(binaryExpressionSyntax.OperatorToken, context), + " ", + Node.Print(binaryExpressionSyntax.Right, context) + ); docs.Add(shouldGroup ? Doc.Group(right) : right); return docs; diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs index 975f8663f..8984d1f78 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/DoStatement.cs @@ -17,11 +17,20 @@ public static Doc Print(DoStatementSyntax node, PrintingContext context) Node.Print(node.Statement, context), node.Statement is BlockSyntax ? " " : Doc.HardLine, Token.PrintWithSuffix(node.WhileKeyword, " ", context), - Doc.Group( - Token.Print(node.OpenParenToken, context), - Doc.Indent(Node.Print(node.Condition, context)), - Token.Print(node.CloseParenToken, context) - ), + context.Options.FormattingStyle == FormattingStyle.Resharper + ? Doc.Group( + Token.Print(node.OpenParenToken, context), + Doc.Indent(Node.Print(node.Condition, context)), + Token.Print(node.CloseParenToken, context) + ) + : Doc.Concat( + Token.Print(node.OpenParenToken, context), + Doc.Group( + Doc.Indent(Doc.SoftLine, Node.Print(node.Condition, context)), + Doc.SoftLine + ), + Token.Print(node.CloseParenToken, context) + ), Token.Print(node.SemicolonToken, context) ); } diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs index 12f4ad251..94de9d095 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/IfStatement.cs @@ -14,16 +14,36 @@ public static Doc Print(IfStatementSyntax node, PrintingContext context) docs.Add(ExtraNewLines.Print(node)); } - docs.Add( - Token.Print(node.IfKeyword, context), - " ", - Doc.Group( - Token.Print(node.OpenParenToken, context), - Doc.Indent(Node.Print(node.Condition, context)), - Token.Print(node.CloseParenToken, context) - ), - OptionalBraces.Print(node.Statement, context) - ); + if (context.Options.FormattingStyle == FormattingStyle.Resharper) + { + docs.Add( + Token.Print(node.IfKeyword, context), + " ", + Doc.Group( + Token.Print(node.OpenParenToken, context), + Doc.Indent(Node.Print(node.Condition, context)), + Token.Print(node.CloseParenToken, context) + ), + OptionalBraces.Print(node.Statement, context) + ); + } + else + { + docs.Add( + Token.Print(node.IfKeyword, context), + " ", + Doc.Group( + Token.Print(node.OpenParenToken, context), + Doc.Indent( + Doc.IfBreak(Doc.SoftLine, Doc.Null), + Node.Print(node.Condition, context) + ), + Doc.IfBreak(Doc.SoftLine, Doc.Null) + ), + Token.Print(node.CloseParenToken, context), + OptionalBraces.Print(node.Statement, context) + ); + } if (node.Else != null) { diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs index 9dbd1c420..3531d4e18 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/SwitchStatement.cs @@ -33,12 +33,25 @@ public static Doc Print(SwitchStatementSyntax node, PrintingContext context) Doc.Group( Token.PrintWithoutLeadingTrivia(node.SwitchKeyword, context), " ", - Doc.GroupWithId( - groupId, - Token.Print(node.OpenParenToken, context), - Doc.Indent(Node.Print(node.Expression, context)), - Token.Print(node.CloseParenToken, context) - ), + context.Options.FormattingStyle == FormattingStyle.Resharper + ? Doc.GroupWithId( + groupId, + Token.Print(node.OpenParenToken, context), + Doc.Indent(Node.Print(node.Expression, context)), + Token.Print(node.CloseParenToken, context) + ) + : Doc.Concat( + Token.Print(node.OpenParenToken, context), + Doc.GroupWithId( + groupId, + Doc.Indent( + Doc.SoftLine, + Node.Print(node.Expression, context) + ), + Doc.SoftLine + ), + Token.Print(node.CloseParenToken, context) + ), node.Sections.Count == 0 ? " " : Doc.Line, Token.Print(node.OpenBraceToken, context), sections, diff --git a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs index ae1b979ff..5ca341620 100644 --- a/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs +++ b/Src/CSharpier.Core/CSharp/SyntaxPrinter/SyntaxNodePrinters/WhileStatement.cs @@ -7,13 +7,19 @@ internal static class WhileStatement { public static Doc Print(WhileStatementSyntax node, PrintingContext context) { + var isResharper = context.Options.FormattingStyle == FormattingStyle.Resharper; var result = Doc.Concat( ExtraNewLines.Print(node), Doc.Group( Token.Print(node.WhileKeyword, context), " ", Token.Print(node.OpenParenToken, context), - Doc.Indent(Node.Print(node.Condition, context)), + isResharper + ? Doc.Indent(Node.Print(node.Condition, context)) + : Doc.Group( + Doc.Indent(Doc.SoftLine, Node.Print(node.Condition, context)), + Doc.SoftLine + ), Token.Print(node.CloseParenToken, context) ), node.Statement switch diff --git a/Src/CSharpier.Core/CodeFormatterOptions.cs b/Src/CSharpier.Core/CodeFormatterOptions.cs index 9292aaa23..625fa2bd3 100644 --- a/Src/CSharpier.Core/CodeFormatterOptions.cs +++ b/Src/CSharpier.Core/CodeFormatterOptions.cs @@ -7,7 +7,7 @@ public class CodeFormatterOptions public int IndentSize { get; init; } = 4; public EndOfLine EndOfLine { get; init; } = EndOfLine.Auto; public bool IncludeGenerated { get; init; } - public bool AllowFieldAttributeOnSameLine { get; init; } + public FormattingStyle FormattingStyle { get; init; } public XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; init; } = XmlWhitespaceSensitivity.Strict; @@ -20,7 +20,7 @@ internal PrinterOptions ToPrinterOptions() IndentSize = this.IndentSize, EndOfLine = this.EndOfLine, IncludeGenerated = this.IncludeGenerated, - AllowFieldAttributeOnSameLine = this.AllowFieldAttributeOnSameLine, + FormattingStyle = this.FormattingStyle, }; } } diff --git a/Src/CSharpier.Core/PrinterOptions.cs b/Src/CSharpier.Core/PrinterOptions.cs index 0e34750ec..4105a209d 100644 --- a/Src/CSharpier.Core/PrinterOptions.cs +++ b/Src/CSharpier.Core/PrinterOptions.cs @@ -29,7 +29,7 @@ public int IndentSize public EndOfLine EndOfLine { get; set; } = EndOfLine.Auto; public bool TrimInitialLines { get; init; } = true; public bool IncludeGenerated { get; set; } - public bool AllowFieldAttributeOnSameLine { get; set; } + public FormattingStyle FormattingStyle { get; set; } public Formatter Formatter { get; } = formatter; public XmlWhitespaceSensitivity XmlWhitespaceSensitivity { get; set; } = xmlWhitespaceSensitivity; @@ -101,3 +101,9 @@ internal enum Formatter CSharpScript, XML, } + +public enum FormattingStyle +{ + Default, + Resharper, +} diff --git a/Src/CSharpier.Core/PublicAPI.Unshipped.txt b/Src/CSharpier.Core/PublicAPI.Unshipped.txt index 5ade7e860..426fe35c5 100644 --- a/Src/CSharpier.Core/PublicAPI.Unshipped.txt +++ b/Src/CSharpier.Core/PublicAPI.Unshipped.txt @@ -1,7 +1,10 @@ -CSharpier.Core.CodeFormatterOptions.AllowFieldAttributeOnSameLine.get -> bool -CSharpier.Core.CodeFormatterOptions.AllowFieldAttributeOnSameLine.init -> void +CSharpier.Core.CodeFormatterOptions.FormattingStyle.get -> CSharpier.Core.FormattingStyle +CSharpier.Core.CodeFormatterOptions.FormattingStyle.init -> void CSharpier.Core.CodeFormatterOptions.XmlWhitespaceSensitivity.get -> CSharpier.Core.XmlWhitespaceSensitivity CSharpier.Core.CodeFormatterOptions.XmlWhitespaceSensitivity.init -> void +CSharpier.Core.FormattingStyle +CSharpier.Core.FormattingStyle.Default = 0 -> CSharpier.Core.FormattingStyle +CSharpier.Core.FormattingStyle.Resharper = 1 -> CSharpier.Core.FormattingStyle CSharpier.Core.XmlWhitespaceSensitivity CSharpier.Core.XmlWhitespaceSensitivity.Ignore = 1 -> CSharpier.Core.XmlWhitespaceSensitivity -CSharpier.Core.XmlWhitespaceSensitivity.Strict = 0 -> CSharpier.Core.XmlWhitespaceSensitivity \ No newline at end of file +CSharpier.Core.XmlWhitespaceSensitivity.Strict = 0 -> CSharpier.Core.XmlWhitespaceSensitivity diff --git a/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs b/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs index 26a283f43..c76edee98 100644 --- a/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs +++ b/Src/CSharpier.Tests/AllowFieldAttributeOnSameLineTests.cs @@ -11,7 +11,9 @@ private static PrinterOptions CreateOptions(bool allowFieldAttributeOnSameLine) return new PrinterOptions(Formatter.CSharp, XmlWhitespaceSensitivity.Strict) { Width = 100, - AllowFieldAttributeOnSameLine = allowFieldAttributeOnSameLine, + FormattingStyle = allowFieldAttributeOnSameLine + ? FormattingStyle.Resharper + : FormattingStyle.Default, }; } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test index 4971044c9..562ba833f 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/AssignmentExpressions.test @@ -17,8 +17,8 @@ class ClassName editAssignmentViewModel.InstructionalTextxxxxxxxxxx ?? string.Empty; value = - someLongValue__________________________________ && - someOtherValue__________________________________ + someLongValue__________________________________ + && someOtherValue__________________________________ ? trueValue : falseValue; @@ -71,8 +71,8 @@ class ClassName public SomeExpressionBodyMethod() => nonChainFormatting = anotherVariable1 = ( - someCondition________________________________ || - someOtherCondition___________________________ + someCondition________________________________ + || someOtherCondition___________________________ ); public SomeExpressionBodyMethod() => @@ -80,7 +80,7 @@ class ClassName anotherVariable1 = anotherVariable2 = ( - someCondition________________________________ || - someOtherCondition___________________________ + someCondition________________________________ + || someOtherCondition___________________________ ); } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test index 7487b952d..1c466035d 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/BinaryExpressions.test @@ -1,38 +1,38 @@ class TestClass { public string SomeProperty => - "someLongStringValue__________________________" + - "someOtherLongStringValue_______________________________"; + "someLongStringValue__________________________" + + "someOtherLongStringValue_______________________________"; void TestMethod() { var someVar = "a string" + thatIsJust(shortEnough) + "to not wrap"; var someLongVariableName = - "a long string with just concatenation" + - "will break this way" + - "because of reasons such as the fact it is too long"; + "a long string with just concatenation" + + "will break this way" + + "because of reasons such as the fact it is too long"; var someLongVariableName = - "a really loooooooooooooooong string" + - someMethodCall("with long args") + - "really long string"; + "a really loooooooooooooooong string" + + someMethodCall("with long args") + + "really long string"; var samePrecedenceAligns = - one_________________________________ + - two_______________________________ - - three_____________________________ + - four______________________________; + one_________________________________ + + two_______________________________ + - three_____________________________ + + four______________________________; var coalesceIsSpecial = - someValue_________________________ ?? - someOtherValue_______________________ ?? - someOtherValue_______________________; + someValue_________________________ + ?? someOtherValue_______________________ + ?? someOtherValue_______________________; coalesceIsSpecial ??= - someValue_________________________ ?? - someOtherValue_______________________ ?? - someOtherValue_______________________; + someValue_________________________ + ?? someOtherValue_______________________ + ?? someOtherValue_______________________; CallSomeLongMethodWithStringConcatenationThatShouldNotBreak( csharpDirectory + ".generated.cs", @@ -53,116 +53,140 @@ class TestClass true || false; var conditionalIndentation = someBoolean - ? someLongValue____________________________________ + - someLongValue____________________________________ - : someLongValue____________________________________ + - someLongValue____________________________________; + ? someLongValue____________________________________ + + someLongValue____________________________________ + : someLongValue____________________________________ + + someLongValue____________________________________; var someValue = - value1__________________ == value2_________________ != - (value3_______________________ == value4___________________); - - if (one == two || - someValue_______________ == - thisWillIndent_______________________________________________________________) { } - - while (one == two || - someValue_______________ == - thisWillIndent_______________________________________________________________) { } - - switch (one == two || - someValue_______________ == - thisWillIndent_______________________________________________________________) { } + value1__________________ == value2_________________ + != (value3_______________________ == value4___________________); + + if ( + one == two + || someValue_______________ + == thisWillIndent_______________________________________________________________ + ) { } + + while ( + one == two + || someValue_______________ + == thisWillIndent_______________________________________________________________ + ) { } + + switch ( + one == two + || someValue_______________ + == thisWillIndent_______________________________________________________________ + ) { } do { CallSomething(); - } while (one == two || - someValue_______________ == - thisWillIndent_______________________________________________________________); + } while ( + one == two + || someValue_______________ + == thisWillIndent_______________________________________________________________ + ); CallMethod( - "shouldIndentToMakeItClearWhereParametersAre" + - "someLongString_________________________________", + "shouldIndentToMakeItClearWhereParametersAre" + + "someLongString_________________________________", "SecondParameter" ); var y = someList.Where(o => - someLongValue_______________________ && - theseShouldNotIndent_________________ && - theseShouldNotIndent_________________ > - butThisOneShould_________________________________________ + someLongValue_______________________ + && theseShouldNotIndent_________________ + && theseShouldNotIndent_________________ + > butThisOneShould_________________________________________ ); var someVariable = CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) && - CallMethod() == someValue; + ) + && CallMethod() == someValue; var someValue = someLongThing___________________________.someLongThing_____________ ?? someOtherThing; - if (one - two == three || - one + two == three || - one * two == three || - one / two == three || - one % two == three || - one != three || - one < two || - one > two || - one <= two || - one >= two || - one is null || - one as Something == null || - one - two > three || - someLongThing - someOtherLongThing__________________________________ > anotherLongThing) - { } - - if (CallSomeMethod( + if ( + one - two == three + || one + two == three + || one * two == three + || one / two == three + || one % two == three + || one != three + || one < two + || one > two + || one <= two + || one >= two + || one is null + || one as Something == null + || one - two > three + || someLongThing - someOtherLongThing__________________________________ + > anotherLongThing + ) { } + + if ( + CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0) { } + ) == 0 + ) { } - if (someValue && - CallSomeMethod( + if ( + someValue + && CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0) { } + ) == 0 + ) { } - if (CallSomeMethod( + if ( + CallSomeMethod( someParameter_____________________________________, someParameter_____________________________________ - ) == 0 && - someValue) { } + ) == 0 + && someValue + ) { } - if (CallMethod( + if ( + CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) && - CallMethod( + ) + && CallMethod( someParameter_____________________________________, someParameter_____________________________________ - )) { } + ) + ) { } - if (CallMethod( + if ( + CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) || CallMethod(shortValue, "shortValue")) { } + ) || CallMethod(shortValue, "shortValue") + ) { } - if (CallMethod( + if ( + CallMethod( someParameter_____________________________________, someParameter_____________________________________ - ) || - CallMethod(shortValue, "shortValue") || - CallMethod(shortValue1, "shortValue1")) { } + ) + || CallMethod(shortValue, "shortValue") + || CallMethod(shortValue1, "shortValue1") + ) { } - if (CallSomeMethod(someParameter) == - someLongerValue_______________________________________________________________) { } + if ( + CallSomeMethod(someParameter) + == someLongerValue_______________________________________________________________ + ) { } - return someValue != someOtherValue && - someLongValue_____________________ == someOtherLongValue_____________________; + return someValue != someOtherValue + && someLongValue_____________________ == someOtherLongValue_____________________; var someValue = CallSomething( @@ -182,8 +206,8 @@ class TestClass .CallMethod( someLongValue__________________________________________, someLongValue__________________________________________ - ) ?? - someOtherValue; + ) + ?? someOtherValue; var x = someValue.CallMethod( @@ -240,8 +264,8 @@ class TestClass ) ) .CallMethod() - .CallMethod() ?? - someOtherValue; + .CallMethod() + ?? someOtherValue; var x = ( @@ -275,8 +299,8 @@ class TestClass ) ) .SomeProperty.CallMethod() - .CallMethod() ?? - someOtherValue; + .CallMethod() + ?? someOtherValue; var x = ( @@ -286,8 +310,8 @@ class TestClass ) ) ?.SomeProperty.CallMethod() - .CallMethod() ?? - someOtherValue; + .CallMethod() + ?? someOtherValue; var x = await CallMethodAsync( @@ -307,78 +331,78 @@ class TestClass .CallMethodAsync( someLongValue__________________________________________, someLongValue__________________________________________ - ) ?? - someOtherValue; + ) + ?? someOtherValue; var x = (IEnumerable?) - someValue.CallLongMethod____________________________________________________() ?? - someOtherValue; + someValue.CallLongMethod____________________________________________________() + ?? someOtherValue; var x = (IEnumerable?)( - someLongValue____________________________________________ ?? someLongValue____________________________________________ + ?? someLongValue____________________________________________ ) ?? someOtherValue; var x = someValue .Property.CallLongMethod_____________________________________() - .CallMethod__________() ?? - throw new Exception(); + .CallMethod__________() + ?? throw new Exception(); var x = someValue .Property.CallLongMethod_____________________________________() - .CallMethod__________(someParameter) ?? - throw new Exception(); + .CallMethod__________(someParameter) + ?? throw new Exception(); var x = someValue .Property.CallLongMethod_____________________________________() - .CallLongMethod___________________________________________________() ?? - throw new Exception(); + .CallLongMethod___________________________________________________() + ?? throw new Exception(); - return SomeObject.CallSomeMethod___________() ?? - SomeObject.CallSomeMethod___________() ?? - new SomeObject(); + return SomeObject.CallSomeMethod___________() + ?? SomeObject.CallSomeMethod___________() + ?? new SomeObject(); var storeObject = - entityType.GetSchemaQualifiedTableName() ?? - entityType.GetInsertStoredProcedure()?.GetSchemaQualifiedName() ?? - entityType.GetDeleteStoredProcedure()?.GetSchemaQualifiedName() ?? - entityType.GetUpdateStoredProcedure()?.GetSchemaQualifiedName(); + entityType.GetSchemaQualifiedTableName() + ?? entityType.GetInsertStoredProcedure()?.GetSchemaQualifiedName() + ?? entityType.GetDeleteStoredProcedure()?.GetSchemaQualifiedName() + ?? entityType.GetUpdateStoredProcedure()?.GetSchemaQualifiedName(); - return parameterDescriptor.BindingInfo.Binder ?? - Binders.GetBinder(parameterDescriptor.ParameterType); + return parameterDescriptor.BindingInfo.Binder + ?? Binders.GetBinder(parameterDescriptor.ParameterType); var x = - someValue.SomeCall()?.SomeCall().SomeProperty ?? - someValue.SomeCall()?.SomeCall().SomeProperty; + someValue.SomeCall()?.SomeCall().SomeProperty + ?? someValue.SomeCall()?.SomeCall().SomeProperty; var x = - someValue.SomeCall().SomeProperty.SomeProperty ?? - someValue.SomeCall().SomeProperty.SomeProperty; + someValue.SomeCall().SomeProperty.SomeProperty + ?? someValue.SomeCall().SomeProperty.SomeProperty; var x = - someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty ?? - someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty; + someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty + ?? someValue.SomeCall().SomeProperty?.SomeCall().SomeProperty; var x = - someValue.SomeCall()?.SomeProperty_______________________ ?? - someValue.SomeCall()?.SomeProperty_______________________; + someValue.SomeCall()?.SomeProperty_______________________ + ?? someValue.SomeCall()?.SomeProperty_______________________; var x = - someValue.SomeCall().SomeProperty_______________________ ?? - someValue.SomeCall().SomeProperty_______________________; + someValue.SomeCall().SomeProperty_______________________ + ?? someValue.SomeCall().SomeProperty_______________________; var x = - someValue.SomeCall()?.A______().B______().C______() ?? - someValue.SomeCall()?.A______().B______().C______(); + someValue.SomeCall()?.A______().B______().C______() + ?? someValue.SomeCall()?.A______().B______().C______(); var x = - someValue.SomeCall().A_______.B_______.C_______ ?? - someValue.SomeCall().A_______.B_______.C_______; + someValue.SomeCall().A_______.B_______.C_______ + ?? someValue.SomeCall().A_______.B_______.C_______; var x = someValue switch @@ -394,10 +418,10 @@ class TestClass .Replace(someParameter_______________________, '.') + "."; UglyButConsistentWithPrettier( - someValue == - someLongThing__________________________________________________________________ || - someOtherValue == - someOtherLongThing________________________________________________, + someValue + == someLongThing__________________________________________________________________ + || someOtherValue + == someOtherLongThing________________________________________________, secondParameter ); diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test index f4a6cd5b2..639df3cc7 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/CheckedStatements.test @@ -13,8 +13,8 @@ class ClassName ); checked( - printsLikeInvocations + - whenItLongBreaks_______________________________________________ + printsLikeInvocations + + whenItLongBreaks_______________________________________________ ); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test index 654684c75..1ceea30f0 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions.test @@ -29,8 +29,8 @@ public class ClassName : someOtherThirdValue_______________________; var value = - someLongValue__________________________________ && - someOtherValue__________________________________ + someLongValue__________________________________ + && someOtherValue__________________________________ ? trueValue : falseValue; @@ -39,12 +39,12 @@ public class ClassName someCondition ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ && - someOtherCondition__________________________________ + someCondition_____________________________________ + && someOtherCondition__________________________________ ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ && - someOtherCondition__________________________________ + someCondition_____________________________________ + && someOtherCondition__________________________________ ); var fileContents = File.ReadAllText( @@ -68,28 +68,28 @@ public class ClassName : falseValue________________________________; return - someLongCondition____________________________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + && someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ is - SomeLongType___________________________ + someLongCondition____________________________________ + is SomeLongType___________________________ ? trueValue________________________________ : falseValue_______________________________; return ( - someLongCondition____________________________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + && someOtherLongCondition____________________________________ ) ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ == - someThingElse______________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + == someThingElse______________________ + && someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; @@ -156,14 +156,14 @@ public class ClassName : "enUs"; var languageCode = - something____________________________________ && - someCondition______________________________________ + something____________________________________ + && someCondition______________________________________ ? something____________________________________ - : otherThing____________________________________ && - someCondition______________________________________ + : otherThing____________________________________ + && someCondition______________________________________ ? otherThing____________________________________ - : thingThing____________________________________ && - someCondition______________________________________ + : thingThing____________________________________ + && someCondition______________________________________ ? thingThing____________________________________ : "enUs"; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test index 607980c9c..ed29d4f88 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ConditionalExpressions_Tabs.test @@ -29,8 +29,8 @@ public class ClassName : someOtherThirdValue_______________________; var value = - someLongValue__________________________________ && - someOtherValue__________________________________ + someLongValue__________________________________ + && someOtherValue__________________________________ ? trueValue : falseValue; @@ -39,12 +39,12 @@ public class ClassName someCondition ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ && - someOtherCondition__________________________________ + someCondition_____________________________________ + && someOtherCondition__________________________________ ? trueValue________________________________ : falseValue_______________________________, - someCondition_____________________________________ && - someOtherCondition__________________________________ + someCondition_____________________________________ + && someOtherCondition__________________________________ ); var fileContents = File.ReadAllText( @@ -68,28 +68,28 @@ public class ClassName : falseValue________________________________; return - someLongCondition____________________________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + && someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ is - SomeLongType___________________________ + someLongCondition____________________________________ + is SomeLongType___________________________ ? trueValue________________________________ : falseValue_______________________________; return ( - someLongCondition____________________________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + && someOtherLongCondition____________________________________ ) ? trueValue________________________________ : falseValue_______________________________; return - someLongCondition____________________________________ == - someThingElse______________________ && - someOtherLongCondition____________________________________ + someLongCondition____________________________________ + == someThingElse______________________ + && someOtherLongCondition____________________________________ ? trueValue________________________________ : falseValue_______________________________; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test index 2d92a7258..a2368476e 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/Directives.test @@ -18,7 +18,8 @@ public class ClassName { public bool SomeProperty => #if !DEBUG - someValue && // trailing comment with endif should work properly + someValue + && // trailing comment with endif should work properly #endif someOtherValue; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test index 7a0749b92..381879aae 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/DoStatements.test @@ -13,9 +13,10 @@ class ClassName do { return; - } while (initialDepth - 1 < - reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) && - writeChildren && - reader.Read()); + } while ( + initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) + && writeChildren + && reader.Read() + ); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test index 5019f77a2..843096388 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ElseStatements.test @@ -24,8 +24,10 @@ public class ClassName { DoIf(); } - else if (jklasdfklalsdkfjlkasdflkaslkjfjsdkf || - kljadsfklaskldflkjasdfklaskjdfjklasdfjlkasdfjlkasdf) + else if ( + jklasdfklalsdkfjlkasdflkaslkjfjsdkf + || kljadsfklaskldflkjasdfklaskjdfjklasdfjlkasdfjlkasdf + ) { DoElse(); } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test index a1204b518..62d29695e 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/FieldDeclarations.test @@ -8,10 +8,10 @@ public class ClassName private static readonly Regex FrontEndResourceRelativePathRegex = new Regex( @".*?/Themes/.*?/.*?/(.*)", - RegexOptions.Compiled | - RegexOptions.CultureInvariant | - RegexOptions.IgnoreCase | - RegexOptions.MakeThisBreak + RegexOptions.Compiled + | RegexOptions.CultureInvariant + | RegexOptions.IgnoreCase + | RegexOptions.MakeThisBreak ); private SomeObject SomeLongerName = new SomeObject( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test index 31706ad37..ca1319ec8 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ForStatements.test @@ -53,8 +53,8 @@ class ClassName for ( var shorterName = 0; - someLongName____________ < - someOtherLongName__________________________________________________; + someLongName____________ + < someOtherLongName__________________________________________________; someLongishName_________________________++ ) { diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test index 5e390ab25..7d9fdd7e9 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IfStatements.test @@ -30,18 +30,22 @@ public class ClassName else DoSomeLongMethodCall________________________________________(); - if (longStatementName && - longerStatementName && - evenLongerStatementName && - superLongStatementName) + if ( + longStatementName + && longerStatementName + && evenLongerStatementName + && superLongStatementName + ) { return; } - if (longStatementName && - longerStatementName && - evenLongerStatementName && - superLongStatementName) + if ( + longStatementName + && longerStatementName + && evenLongerStatementName + && superLongStatementName + ) return; if (!true) { } @@ -63,14 +67,18 @@ public class ClassName // just fits } - if (someLongStatement == true || - someOtherStatement________________________________ == false) + if ( + someLongStatement == true + || someOtherStatement________________________________ == false + ) { // just too big } - if (someLongStatement == true || - someOtherStatement_________________________________ == false) + if ( + someLongStatement == true + || someOtherStatement_________________________________ == false + ) { // also too big } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test index 69acd6bd1..19cc7a121 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InitializerExpressions.test @@ -190,8 +190,8 @@ class ClassName SomeOtherMethod(), this.CallSomeMethod________________________________________() .CallSomeMethod________________________________________(), - someLongCondition___________________________________ && someLongCondition___________________________________ + && someLongCondition___________________________________ ? one : two, }; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test index ed5f9b3cc..1bac831c4 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/InterpolatedStringExpressions.test @@ -3,7 +3,8 @@ public class ClassName public string Test = $"test"; public string LeadingCommentWithInterpolatedString = - $"one" + + $"one" + + // comment stays on this line $"two"; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test index 4b9bbbf87..20cf1704e 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/IsPatternExpressions.test @@ -25,11 +25,13 @@ if (expr is { Length: 5 }) return; } -if (expr is +if ( + expr is { SomeProperty: "someValue____________________", SomeOtherProperty: "someOtherValue__________________" - }) + } +) { return; } @@ -50,8 +52,10 @@ var useLine = ( or SyntaxKind.PlusToken ); -if (someRandomValue_______________________ is SomeRandomType someRandomType && - someRandomType.IsEnum) +if ( + someRandomValue_______________________ is SomeRandomType someRandomType + && someRandomType.IsEnum +) { return; } @@ -66,8 +70,10 @@ if (expr is { } noExtraSpaceBeforeOpenBrace) return; } -if (someValue_________________________ is SomeType_________________ someType && - someType.SomeProperty) { } +if ( + someValue_________________________ is SomeType_________________ someType + && someType.SomeProperty +) { } var value = someOtherValue is { Property: true }; @@ -104,8 +110,8 @@ var value = someOtherValue is SomeType___________________ or SomeOtherType___________________ - or SomeThirdType___________ && - someLongValue_________________; + or SomeThirdType___________ + && someLongValue_________________; var value = someOtherValue is @@ -137,109 +143,135 @@ if (someOtherValue is not (SomeType or SomeOtherType)) return; } -if (someOtherValue_________________ - is (SomeLongType_______________ or SomeOtherLongType_______________)) +if ( + someOtherValue_________________ + is (SomeLongType_______________ or SomeOtherLongType_______________) +) { return; } -if (someOtherValue_________________ - is not (SomeLongType_____________ or SomeOtherLongType_____________)) +if ( + someOtherValue_________________ + is not (SomeLongType_____________ or SomeOtherLongType_____________) +) { return; } -if (someOtherValue_____________ +if ( + someOtherValue_____________ is ( SomeLongType_____________________________________ or SomeLongType_____________________________________ - )) + ) +) { return; } -if (node is SomeType_______________________ +if ( + node is SomeType_______________________ { SomeProperty: SomeOtherType_____________________________ - }) + } +) { return; } -if (node is PrefixUnaryExpressionSyntax +if ( + node is PrefixUnaryExpressionSyntax { Operand: ParenthesizedExpressionSyntax { Expression: IsPatternExpressionSyntax or IsPatternExpressionSyntax }, - }) + } +) { return; } -if (node is PrefixUnaryExpressionSyntax +if ( + node is PrefixUnaryExpressionSyntax { Operand: { Expression: IsPatternExpressionSyntax or IsPatternExpressionSyntax______________________ }, - }) + } +) { return; } -if (!( +if ( + !( node is PrefixUnaryExpressionSyntax { Operand: ParenthesizedExpressionSyntax or IsPatternExpressionSyntax } - )) + ) +) { return; } -if (someLongName____________________________________________________ is - { } anotherLongName______________________) +if ( + someLongName____________________________________________________ is + { } anotherLongName______________________ +) { return; } -if (someLongVariableName____________ - is SomeLongTypeName______________________________ someOtherLongVariableName_____________) +if ( + someLongVariableName____________ + is SomeLongTypeName______________________________ someOtherLongVariableName_____________ +) { return; } -if (someArray[index] - is SomeLongTypeName______________________________ someOtherLongVariableName_____________) +if ( + someArray[index] + is SomeLongTypeName______________________________ someOtherLongVariableName_____________ +) { return; } -if (someLongName_____________________ +if ( + someLongName_____________________ is SomeObjectType or SomeOtherObjectType - or YetAnotherObjectType) + or YetAnotherObjectType +) { return; } -if (someCondition && - someLongName_____________ - is { Kind: SomeObjectType, Value: "___________________________________" }) { } +if ( + someCondition + && someLongName_____________ + is { Kind: SomeObjectType, Value: "___________________________________" } +) { } if (expr is { Property.Length: 5 }) { return; } -if (e is +if ( + e is #pragma warning disable CS0618 BadHttpRequestException #pragma warning restore CS0618 { Message: "______________________________________________________________________________________________________________" - }) { } + } +) { } var needsUpdatedRoslyn = y is y ? [] : z ?? []; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test index b3ad0932a..f0501989e 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/MemberChains.test @@ -257,8 +257,8 @@ CallMethod( ); var someValue = - someValue && - o.Property.CallMethod_____________________________________________________() + someValue + && o.Property.CallMethod_____________________________________________________() .CallMethod_____________________________________________________(); o.Property.CallMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test index cf2f7459f..7c0cce35b 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ObnoxiousEdgeCases.test @@ -112,9 +112,9 @@ class ClassName { get => _sourceType ??= - CustomMapExpression?.ReturnType ?? - CustomMapFunction?.ReturnType ?? - ( + CustomMapExpression?.ReturnType + ?? CustomMapFunction?.ReturnType + ?? ( _sourceMembers.Length > 0 ? _sourceMembers[_sourceMembers.Length - 1].GetMemberType() : Parameter.ParameterType @@ -138,14 +138,14 @@ class ClassName private bool VisitChildForCompare(Pair tuple, ref int result) { int r; - return 0 != - ( + return 0 + != ( result = (null == tuple.Item1) ? -1 : (null == tuple.Item2) ? +1 : 0 != (r = comparer.Compare(tuple.Item1.LocalName, tuple.Item2.LocalName)) ? r - : 0 != - (r = comparer.Compare(tuple.Item1.NamespaceURI, tuple.Item2.NamespaceURI)) + : 0 + != (r = comparer.Compare(tuple.Item1.NamespaceURI, tuple.Item2.NamespaceURI)) ? r : 0 ); diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test index fedba47a0..70ec26e76 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ParenthesizedExpressions.test @@ -3,14 +3,14 @@ class ClassName void MethodName() { var x = - query && - ( - currentChar == '=' || - currentChar == '<' || - currentChar == '!' || - currentChar == '>' || - currentChar == '|' || - currentChar == '&' + query + && ( + currentChar == '=' + || currentChar == '<' + || currentChar == '!' + || currentChar == '>' + || currentChar == '|' + || currentChar == '&' ); var b2 = ( System.Environment.SpecialFolder.AdminTools diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test index 13107aa48..7bcacba8a 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/QueryExpressions.test @@ -34,8 +34,8 @@ class ClassName var complexWhere = from c in customers where - c.Value == "true" && - someLongValueThatForcesABreak_________________________ != someOtherValue + c.Value == "true" + && someLongValueThatForcesABreak_________________________ != someOtherValue select d; var selectIntoQuery = from c in customers select c into d select d; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test index 24c99672e..2342b9aa6 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/ReturnStatements.test @@ -12,8 +12,8 @@ class ClassName bool ReturnLongBinaryExpression() { - return someValueThatIsLongAndForcesALineBreak || - otherValueThatIsLongAndForcesALineBreak_____________________; + return someValueThatIsLongAndForcesALineBreak + || otherValueThatIsLongAndForcesALineBreak_____________________; } string LongMethodCallWithParameter() diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test index 53d2fab9d..3809d744d 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SimpleLambdaExpressions.test @@ -109,8 +109,8 @@ public class ClassName ); this.Where(t => - t.SomeVeryLongColumn________________________________ || - t.OtherLongColumn________________________________ + t.SomeVeryLongColumn________________________________ + || t.OtherLongColumn________________________________ ); Select______________________________________(superLongName_________________________ => diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test index f807585e8..0d2da16af 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions.test @@ -49,9 +49,9 @@ class ClassName SomeObject_______________________________________________ ) => "LongString_____________________________________________________________________", - OneMore => "someStrings" + - "moreStrings" + - "andMoreStrings_________________________________________", + OneMore => "someStrings" + + "moreStrings" + + "andMoreStrings_________________________________________", SomeOtherObject or AnotherObject or OrEvenSomeOtherObject_________________ => CallSomeMethod(someValue), SomeOtherObject { SomeProperty: SomeOtherProject } or AnotherObject => CallSomeMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test index 3ae27baf4..6951bd3a3 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchExpressions_Tabs.test @@ -41,9 +41,9 @@ class ClassName ), VeryLongObject_______________________________________________________________ when count > 0 => CallSomeMethod(someValue), - OneMore => "someStrings" + - "moreStrings" + - "andMoreStrings_________________________________________", + OneMore => "someStrings" + + "moreStrings" + + "andMoreStrings_________________________________________", SomeOtherObject or AnotherObject or OrEvenSomeOtherObject_________________ => CallSomeMethod(someValue), SomeOtherObject { SomeProperty: SomeOtherProject } or AnotherObject => CallSomeMethod( diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test index 77dce0623..42ea00033 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/SwitchStatements.test @@ -89,8 +89,10 @@ public class ClassName } } - switch (someLongValue + - someOtherLongValue_________________________________________________________) + switch ( + someLongValue + + someOtherLongValue_________________________________________________________ + ) { default: return; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test index d87a8b3b8..e103d1cd1 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/TryStatements.test @@ -49,8 +49,8 @@ class ClassName throw new Exception(); } catch (Exception exception) - when (exception.Message.Contains("someLongValueThatMakesThisLineTooLong") && - someLongCondition == someOtherLongValue + when (exception.Message.Contains("someLongValueThatMakesThisLineTooLong") + && someLongCondition == someOtherLongValue ) { return; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test index 4cf7c918c..64b3564d0 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/UncheckedStatements.test @@ -13,8 +13,8 @@ class ClassName ); unchecked( - printsLikeInvocations + - whenItLongBreaks_______________________________________________ + printsLikeInvocations + + whenItLongBreaks_______________________________________________ ); } } diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test index d7043f4b0..a9396cf94 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/VariableDeclarations.test @@ -54,8 +54,8 @@ class ClassName SqlParameterCollectionExtensions.DefaultValueColumnWidth + DefaultValueColumnWidth ]; var muchLongerOne_________________ = new byte[ - SqlParameterCollectionExtensions.DefaultValueColumnWidth + - SqlParameterCollectionExtensions.DefaultValueColumnWidth + SqlParameterCollectionExtensions.DefaultValueColumnWidth + + SqlParameterCollectionExtensions.DefaultValueColumnWidth ]; var elementAccessExpression1 = anArray[100]; @@ -72,8 +72,8 @@ class ClassName DefaultValueColumnWidth_________ + DefaultValueColumnWidth_______ ]; var shortOne______ = anArray[ - SqlParameterCollectionExtensions.DefaultValueColumnWidth + - SqlParameterCollectionExtensions.DefaultValueColumnWidth + SqlParameterCollectionExtensions.DefaultValueColumnWidth + + SqlParameterCollectionExtensions.DefaultValueColumnWidth ]; var someLongValue_________________ = memberAccessExpression[ @@ -94,17 +94,17 @@ class ClassName (ArrayType[])CallMethod(); var conditionalIndentation = someBoolean - ? someLongValue____________________________________ + - someLongValue____________________________________ - : someLongValue____________________________________ + - someLongValue____________________________________; + ? someLongValue____________________________________ + + someLongValue____________________________________ + : someLongValue____________________________________ + + someLongValue____________________________________; var longEnoughToMakeThisBreak = something == somethingElse ? shortValue__________ : otherShortValue; var value = - someLongValue__________________________________ && - someOtherValue__________________________________ + someLongValue__________________________________ + && someOtherValue__________________________________ ? trueValue : falseValue; @@ -175,8 +175,8 @@ withLineEnding" : someOtherValue; var someValue = - someLongCondition___________________________________ && - someOtheLongCondition___________________________________ + someLongCondition___________________________________ + && someOtheLongCondition___________________________________ ? someValue : someValue; diff --git a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test index 221cc430d..6f979d467 100644 --- a/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test +++ b/Src/CSharpier.Tests/FormattingTests/TestFiles/cs/WhileStatements.test @@ -12,9 +12,11 @@ class ClassName return; } - while (directoryInfo.Name != "Test" && - directoryInfo.Parent != null && - someLongCondition == "test") + while ( + directoryInfo.Name != "Test" + && directoryInfo.Parent != null + && someLongCondition == "test" + ) { directoryInfo = directoryInfo.Parent; } @@ -30,8 +32,9 @@ class ClassName return; } - while (justOver100 || - moreTextToMakeItWork__________________________________________________) + while ( + justOver100 || moreTextToMakeItWork__________________________________________________ + ) { return; } @@ -42,8 +45,9 @@ class ClassName while (someLongerStatement && someOtherLongerStatement________________) return someLongerValue; - while (someEvenLongerStatement && - someOtherEvenLongerStatement________________________________) + while ( + someEvenLongerStatement && someOtherEvenLongerStatement________________________________ + ) return someLongerValue; while (true) From 01c00afe0226b330fb6080978c30dd831dc98d5e Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 09:57:38 +0800 Subject: [PATCH 3/9] chore: configure as CSharpier-Flex dotnet tool --- .github/workflows/publish.yml | 26 ++++ MODIFICATIONS.md | 4 +- Nuget/Build.props | 6 +- README.md | 158 ++++++++++++++++++------- Src/CSharpier.Cli/CSharpier.Cli.csproj | 4 +- 5 files changed, 147 insertions(+), 51 deletions(-) create mode 100644 .github/workflows/publish.yml diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 000000000..75b9e3de6 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,26 @@ +name: Publish NuGet Package + +on: + push: + tags: + - 'v*' + +jobs: + publish: + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + - name: Pack + run: dotnet pack Src/CSharpier.Cli/CSharpier.Cli.csproj -c Release -o ./nupkg + + - name: Push to GitHub Packages + run: dotnet nuget push ./nupkg/*.nupkg --api-key ${{ secrets.GITHUB_TOKEN }} --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" diff --git a/MODIFICATIONS.md b/MODIFICATIONS.md index a1fb5e62c..91b8de464 100644 --- a/MODIFICATIONS.md +++ b/MODIFICATIONS.md @@ -1,4 +1,4 @@ -# CSharpier-Flex 魔改记录 +# CSharpier-Flex 扩展记录 本文档记录对 CSharpier 原版所做的所有定制化修改。 @@ -6,7 +6,7 @@ ## 配置方式 -所有魔改行为统一由 `formattingStyle` 配置项控制: +所有扩展行为统一由 `formattingStyle` 配置项控制: ```json // .csharpierrc diff --git a/Nuget/Build.props b/Nuget/Build.props index bc58afe0b..01a3ed439 100644 --- a/Nuget/Build.props +++ b/Nuget/Build.props @@ -1,10 +1,10 @@ - 1.2.6 + 1.0.0 MIT - https://github.com/belav/csharpier + https://github.com/AnyAnq/csharpier-flex git - CSharpier is an opinionated code formatter for c#. + CSharpier-Flex: CSharpier fork with ReSharper-style formatting options. logo.png README.md false diff --git a/README.md b/README.md index d809cb1c5..8ac92e594 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,139 @@ -![CSharpier](./banner.svg) +# CSharpier-Flex -CSharpier is an opinionated code formatter for c# and XML. It parses your code and re-prints it using its own rules. -The printing process was ported from [prettier](https://github.com/prettier/prettier) but has evolved over time. +基于 [CSharpier](https://github.com/belav/csharpier) 的 Fork,在保留原版全部功能的基础上,新增 `formattingStyle` 配置项,提供更贴近 ReSharper / Rider 风格的 C# 代码格式化选项。 -CSharpier provides a few basic options that affect formatting and has no plans to add more. It follows the [Option Philosophy](https://prettier.io/docs/en/option-philosophy.html) of prettier. +> 原版 CSharpier 遵循 Prettier 的 [Option Philosophy](https://prettier.io/docs/en/option-philosophy.html),仅提供极少量格式化选项。本 Fork 在此基础上扩展,通过一个配置项切换整套风格预设,不破坏原版行为。 + +--- + +## Quick Start + +### 安装 -### Quick Start -Install CSharpier globally using the following command. ```bash -dotnet tool install csharpier -g +# 从源码构建(需要 .NET 10 SDK) +git clone https://github.com/AnyAnq/csharpier-flex.git +cd csharpier-flex +dotnet build Src/CSharpier.Cli/CSharpier.Cli.csproj ``` -Then format the contents of a directory and its children with the following command. + +### 使用 + ```bash -csharpier format . -``` +# 格式化当前目录 +dotnet run --project Src/CSharpier.Cli/CSharpier.Cli.csproj -- format . -CSharpier can also format [on save in your editor](https://csharpier.com/docs/Editors) or as a [pre-commit hook](https://csharpier.com/docs/Pre-commit). Then you can ensure code was formatted with a [CI/CD tool](https://csharpier.com/docs/ContinuousIntegration). +# 格式化单个文件并输出到标准输出 +dotnet run --project Src/CSharpier.Cli/CSharpier.Cli.csproj -- format --write-stdout "MyFile.cs" +``` --- -[Read the documentation](https://csharpier.com) - -[Try it out](https://playground.csharpier.com) +## 配置 ---- +在项目根目录创建 `.csharpierrc` 文件: -### Before -```c# -public class ClassName { - public void CallMethod() { - this.LongUglyMethod("1234567890", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - } +```json +{ + "formattingStyle": "resharper", + "printWidth": 120 } ``` -### After -```c# -public class ClassName -{ - public void CallMethod() +### `formattingStyle` + +| 值 | 说明 | +|---|---| +| `"default"` | 原版 CSharpier 行为(不写此项时的默认值) | +| `"resharper"` | 启用下列所有扩展格式化规则 | + +### 其他配置项 + +原版 CSharpier 的所有配置项均可正常使用: + +| 配置项 | 默认值 | 说明 | +|---|---|---| +| `printWidth` | `100` | 行宽限制 | +| `indentSize` | `4` | 缩进空格数 | +| `useTabs` | `false` | 是否使用 Tab 缩进 | +| `endOfLine` | `"auto"` | 换行符类型(`auto` / `lf` / `crlf`) | + +--- + +## 扩展格式化规则 + +以下规则仅在 `"formattingStyle": "resharper"` 时生效。 + +### 1. 字段属性同行 + +属性(Attribute)与字段声明保持在同一行,适用于 Unity 项目中常见的 `[SerializeField]` 风格。 + +```csharp +// 1-2 个属性 → 全部同行 +[SerializeField] private Button _buttonQuit; +[SerializeField] [HideInInspector] private Text _label; + +// 3 个属性 → 属性同行,字段换行 +[SerializeField] [HideInInspector] [Header("Title")] +private Text _labelTitle; + +// 4+ 个属性 → 保持原版行为(各自一行) +[SerializeField] +[HideInInspector] +[Header("Title")] +[Tooltip("tip")] +private Text _labelTitle; +``` + +### 2. 二元表达式操作符留在行尾 + +换行时操作符(`||`、`&&`、`??` 等)保留在当前行末尾,而非移到下一行开头。同时 `if` / `while` / `do-while` / `switch` 的条件紧贴括号。 + +```csharp +// default 风格 +if ( + condition1 + || condition2 +) + +// resharper 风格 +if (condition1 || + condition2) +``` + +### 3. 方法调用尾部 Lambda 参数内联 + +当方法调用的最后一个参数是带代码块的 lambda 时,非 lambda 参数保持在方法名同一行,lambda 体自然换行。 + +```csharp +// default 风格 +BindButton( + _buttonChallenge, + () => { - this.LongUglyMethod( - "1234567890", - "abcdefghijklmnopqrstuvwxyz", - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - ); + DoSomething(); } -} +); + +// resharper 风格 +BindButton(_buttonChallenge, () => +{ + DoSomething(); +}); ``` -## Contributing -See [Development Readme](CONTRIBUTING.md) +--- -Join Us [![Discord](https://img.shields.io/badge/Discord-chat?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/HfAKGEZQcX) +## 与原版 CSharpier 的关系 -## Sponsors +- **完全兼容**:不设置 `formattingStyle` 或设为 `"default"` 时,行为与原版 CSharpier 完全一致 +- **非破坏性**:所有扩展规则仅在显式配置 `"resharper"` 时生效 +- **持续同步**:定期从上游 [belav/csharpier](https://github.com/belav/csharpier) 合并更新 -Thanks to the following companies for sponsoring the ongoing development of CSharpier. +详细修改记录见 [MODIFICATIONS.md](MODIFICATIONS.md)。 -[.NET on AWS Open Source Software Fund](https://github.com/aws/dotnet-foss) \ - \ -[](https://github.com/aws/dotnet-foss) +--- -[Fern](https://buildwithfern.com/) \ - \ -[]((https://buildwithfern.com/)) +## 致谢 -And a huge thanks to all the others who sponsor the project through [Github sponsors](https://github.com/sponsors/belav) \ No newline at end of file +本项目基于 [CSharpier](https://github.com/belav/csharpier),感谢原作者及所有贡献者的工作。 diff --git a/Src/CSharpier.Cli/CSharpier.Cli.csproj b/Src/CSharpier.Cli/CSharpier.Cli.csproj index a2f9b21a9..6d6f3fa6a 100644 --- a/Src/CSharpier.Cli/CSharpier.Cli.csproj +++ b/Src/CSharpier.Cli/CSharpier.Cli.csproj @@ -3,11 +3,11 @@ $(NoWarn);NU1510 Exe - CSharpier + CSharpier-Flex CSharpier net8.0;net9.0;net10.0 true - csharpier + csharpier-flex ../../Nuget/csharpier.snk Major True From 5d10ef37dce71698253f6549d19d47e577f4d2b2 Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 10:25:49 +0800 Subject: [PATCH 4/9] chore: add nuget.org trusted publishing --- .github/workflows/publish.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 75b9e3de6..293c689a4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,6 +11,7 @@ jobs: permissions: packages: write contents: read + id-token: write steps: - uses: actions/checkout@v4 @@ -24,3 +25,6 @@ jobs: - name: Push to GitHub Packages run: dotnet nuget push ./nupkg/*.nupkg --api-key ${{ secrets.GITHUB_TOKEN }} --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" + + - name: Push to nuget.org + run: dotnet nuget push ./nupkg/*.nupkg --source "https://api.nuget.org/v3/index.json" From d01656c433551a17151188dc9845fda5fb7391be Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 10:30:05 +0800 Subject: [PATCH 5/9] fix: upgrade Scriban to 7.2.1 to resolve vulnerability --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 36b668f8a..60877b96c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -22,7 +22,7 @@ - + From 89b7beb8301b64ccb30dd58ff9fdfc4306fefdda Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 10:34:47 +0800 Subject: [PATCH 6/9] fix: revert Scriban, suppress NU1903, remove legacy workflows --- .github/workflows/publish_beta.yml | 23 ----------- .github/workflows/publish_nuget.yml | 40 ------------------- Directory.Packages.props | 2 +- .../CSharpier.Generators.csproj | 2 +- 4 files changed, 2 insertions(+), 65 deletions(-) delete mode 100644 .github/workflows/publish_beta.yml delete mode 100644 .github/workflows/publish_nuget.yml diff --git a/.github/workflows/publish_beta.yml b/.github/workflows/publish_beta.yml deleted file mode 100644 index c92e2c8da..000000000 --- a/.github/workflows/publish_beta.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: Publish -on: - push: - branches: [ 1.0.0 ] -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - uses: actions/setup-dotnet@v3 - - uses: gittools/actions/gitversion/setup@v3.1.1 - with: - versionSpec: '6.0.x' - - uses: gittools/actions/gitversion/execute@v3.1.1 - - run: | - dotnet pack Src/CSharpier.Cli/CSharpier.Cli.csproj -c Release /p:Version=${{env.VERSION}} /p:InformationalVersion=${{env.VERSION}} -o dist - dotnet nuget push ./dist/CSharpier.${{env.VERSION}}.nupkg -k ${{secrets.NUGET_API_KEY}} -s https://api.nuget.org/v3/index.json - git tag ${{env.VERSION}} - git push origin ${{env.VERSION}} - env: - VERSION: ${{env.branchName}}-alpha${{env.commitsSinceVersionSource}} diff --git a/.github/workflows/publish_nuget.yml b/.github/workflows/publish_nuget.yml deleted file mode 100644 index 998f83e70..000000000 --- a/.github/workflows/publish_nuget.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Publish Nuget -on: - push: - branches: [ main ] -jobs: - test: - runs-on: ubuntu-latest - name: test - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-dotnet@v3 - - run: > - dotnet build CSharpier.slnx -c release -p:TreatWarningsAsErrors=true - - publish-nuget: - runs-on: ubuntu-latest - name: publish nuget - needs: test - env: - VERSION_FILE_PATH: Nuget/Build.props - NUGET_KEY: ${{secrets.NUGET_API_KEY}} - steps: - - uses: actions/checkout@v2 - - uses: actions/setup-dotnet@v3 - - name: Publish CSharpier.Core library on version change - uses: alirezanet/publish-nuget@v3.1.0 - with: - PROJECT_FILE_PATH: Src/CSharpier.Core/CSharpier.Core.csproj - TAG_FORMAT: "*" - - name: Publish CSharpier dotnet tool on version change - uses: alirezanet/publish-nuget@v3.1.0 - with: - PACKAGE_NAME: CSharpier - PROJECT_FILE_PATH: Src/CSharpier.Cli/CSharpier.Cli.csproj - TAG_FORMAT: "*" - - name: Publish CSharpier.MsBuild library on version change - uses: alirezanet/publish-nuget@v3.1.0 - with: - PROJECT_FILE_PATH: Src/CSharpier.MsBuild/CSharpier.MsBuild.csproj - TAG_FORMAT: "*" diff --git a/Directory.Packages.props b/Directory.Packages.props index 60877b96c..36b668f8a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -22,7 +22,7 @@ - + diff --git a/Src/CSharpier.Generators/CSharpier.Generators.csproj b/Src/CSharpier.Generators/CSharpier.Generators.csproj index ea01ed6af..713f09e87 100644 --- a/Src/CSharpier.Generators/CSharpier.Generators.csproj +++ b/Src/CSharpier.Generators/CSharpier.Generators.csproj @@ -5,7 +5,7 @@ true true 13 - SYSLIB0013 + SYSLIB0013;NU1903 From 62c58fd3c8d5d23e8c34c461f0ba42e3736f69bd Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 10:42:22 +0800 Subject: [PATCH 7/9] fix: workflow --- .github/workflows/publish.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 293c689a4..210265ec7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -24,7 +24,7 @@ jobs: run: dotnet pack Src/CSharpier.Cli/CSharpier.Cli.csproj -c Release -o ./nupkg - name: Push to GitHub Packages - run: dotnet nuget push ./nupkg/*.nupkg --api-key ${{ secrets.GITHUB_TOKEN }} --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" + run: dotnet nuget push ./nupkg/*.nupkg --skip-duplicate --api-key ${{ secrets.GITHUB_TOKEN }} --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" - name: Push to nuget.org - run: dotnet nuget push ./nupkg/*.nupkg --source "https://api.nuget.org/v3/index.json" + run: dotnet nuget push ./nupkg/*.nupkg --skip-duplicate --source "https://api.nuget.org/v3/index.json" From 8299872b26334ec243e066a369ad07e5e09d282f Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 10:47:55 +0800 Subject: [PATCH 8/9] fix: workflow --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 210265ec7..d857dff53 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -27,4 +27,4 @@ jobs: run: dotnet nuget push ./nupkg/*.nupkg --skip-duplicate --api-key ${{ secrets.GITHUB_TOKEN }} --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" - name: Push to nuget.org - run: dotnet nuget push ./nupkg/*.nupkg --skip-duplicate --source "https://api.nuget.org/v3/index.json" + run: dotnet nuget push ./nupkg/*.nupkg --skip-duplicate --api-key ${{ secrets.NUGET_API_KEY }} --source "https://api.nuget.org/v3/index.json" From 72721efb1e1a57bf6e722f18626a7359a1c98416 Mon Sep 17 00:00:00 2001 From: anqiang Date: Mon, 25 May 2026 11:03:45 +0800 Subject: [PATCH 9/9] =?UTF-8?q?doc:=20=E6=9B=B4=E6=96=B0=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8ac92e594..ccf7f283f 100644 --- a/README.md +++ b/README.md @@ -6,25 +6,67 @@ --- -## Quick Start +## 环境要求 -### 安装 +| 依赖 | 版本 | +|---|---| +| .NET SDK | 8.0 / 9.0 / 10.0(任一即可) | +| 操作系统 | Windows / macOS / Linux | + +--- + +## 安装 + +### 方式一:从 NuGet 安装(推荐) + +```bash +dotnet tool install CSharpier-Flex -g +``` + +安装后即可在任意目录使用 `csharpier-flex` 命令。 + +### 方式二:从源码构建 ```bash -# 从源码构建(需要 .NET 10 SDK) git clone https://github.com/AnyAnq/csharpier-flex.git cd csharpier-flex dotnet build Src/CSharpier.Cli/CSharpier.Cli.csproj ``` -### 使用 +--- + +## 使用 + +```bash +# 格式化当前目录下所有 .cs 文件 +csharpier-flex format . + +# 格式化单个文件 +csharpier-flex format MyFile.cs + +# 格式化并输出到标准输出(不修改文件) +csharpier-flex format --write-stdout MyFile.cs + +# 检查格式化是否一致(CI 用) +csharpier-flex check . +``` + +如果通过源码构建,使用 `dotnet run` 替代: ```bash -# 格式化当前目录 dotnet run --project Src/CSharpier.Cli/CSharpier.Cli.csproj -- format . +``` + +--- + +## 更新 & 卸载 + +```bash +# 更新到最新版 +dotnet tool update CSharpier-Flex -g -# 格式化单个文件并输出到标准输出 -dotnet run --project Src/CSharpier.Cli/CSharpier.Cli.csproj -- format --write-stdout "MyFile.cs" +# 卸载 +dotnet tool uninstall CSharpier-Flex -g ``` ---