From 8b50c182303a981058e7db2ac1c96b84d93355c2 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Tue, 5 Sep 2023 13:46:23 +0530 Subject: [PATCH 01/22] Read the formatting configurations in toml file --- .../main/resources/ballerina-toml-schema.json | 45 +++++ .../formatter/cli/FormatUtil.java | 33 +++- .../formatter/core/FormattingOptions.java | 158 ++++++++++++++++++ 3 files changed, 227 insertions(+), 9 deletions(-) diff --git a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json index e7bb00432374..bc4ff00f6810 100644 --- a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json +++ b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json @@ -351,6 +351,51 @@ "type": "boolean" } } + }, + "format": { + "type": "object", + "additionalProperties": true, + "properties": { + "columnLimit": { + "type": "integer" + }, + "tabWidth": { + "type": "integer" + }, + "allowShortBlocksOnASingleLine": { + "type": "boolean" + }, + "allowShortMatchLabelsOnASingleLine": { + "type": "boolean" + }, + "allowShortIfStatementsOnASingleLine": { + "type": "boolean" + }, + "allowShortLoopsOnASingleLine": { + "type": "boolean" + }, + "alignConsecutiveDefinitions": { + "type": "boolean" + }, + "elseBlocksOnANewLine": { + "type": "boolean" + }, + "recordBraceSpacing": { + "type": "boolean" + }, + "function": { + "type": "object", + "additionalProperties": true, + "properties": { + "oneArgPerLine": { + "type": "boolean" + }, + "paranAlign": { + "type": "boolean" + } + } + } + } } } } diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index 8d6b06d181d6..88d4fe12eb0b 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -27,6 +27,8 @@ import io.ballerina.projects.directory.SingleFileProject; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormattingOptions; + import java.io.File; import java.io.FileOutputStream; @@ -41,6 +43,7 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import java.util.Map; /** * Util class for compilation and format execution for formatting CLI tool. @@ -122,9 +125,11 @@ static void execute(List argList, boolean helpFlag, String moduleName, S Path projectPath = sourceRootPath.resolve(argList.get(0)); BuildProject project; + FormattingOptions options; try { project = BuildProject.load(projectPath, constructBuildOptions()); + options = constructFormattingOptions(project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -141,7 +146,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S project.currentPackage().module(FormatUtil.isModuleExist(project, moduleName)); try { formattedFiles.addAll(iterateAndFormat(getDocumentPaths(project, - moduleToBeFormatted.moduleId()), sourceRootPath, dryRun)); + moduleToBeFormatted.moduleId()), sourceRootPath, options, dryRun)); } catch (IOException | FormatterException e) { throw LauncherUtils.createLauncherException(Messages.getException() + e); } @@ -178,7 +183,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S project.currentPackage().moduleIds().forEach(moduleId -> { try { formattedFiles.addAll(iterateAndFormat(getDocumentPaths(project, moduleId), - sourceRootPath, dryRun)); + sourceRootPath, options, dryRun)); } catch (IOException | FormatterException e) { throw LauncherUtils.createLauncherException(Messages.getException() + e); } @@ -188,9 +193,10 @@ static void execute(List argList, boolean helpFlag, String moduleName, S } } else { BuildProject project; - + FormattingOptions options; try { project = BuildProject.load(sourceRootPath, constructBuildOptions()); + options = constructFormattingOptions(project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -207,7 +213,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S project.currentPackage().module(FormatUtil.isModuleExist(project, moduleName)); try { formattedFiles.addAll(iterateAndFormat(getDocumentPaths(project, - moduleToBeFormatted.moduleId()), sourceRootPath, dryRun)); + moduleToBeFormatted.moduleId()), sourceRootPath, options, dryRun)); } catch (IOException | FormatterException e) { throw LauncherUtils.createLauncherException(Messages.getException() + e); } @@ -244,7 +250,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S project.currentPackage().moduleIds().forEach(moduleId -> { try { formattedFiles.addAll(iterateAndFormat(getDocumentPaths(project, moduleId), - sourceRootPath, dryRun)); + sourceRootPath, options, dryRun)); } catch (IOException | FormatterException e) { throw LauncherUtils.createLauncherException(Messages.getException() + e); } @@ -293,12 +299,13 @@ private static void generateChangeReport(List formattedFiles, boolean dr } private static void formatAndWrite(Path documentPath, Path sourceRootPath, - List formattedFiles, boolean dryRun) throws IOException, FormatterException { + List formattedFiles, FormattingOptions options, boolean dryRun) + throws IOException, FormatterException { String fileName = Paths.get(sourceRootPath.toString()).resolve("modules").resolve(documentPath).toString(); String originalSource = Files.readString(Paths.get(fileName)); // Format and get the formatted source. - String formattedSource = Formatter.format(originalSource); + String formattedSource = Formatter.format(originalSource, options); if (areChangesAvailable(originalSource, formattedSource)) { if (!dryRun) { @@ -309,13 +316,14 @@ private static void formatAndWrite(Path documentPath, Path sourceRootPath, } } - private static List iterateAndFormat(List documentPaths, Path sourceRootPath, boolean dryRun) + private static List iterateAndFormat(List documentPaths, Path sourceRootPath, + FormattingOptions options, boolean dryRun) throws IOException, FormatterException { List formattedFiles = new ArrayList<>(); // Iterate compilation units and format. for (Path path : documentPaths) { - formatAndWrite(path, sourceRootPath, formattedFiles, dryRun); + formatAndWrite(path, sourceRootPath, formattedFiles, options, dryRun); } return formattedFiles; @@ -332,6 +340,13 @@ private static BuildOptions constructBuildOptions() { .build(); } + private static FormattingOptions constructFormattingOptions(Object configurations) { + if (configurations instanceof Map) { + return FormattingOptions.builder().build((Map) configurations); + } + return FormattingOptions.builder().build(); + } + /** * Check whether the given module name exists. * diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java index 938ebeb76881..1168a0b45135 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core; +import java.util.Map; + /** * A model for formatting options that could be passed onto the formatter. */ @@ -32,6 +34,26 @@ public class FormattingOptions { private int continuationIndent; + private boolean paranAlignedIndentation; + + private boolean oneArgPerLine; + + private boolean recordBraceSpacing; + + private boolean allowShortBlocksOnASingleLine; + + private boolean allowShortMatchLabelsOnASingleLine; + + private boolean allowShortIfStatementsOnASingleLine; + + private boolean allowShortLoopsOnASingleLine; + + private boolean elseBlockOnANewLine; + + private boolean sortImports; + + private boolean alignConsecutiveDefinitions; + private ForceFormattingOptions forceFormattingOptions; private ImportFormattingOptions importFormattingOptions; @@ -48,6 +70,29 @@ private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, bool this.importFormattingOptions = importFormattingOptions; } + FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, + ForceFormattingOptions forceFormattingOptions, boolean paranAlignedIndentation, + boolean oneArgPerLine, boolean allowShortBlocksOnASingleLine, boolean recordBraceSpacing, + boolean elseBlockOnANewLine, boolean sortImports, boolean alignConsecutiveDefinitions, + boolean allowShortIfStatementsOnASingleLine, boolean allowShortLoopsOnASingleLine, + boolean allowShortMatchLabelsOnASingleLine) { + this.tabSize = tabSize; + this.wsCharacter = wsCharacter; + this.columnLimit = columnLimit; + this.lineWrapping = lineWrapping; + this.forceFormattingOptions = forceFormattingOptions; + this.paranAlignedIndentation = paranAlignedIndentation; + this.oneArgPerLine = oneArgPerLine; + this.recordBraceSpacing = recordBraceSpacing; + this.elseBlockOnANewLine = elseBlockOnANewLine; + this.sortImports = sortImports; + this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; + this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; + this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; + this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; + this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; + } + /** * @deprecated * This constructor is no longer acceptable to instantiate Formatting Options. @@ -155,6 +200,46 @@ public ImportFormattingOptions getImportFormattingOptions() { return importFormattingOptions; } + public boolean isElseBlockOnANewLine() { + return elseBlockOnANewLine; + } + + public boolean isParanAlignedIndentation() { + return paranAlignedIndentation; + } + + public boolean isOneArgPerLine() { + return oneArgPerLine; + } + + public boolean allowShortBlocksOnASingleLine() { + return allowShortBlocksOnASingleLine; + } + + public boolean allowShortMatchLabelsOnASingleLine() { + return allowShortMatchLabelsOnASingleLine; + } + + public boolean allowShortIfStatementsOnASingleLine() { + return allowShortIfStatementsOnASingleLine; + } + + public boolean allowShortLoopsOnASingleLine() { + return allowShortLoopsOnASingleLine; + } + + public boolean isRecordBraceSpacing() { + return recordBraceSpacing; + } + + public boolean sortImports() { + return sortImports; + } + + public boolean alignConsecutiveDefinitions() { + return alignConsecutiveDefinitions; + } + public static FormattingOptionsBuilder builder() { return new FormattingOptionsBuilder(); } @@ -170,6 +255,16 @@ public static class FormattingOptionsBuilder { private int columnLimit = 120; private boolean lineWrapping = false; private int continuationIndent = 2; + private boolean paranAlignedIndentation = false; + private boolean oneArgPerLine = false; + private boolean recordBraceSpacing = false; + private boolean elseBlockOnANewLine = false; + private Boolean sortImports = false; + private Boolean alignConsecutiveDefinitions = false; + private boolean allowShortBlocksOnASingleLine = false; + private Boolean allowShortMatchLabelsOnASingleLine = false; + private Boolean allowShortLoopsOnASingleLine = false; + private Boolean allowShortIfStatementsOnASingleLine = false; private ForceFormattingOptions forceFormattingOptions = ForceFormattingOptions.builder().build(); private ImportFormattingOptions importFormattingOptions = ImportFormattingOptions.builder().build(); @@ -209,5 +304,68 @@ public FormattingOptions build() { return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, forceFormattingOptions, importFormattingOptions); } + + public FormattingOptions build(Map configurations) { + for (Map.Entry entry : configurations.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + switch (key) { + case "columnLimit": + this.columnLimit = ((Number) value).intValue(); + this.lineWrapping = true; + break; + case "tabWidth": + this.tabSize = ((Number) value).intValue(); + break; + case "sortImports": + this.sortImports = ((Boolean) value); + break; + case "alignConsecutiveDefinitions": + this.alignConsecutiveDefinitions = ((Boolean) value); + break; + case "allowShortMatchLabelsOnASingleLine": + this.allowShortMatchLabelsOnASingleLine = ((Boolean) value); + break; + case "allowShortIfStatementsOnASingleLine": + this.allowShortIfStatementsOnASingleLine = ((Boolean) value); + break; + case "allowShortLoopsOnASingleLine": + this.allowShortLoopsOnASingleLine = ((Boolean) value); + break; + case "allowShortBlocksOnASingleLine": + this.allowShortBlocksOnASingleLine = ((Boolean) value); + break; + case "recordBraceSpacing": + this.recordBraceSpacing = ((Boolean) value); + break; + case "elseBlockOnANewLine": + this.elseBlockOnANewLine = ((Boolean) value); + break; + case "function": + Map funcConfigurations = (Map) value; + for (Map.Entry funcEntry : funcConfigurations.entrySet()) { + String funcKey = funcEntry.getKey(); + Object funcValue = funcEntry.getValue(); + switch (funcKey) { + case "paranAlign": + this.paranAlignedIndentation = ((Boolean) funcValue); + break; + case "oneArgPerLine": + this.oneArgPerLine = ((Boolean) funcValue); + break; + default: + break; + } + } + break; + default: + break; + } + } + return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, forceFormattingOptions, + paranAlignedIndentation, oneArgPerLine, allowShortBlocksOnASingleLine, recordBraceSpacing, + elseBlockOnANewLine, sortImports, alignConsecutiveDefinitions, allowShortIfStatementsOnASingleLine, + allowShortLoopsOnASingleLine, allowShortMatchLabelsOnASingleLine); + } } } From 342d660e450ae826544ad1f90e6e0c9bb81a2485 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Tue, 5 Sep 2023 13:49:33 +0530 Subject: [PATCH 02/22] Modify formatter to match configurations --- .../formatter/core/FormatterUtils.java | 24 ++++++ .../formatter/core/FormattingEnv.java | 10 +++ .../core/FormattingTreeModifier.java | 86 ++++++++++++++----- 3 files changed, 99 insertions(+), 21 deletions(-) diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index b9cdef30e98f..3ea2dfe95dbb 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core; +import io.ballerina.compiler.syntax.tree.BlockStatementNode; +import io.ballerina.compiler.syntax.tree.ConstantDeclarationNode; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; import io.ballerina.compiler.syntax.tree.ImportOrgNameNode; import io.ballerina.compiler.syntax.tree.Minutiae; @@ -162,4 +164,26 @@ private static boolean hasEmptyLineAtEnd(MinutiaeList minutiaeList) { return minutiaeList.get(size - 1).kind() == SyntaxKind.END_OF_LINE_MINUTIAE && minutiaeList.get(size - 2).kind() == SyntaxKind.END_OF_LINE_MINUTIAE; } + + static boolean isBlockOnASingleLine(FormattingOptions options, BlockStatementNode node) { + if (node.lineRange().startLine().line() != node.lineRange().endLine().line()) { + return false; + } + + if (options.allowShortBlocksOnASingleLine()) { + return true; + } + + SyntaxKind parentKind = node.parent().kind(); + return (options.allowShortIfStatementsOnASingleLine() && parentKind == SyntaxKind.IF_ELSE_STATEMENT) || + (options.allowShortLoopsOnASingleLine() && parentKind == SyntaxKind.WHILE_STATEMENT) || + (options.allowShortMatchLabelsOnASingleLine() && parentKind == SyntaxKind.MATCH_CLAUSE); + } + + static int getConstDefLength(ConstantDeclarationNode node) { + int size = node.visibilityQualifier().isPresent() ? node.visibilityQualifier().get().text().length() : 0; + size += node.constKeyword().text().length(); + size += node.variableName().text().length(); + return size; + } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingEnv.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingEnv.java index 5f5a528e535c..8a77a7ef96bb 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingEnv.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingEnv.java @@ -31,6 +31,11 @@ public class FormattingEnv { */ int currentIndentation = 0; + /** + * Number of whitespaces to be used as the indentation for the current context used when aligning statements. + */ + int preservedIndentation = 0; + /** * Number of leading newlines to be added to the currently processing node. */ @@ -76,6 +81,11 @@ public class FormattingEnv { */ int prevTokensTrailingNL = 0; + /** + * Maximum length of the consecutive constant definitions. + */ + int maxConstDefWidth = 1; + /** * Flag indicating whether the token that is currently being formatted should preserve its user defined indentation. */ diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 17fe66a9dfd8..bc596811ed56 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -259,6 +259,8 @@ import java.util.stream.Collectors; import static org.ballerinalang.formatter.core.FormatterUtils.isInlineRange; +import static org.ballerinalang.formatter.core.FormatterUtils.isBlockOnASingleLine; +import static org.ballerinalang.formatter.core.FormatterUtils.getConstDefLength; import static org.ballerinalang.formatter.core.FormatterUtils.sortImportDeclarations; import static org.ballerinalang.formatter.core.FormatterUtils.swapLeadingMinutiae; @@ -371,10 +373,16 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); // Start a new indentation of two tabs for the parameters. - indent(options.getContinuationIndent()); + if (options.isParanAlignedIndentation()) { + align(); + } else { + indent(options.getContinuationIndent()); + } + boolean oneArgPerLine = options.isOneArgPerLine(); SeparatedNodeList parameters = - formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, 0, 0, 0, 0, true); - unindent(options.getContinuationIndent()); + formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, + oneArgPerLine ? 1 : 0, + 0, 0); Token closePara; ReturnTypeDescriptorNode returnTypeDesc = null; @@ -386,6 +394,12 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo closePara = formatToken(functionSignatureNode.closeParenToken(), env.trailingWS, env.trailingNL); } + if (options.isParanAlignedIndentation()) { + unalign(); + } else { + unindent(options.getContinuationIndent()); + } + return functionSignatureNode.modify() .withOpenParenToken(openPara) .withParameters(parameters) @@ -423,7 +437,7 @@ public IncludedRecordParameterNode transform(IncludedRecordParameterNode include if (includedRecordParameterNode.paramName().isPresent()) { typeName = formatNode(includedRecordParameterNode.typeName(), 1, 0); Token paramName = formatToken(includedRecordParameterNode.paramName().orElse(null), - env.trailingWS, env.trailingNL); + env.trailingWS, env.trailingNL); return includedRecordParameterNode.modify() .withAsteriskToken(asterisk) .withAnnotations(annotations) @@ -526,7 +540,9 @@ public IfElseStatementNode transform(IfElseStatementNode ifElseStatementNode) { BlockStatementNode ifBody; Node elseBody = null; if (ifElseStatementNode.elseBody().isPresent()) { - ifBody = formatNode(ifElseStatementNode.ifBody(), 1, 0); + boolean needNL = options.isElseBlockOnANewLine(); + ifBody = formatNode(ifElseStatementNode.ifBody(), needNL ? 0 : 1, + needNL ? 1 : 0); preserveIndentation(!hasTrailingNL(ifElseStatementNode.ifBody().closeBraceToken())); elseBody = formatNode(ifElseStatementNode.elseBody().orElse(null), env.trailingWS, env.trailingNL); preserveIndentation(prevPreservedNewLine); @@ -556,12 +572,19 @@ public ElseBlockNode transform(ElseBlockNode elseBlockNode) { public BlockStatementNode transform(BlockStatementNode blockStatementNode) { boolean preserveIndent = env.preserveIndentation; preserveIndentation(blockStatementNode.openBraceToken().isMissing() && preserveIndent); - Token openBrace = formatToken(blockStatementNode.openBraceToken(), 0, 1); + int trailingNL = isBlockOnASingleLine(options, blockStatementNode) ? 0 : 1; + int trailingWS = 1 - trailingNL; + Token openBrace = formatToken(blockStatementNode.openBraceToken(), trailingWS, trailingNL); preserveIndentation(preserveIndent); indent(); // start an indentation - NodeList statements = formatNodeList(blockStatementNode.statements(), 0, 1, 0, 1); + NodeList statements = + formatNodeList(blockStatementNode.statements(), 0, 1, trailingWS, trailingNL); unindent(); // end the indentation - Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, env.trailingNL); + int closingNewLine = + (options.isElseBlockOnANewLine() && + blockStatementNode.parent().kind() == SyntaxKind.IF_ELSE_STATEMENT) ? 1 : + env.trailingNL; + Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, closingNewLine); return blockStatementNode.modify() .withOpenBraceToken(openBrace) @@ -1079,7 +1102,7 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC env.currentIndentation = prevIndentation; Token functionCallClosePara = formatToken(functionCallExpressionNode.closeParenToken(), env.trailingWS, env.trailingNL); - + unindent(2); return functionCallExpressionNode.modify() .withFunctionName(functionName) .withOpenParenToken(functionCallOpenPara) @@ -1140,7 +1163,9 @@ public ConstantDeclarationNode transform(ConstantDeclarationNode constantDeclara Token visibilityQualifier = formatToken(constantDeclarationNode.visibilityQualifier().orElse(null), 1, 0); Token constKeyword = formatToken(constantDeclarationNode.constKeyword(), 1, 0); TypeDescriptorNode typeDescriptorNode = formatNode(constantDeclarationNode.typeDescriptor().orElse(null), 1, 0); - Token variableName = formatToken(constantDeclarationNode.variableName(), 1, 0); + int wSBeforeEqual = !options.alignConsecutiveDefinitions() ? 1 : + env.maxConstDefWidth - getConstDefLength(constantDeclarationNode) + 1; + Token variableName = formatToken(constantDeclarationNode.variableName(), wSBeforeEqual, 0); Token equalsToken = formatToken(constantDeclarationNode.equalsToken(), 1, 0); Node initializer = formatNode(constantDeclarationNode.initializer(), 0, 0); Token semicolonToken = formatToken(constantDeclarationNode.semicolonToken(), env.trailingWS, env.trailingNL); @@ -1190,7 +1215,7 @@ public FunctionTypeDescriptorNode transform(FunctionTypeDescriptorNode functionT functionKeyword = formatToken(functionTypeDescriptorNode.functionKeyword(), env.trailingWS, env.trailingNL); } FunctionSignatureNode functionSignature = formatNode(functionTypeDescriptorNode.functionSignature(). - orElse(null), env.trailingWS, env.trailingNL); + orElse(null), env.trailingWS, env.trailingNL); return functionTypeDescriptorNode.modify() .withQualifierList(qualifierList) .withFunctionKeyword(functionKeyword) @@ -1254,11 +1279,12 @@ public MappingConstructorExpressionNode transform( } else { fieldTrailingWS++; } - - Token openBrace = formatToken(mappingConstructorExpressionNode.openBrace(), 0, fieldTrailingNL); + int innerWS = options.isRecordBraceSpacing() ? 1 : 0; + Token openBrace = formatToken(mappingConstructorExpressionNode.openBrace(), innerWS, fieldTrailingNL); indent(); SeparatedNodeList fields = formatSeparatedNodeList( - mappingConstructorExpressionNode.fields(), 0, 0, fieldTrailingWS, fieldTrailingNL, 0, fieldTrailingNL); + mappingConstructorExpressionNode.fields(), 0, 0, fieldTrailingWS, fieldTrailingNL, innerWS, + fieldTrailingNL); unindent(); Token closeBrace = formatToken(mappingConstructorExpressionNode.closeBrace(), env.trailingWS, env.trailingNL); @@ -2840,9 +2866,9 @@ public CollectClauseNode transform(CollectClauseNode collectClauseNode) { @Override public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { - int lineLength = env.lineLength; - if (lineLength != 0) { - indent(); + int indentation = env.currentIndentation; + if (indentation != 0) { + align(); } QueryConstructTypeNode queryConstructType = @@ -2858,8 +2884,8 @@ public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { OnConflictClauseNode onConflictClause = formatNode(queryExpressionNode.onConflictClause().orElse(null), env.trailingWS, env.trailingNL); - if (lineLength != 0) { - unindent(); + if (indentation != 0) { + unalign(); } return queryExpressionNode.modify() @@ -3575,14 +3601,14 @@ public NamedWorkerDeclarator transform(NamedWorkerDeclarator namedWorkerDeclarat @Override public ArrayTypeDescriptorNode transform(ArrayTypeDescriptorNode arrayTypeDescriptorNode) { TypeDescriptorNode memberTypeDesc = formatNode(arrayTypeDescriptorNode.memberTypeDesc(), 0, 0); - NodeList dimensions = formatNodeList(arrayTypeDescriptorNode.dimensions(), 0, + NodeList dimensions = formatNodeList(arrayTypeDescriptorNode.dimensions(), 0, 0, env.trailingWS, env.trailingNL); return arrayTypeDescriptorNode.modify() .withMemberTypeDesc(memberTypeDesc) .withDimensions(dimensions) .apply(); } - + @Override public ArrayDimensionNode transform(ArrayDimensionNode arrayDimensionNode) { Token openBracket = formatToken(arrayDimensionNode.openBracket(), 0, 0); @@ -3897,6 +3923,15 @@ protected NodeList formatMemberDeclarations(NodeList memb boolean nodeModified = false; int size = members.size(); + + if (options.alignConsecutiveDefinitions()) { + env.maxConstDefWidth = members.stream() + .filter(member -> member.kind() == SyntaxKind.CONST_DECLARATION) + .mapToInt(member -> getConstDefLength((ConstantDeclarationNode) member)) + .max() + .orElse(1); + } + Node[] newNodes = new Node[size]; for (int index = 0; index < size; index++) { T currentMember = members.get(index); @@ -4512,6 +4547,11 @@ private void indent(int step) { env.currentIndentation += (options.getTabSize() * step); } + private void align() { + env.preservedIndentation = env.currentIndentation; + env.currentIndentation = env.lineLength; + } + /** * Undo the indentation of the code by the number of white-spaces defined by tab-size. */ @@ -4533,6 +4573,10 @@ private void unindent(int step) { env.currentIndentation -= (options.getTabSize() * step); } + private void unalign() { + env.currentIndentation = env.preservedIndentation; + } + /** * Set the indentation for the code to follow. * From c9248f6c4dc7e6c36a57c9e1a8ddc27227eb6e15 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Wed, 6 Sep 2023 10:16:52 +0530 Subject: [PATCH 03/22] Add classes for formatting options --- .../core/BlockFormattingOptions.java | 119 ++++++++++++ .../formatter/core/FormatterUtils.java | 2 +- .../formatter/core/FormattingOptions.java | 175 +++++++++--------- .../core/FormattingTreeModifier.java | 25 ++- .../core/FunctionFormattingOptions.java | 67 +++++++ 5 files changed, 295 insertions(+), 93 deletions(-) create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java new file mode 100644 index 000000000000..3f8d577b8a29 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core; + +/** + * A model for formatting of functions by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class BlockFormattingOptions { + + private boolean allowShortBlocksOnASingleLine; + + private boolean allowShortMatchLabelsOnASingleLine; + + private boolean allowShortIfStatementsOnASingleLine; + + private boolean allowShortLoopsOnASingleLine; + + private boolean elseBlockOnANewLine; + + public BlockFormattingOptions(boolean allowShortBlocksOnASingleLine, boolean allowShortMatchLabelsOnASingleLine, + boolean allowShortIfStatementsOnASingleLine, boolean allowShortLoopsOnASingleLine, + boolean elseBlockOnANewLine) { + this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; + this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; + this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; + this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; + this.elseBlockOnANewLine = elseBlockOnANewLine; + } + + public boolean allowShortBlocksOnASingleLine() { + return allowShortBlocksOnASingleLine; + } + + public boolean allowShortMatchLabelsOnASingleLine() { + return allowShortMatchLabelsOnASingleLine; + } + + public boolean allowShortIfStatementsOnASingleLine() { + return allowShortIfStatementsOnASingleLine; + } + + public boolean allowShortLoopsOnASingleLine() { + return allowShortLoopsOnASingleLine; + } + + public boolean elseBlockOnANewLine() { + return elseBlockOnANewLine; + } + + public static BlockFormattingOptions.BlockFormattingOptionsBuilder builder() { + return new BlockFormattingOptions.BlockFormattingOptionsBuilder(); + } + + /** + * A builder for the {@code BlockFormattingOptions}. + */ + public static class BlockFormattingOptionsBuilder { + + private boolean allowShortBlocksOnASingleLine = false; + + private boolean allowShortMatchLabelsOnASingleLine = false; + + private boolean allowShortIfStatementsOnASingleLine = false; + + private boolean allowShortLoopsOnASingleLine = false; + + private boolean elseBlockOnANewLine = false; + + public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortBlocksOnASingleLine( + boolean allowShortBlocksOnASingleLine) { + this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; + return this; + } + + public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortMatchLabelsOnASingleLine( + boolean allowShortMatchLabelsOnASingleLine) { + this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; + return this; + } + + public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortIfStatementsOnASingleLine( + boolean allowShortIfStatementsOnASingleLine) { + this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; + return this; + } + + public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortLoopsOnASingleLine( + boolean allowShortLoopsOnASingleLine) { + this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; + return this; + } + + public BlockFormattingOptions.BlockFormattingOptionsBuilder setElseBlockOnANewLine( + boolean elseBlockOnANewLine) { + this.elseBlockOnANewLine = elseBlockOnANewLine; + return this; + } + + public BlockFormattingOptions build() { + return new BlockFormattingOptions(allowShortBlocksOnASingleLine, allowShortMatchLabelsOnASingleLine, + allowShortIfStatementsOnASingleLine, allowShortLoopsOnASingleLine, elseBlockOnANewLine); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 3ea2dfe95dbb..1552400e2606 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -165,7 +165,7 @@ private static boolean hasEmptyLineAtEnd(MinutiaeList minutiaeList) { minutiaeList.get(size - 2).kind() == SyntaxKind.END_OF_LINE_MINUTIAE; } - static boolean isBlockOnASingleLine(FormattingOptions options, BlockStatementNode node) { + static boolean isBlockOnASingleLine(BlockFormattingOptions options, BlockStatementNode node) { if (node.lineRange().startLine().line() != node.lineRange().endLine().line()) { return false; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java index 1168a0b45135..76395d6bf3f2 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java @@ -40,24 +40,18 @@ public class FormattingOptions { private boolean recordBraceSpacing; - private boolean allowShortBlocksOnASingleLine; - - private boolean allowShortMatchLabelsOnASingleLine; - - private boolean allowShortIfStatementsOnASingleLine; - - private boolean allowShortLoopsOnASingleLine; - - private boolean elseBlockOnANewLine; - - private boolean sortImports; - private boolean alignConsecutiveDefinitions; + private boolean alignMultiLineQueries; + private ForceFormattingOptions forceFormattingOptions; private ImportFormattingOptions importFormattingOptions; + private FunctionFormattingOptions functionFormattingOptions; + + private BlockFormattingOptions blockFormattingOptions; + private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, int continuationIndent, ForceFormattingOptions forceFormattingOptions, ImportFormattingOptions importFormattingOptions) { @@ -71,26 +65,25 @@ private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, bool } FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, - ForceFormattingOptions forceFormattingOptions, boolean paranAlignedIndentation, - boolean oneArgPerLine, boolean allowShortBlocksOnASingleLine, boolean recordBraceSpacing, - boolean elseBlockOnANewLine, boolean sortImports, boolean alignConsecutiveDefinitions, - boolean allowShortIfStatementsOnASingleLine, boolean allowShortLoopsOnASingleLine, - boolean allowShortMatchLabelsOnASingleLine) { + ForceFormattingOptions forceFormattingOptions, + boolean recordBraceSpacing, + boolean alignConsecutiveDefinitions, + boolean alignMultiLineQueries, + ImportFormattingOptions importFormattingOptions, + FunctionFormattingOptions functionFormattingOptions, + BlockFormattingOptions blockFormattingOptions) { this.tabSize = tabSize; this.wsCharacter = wsCharacter; this.columnLimit = columnLimit; this.lineWrapping = lineWrapping; this.forceFormattingOptions = forceFormattingOptions; - this.paranAlignedIndentation = paranAlignedIndentation; - this.oneArgPerLine = oneArgPerLine; this.recordBraceSpacing = recordBraceSpacing; - this.elseBlockOnANewLine = elseBlockOnANewLine; - this.sortImports = sortImports; this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; - this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; - this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; - this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; - this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; + this.alignMultiLineQueries = alignMultiLineQueries; + this.importFormattingOptions = importFormattingOptions; + this.functionFormattingOptions = functionFormattingOptions; + this.blockFormattingOptions = blockFormattingOptions; + } /** @@ -200,46 +193,26 @@ public ImportFormattingOptions getImportFormattingOptions() { return importFormattingOptions; } - public boolean isElseBlockOnANewLine() { - return elseBlockOnANewLine; - } - - public boolean isParanAlignedIndentation() { - return paranAlignedIndentation; + public FunctionFormattingOptions getFunctionFormattingOptions() { + return functionFormattingOptions; } - public boolean isOneArgPerLine() { - return oneArgPerLine; - } - - public boolean allowShortBlocksOnASingleLine() { - return allowShortBlocksOnASingleLine; - } - - public boolean allowShortMatchLabelsOnASingleLine() { - return allowShortMatchLabelsOnASingleLine; - } - - public boolean allowShortIfStatementsOnASingleLine() { - return allowShortIfStatementsOnASingleLine; - } - - public boolean allowShortLoopsOnASingleLine() { - return allowShortLoopsOnASingleLine; + public BlockFormattingOptions getBlockFormattingOptions() { + return blockFormattingOptions; } public boolean isRecordBraceSpacing() { return recordBraceSpacing; } - public boolean sortImports() { - return sortImports; - } - public boolean alignConsecutiveDefinitions() { return alignConsecutiveDefinitions; } + public boolean alignMultiLineQueries() { + return alignMultiLineQueries; + } + public static FormattingOptionsBuilder builder() { return new FormattingOptionsBuilder(); } @@ -258,15 +231,16 @@ public static class FormattingOptionsBuilder { private boolean paranAlignedIndentation = false; private boolean oneArgPerLine = false; private boolean recordBraceSpacing = false; - private boolean elseBlockOnANewLine = false; - private Boolean sortImports = false; - private Boolean alignConsecutiveDefinitions = false; - private boolean allowShortBlocksOnASingleLine = false; - private Boolean allowShortMatchLabelsOnASingleLine = false; - private Boolean allowShortLoopsOnASingleLine = false; - private Boolean allowShortIfStatementsOnASingleLine = false; + private boolean alignConsecutiveDefinitions = false; + private boolean alignMultiLineQueries = false; private ForceFormattingOptions forceFormattingOptions = ForceFormattingOptions.builder().build(); - private ImportFormattingOptions importFormattingOptions = ImportFormattingOptions.builder().build(); + private ImportFormattingOptions.ImportFormattingOptionsBuilder importBuilder = + ImportFormattingOptions.builder(); + private FunctionFormattingOptions.FunctionFormattingOptionsBuilder functionBuilder = + FunctionFormattingOptions.builder(); + private BlockFormattingOptions.BlockFormattingOptionsBuilder blockBuilder = + BlockFormattingOptions.builder(); + private ImportFormattingOptions importFormattingOptions = importBuilder.build(); public FormattingOptions.FormattingOptionsBuilder setTabSize(int tabSize) { this.tabSize = tabSize; @@ -317,41 +291,74 @@ public FormattingOptions build(Map configurations) { case "tabWidth": this.tabSize = ((Number) value).intValue(); break; - case "sortImports": - this.sortImports = ((Boolean) value); - break; case "alignConsecutiveDefinitions": this.alignConsecutiveDefinitions = ((Boolean) value); break; - case "allowShortMatchLabelsOnASingleLine": - this.allowShortMatchLabelsOnASingleLine = ((Boolean) value); - break; - case "allowShortIfStatementsOnASingleLine": - this.allowShortIfStatementsOnASingleLine = ((Boolean) value); - break; - case "allowShortLoopsOnASingleLine": - this.allowShortLoopsOnASingleLine = ((Boolean) value); - break; - case "allowShortBlocksOnASingleLine": - this.allowShortBlocksOnASingleLine = ((Boolean) value); - break; case "recordBraceSpacing": this.recordBraceSpacing = ((Boolean) value); break; - case "elseBlockOnANewLine": - this.elseBlockOnANewLine = ((Boolean) value); + case "alignMultiLineQueries": + this.alignMultiLineQueries = ((Boolean) value); + break; + case "block": + Map blockConfigurations = (Map) value; + for (Map.Entry funcEntry : blockConfigurations.entrySet()) { + String blockKey = funcEntry.getKey(); + boolean blockValue = (Boolean) funcEntry.getValue(); + switch (blockKey) { + case "elseBlockOnANewLine": + this.blockBuilder.setElseBlockOnANewLine(blockValue); + break; + case "allowShortMatchLabelsOnASingleLine": + this.blockBuilder.setAllowShortMatchLabelsOnASingleLine( + blockValue); + break; + case "allowShortIfStatementsOnASingleLine": + this.blockBuilder.setAllowShortIfStatementsOnASingleLine( + blockValue); + break; + case "allowShortLoopsOnASingleLine": + this.blockBuilder.setAllowShortLoopsOnASingleLine(blockValue); + break; + case "allowShortBlocksOnASingleLine": + this.blockBuilder.setAllowShortBlocksOnASingleLine(blockValue); + break; + default: + break; + } + } break; case "function": Map funcConfigurations = (Map) value; for (Map.Entry funcEntry : funcConfigurations.entrySet()) { String funcKey = funcEntry.getKey(); - Object funcValue = funcEntry.getValue(); + boolean funcValue = (Boolean) funcEntry.getValue(); switch (funcKey) { case "paranAlign": - this.paranAlignedIndentation = ((Boolean) funcValue); + this.functionBuilder.setParanAlign(funcValue); break; case "oneArgPerLine": - this.oneArgPerLine = ((Boolean) funcValue); + this.functionBuilder.setOneArgPerLine(funcValue); + break; + default: + break; + } + } + break; + case "import": + Map importConfigurations = (Map) value; + for (Map.Entry funcEntry : importConfigurations.entrySet()) { + String funcKey = funcEntry.getKey(); + boolean importValue = (Boolean) funcEntry.getValue(); + switch (funcKey) { + case "groupImports": + this.importBuilder.setGroupImports(importValue); + break; + case "sortImports": + this.importBuilder.setSortImports(importValue); + break; + case "removeUnusedImports": + this.importBuilder.setRemoveUnusedImports(importValue); break; default: break; @@ -363,9 +370,9 @@ public FormattingOptions build(Map configurations) { } } return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, forceFormattingOptions, - paranAlignedIndentation, oneArgPerLine, allowShortBlocksOnASingleLine, recordBraceSpacing, - elseBlockOnANewLine, sortImports, alignConsecutiveDefinitions, allowShortIfStatementsOnASingleLine, - allowShortLoopsOnASingleLine, allowShortMatchLabelsOnASingleLine); + recordBraceSpacing, + alignConsecutiveDefinitions, alignMultiLineQueries, importBuilder.build(), + functionBuilder.build(), blockBuilder.build()); } } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index bc596811ed56..53e3f821975b 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -372,13 +372,14 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo } Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); + boolean paranAlign = options.getFunctionFormattingOptions().paranAlign(); // Start a new indentation of two tabs for the parameters. - if (options.isParanAlignedIndentation()) { + if (paranAlign) { align(); } else { indent(options.getContinuationIndent()); } - boolean oneArgPerLine = options.isOneArgPerLine(); + boolean oneArgPerLine = options.getFunctionFormattingOptions().oneArgPerLine(); SeparatedNodeList parameters = formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, oneArgPerLine ? 1 : 0, @@ -394,7 +395,7 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo closePara = formatToken(functionSignatureNode.closeParenToken(), env.trailingWS, env.trailingNL); } - if (options.isParanAlignedIndentation()) { + if (paranAlign) { unalign(); } else { unindent(options.getContinuationIndent()); @@ -540,7 +541,7 @@ public IfElseStatementNode transform(IfElseStatementNode ifElseStatementNode) { BlockStatementNode ifBody; Node elseBody = null; if (ifElseStatementNode.elseBody().isPresent()) { - boolean needNL = options.isElseBlockOnANewLine(); + boolean needNL = options.getBlockFormattingOptions().elseBlockOnANewLine(); ifBody = formatNode(ifElseStatementNode.ifBody(), needNL ? 0 : 1, needNL ? 1 : 0); preserveIndentation(!hasTrailingNL(ifElseStatementNode.ifBody().closeBraceToken())); @@ -572,7 +573,7 @@ public ElseBlockNode transform(ElseBlockNode elseBlockNode) { public BlockStatementNode transform(BlockStatementNode blockStatementNode) { boolean preserveIndent = env.preserveIndentation; preserveIndentation(blockStatementNode.openBraceToken().isMissing() && preserveIndent); - int trailingNL = isBlockOnASingleLine(options, blockStatementNode) ? 0 : 1; + int trailingNL = isBlockOnASingleLine(options.getBlockFormattingOptions(), blockStatementNode) ? 0 : 1; int trailingWS = 1 - trailingNL; Token openBrace = formatToken(blockStatementNode.openBraceToken(), trailingWS, trailingNL); preserveIndentation(preserveIndent); @@ -581,7 +582,7 @@ public BlockStatementNode transform(BlockStatementNode blockStatementNode) { formatNodeList(blockStatementNode.statements(), 0, 1, trailingWS, trailingNL); unindent(); // end the indentation int closingNewLine = - (options.isElseBlockOnANewLine() && + (options.getBlockFormattingOptions().elseBlockOnANewLine() && blockStatementNode.parent().kind() == SyntaxKind.IF_ELSE_STATEMENT) ? 1 : env.trailingNL; Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, closingNewLine); @@ -2868,7 +2869,11 @@ public CollectClauseNode transform(CollectClauseNode collectClauseNode) { public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { int indentation = env.currentIndentation; if (indentation != 0) { - align(); + if (options.alignMultiLineQueries()) { + align(); + } else { + indent(); + } } QueryConstructTypeNode queryConstructType = @@ -2885,7 +2890,11 @@ public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { OnConflictClauseNode onConflictClause = formatNode(queryExpressionNode.onConflictClause().orElse(null), env.trailingWS, env.trailingNL); if (indentation != 0) { - unalign(); + if (options.alignMultiLineQueries()) { + unalign(); + } else { + unindent(); + } } return queryExpressionNode.modify() diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java new file mode 100644 index 000000000000..12beb82b3b21 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core; + +/** + * A model for formatting of functions by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class FunctionFormattingOptions { + + private boolean paranAlign; + private boolean oneArgPerLine; + + private FunctionFormattingOptions(boolean paranAlign, boolean oneArgPerLine) { + this.paranAlign = paranAlign; + this.oneArgPerLine = oneArgPerLine; + } + + public boolean paranAlign() { + return paranAlign; + } + + public boolean oneArgPerLine() { + return oneArgPerLine; + } + + public static FunctionFormattingOptions.FunctionFormattingOptionsBuilder builder() { + return new FunctionFormattingOptions.FunctionFormattingOptionsBuilder(); + } + + /** + * A builder for the {@code FunctionFormattingOptions}. + */ + public static class FunctionFormattingOptionsBuilder { + + private boolean paranAlign = false; + private boolean oneArgPerLine = false; + + public FunctionFormattingOptions.FunctionFormattingOptionsBuilder setParanAlign(boolean paranAlign) { + this.paranAlign = paranAlign; + return this; + } + + public FunctionFormattingOptions.FunctionFormattingOptionsBuilder setOneArgPerLine(boolean oneArgPerLine) { + this.oneArgPerLine = oneArgPerLine; + return this; + } + + public FunctionFormattingOptions build() { + return new FunctionFormattingOptions(oneArgPerLine, paranAlign); + } + } +} From 5fa06bf9074f4b7f40f4f4495ae54e8f0ca63491 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Thu, 7 Sep 2023 14:27:27 +0530 Subject: [PATCH 04/22] Add tests --- .../formatter/cli/FormatUtil.java | 13 ++------ .../formatter/cli/FormatCmdTest.java | 29 ++++++++++++++++++ .../blocks/assert/ifelse/main.bal | 12 ++++++++ .../blocks/assert/short/main.bal | 28 +++++++++++++++++ .../blocks/source/ifelse/Ballerina.toml | 2 ++ .../blocks/source/ifelse/main.bal | 10 +++++++ .../blocks/source/ifelseTemp/Ballerina.toml | 2 ++ .../blocks/source/ifelseTemp/main.bal | 10 +++++++ .../blocks/source/short/Ballerina.toml | 2 ++ .../blocks/source/short/main.bal | 28 +++++++++++++++++ .../blocks/source/shortTemp/Ballerina.toml | 2 ++ .../blocks/source/shortTemp/main.bal | 28 +++++++++++++++++ .../functions/assert/oneArg/main.bal | 12 ++++++++ .../functions/assert/paranAlign/main.bal | 5 ++++ .../assert/paranAlignOneArg/main.bal | 12 ++++++++ .../functions/source/oneArg/Ballerina.toml | 6 ++++ .../functions/source/oneArg/main.bal | 3 ++ .../source/oneArgTemp/Ballerina.toml | 6 ++++ .../functions/source/oneArgTemp/main.bal | 3 ++ .../source/paranAlign/Ballerina.toml | 6 ++++ .../functions/source/paranAlign/main.bal | 3 ++ .../source/paranAlignOneArg/Ballerina.toml | 6 ++++ .../source/paranAlignOneArg/main.bal | 3 ++ .../paranAlignOneArgTemp/Ballerina.toml | 6 ++++ .../source/paranAlignOneArgTemp/main.bal | 3 ++ .../source/paranAlignTemp/Ballerina.toml | 6 ++++ .../functions/source/paranAlignTemp/main.bal | 3 ++ .../general/assert/project/main.bal | 30 +++++++++++++++++++ .../general/source/project/Ballerina.toml | 6 ++++ .../general/source/project/main.bal | 28 +++++++++++++++++ .../general/source/projectTemp/Ballerina.toml | 6 ++++ .../general/source/projectTemp/main.bal | 28 +++++++++++++++++ .../imports/assert/project/main.bal | 10 +++++++ .../imports/source/project/Ballerina.toml | 3 ++ .../imports/source/project/main.bal | 8 +++++ .../imports/source/projectTemp/Ballerina.toml | 3 ++ .../imports/source/projectTemp/main.bal | 8 +++++ .../formatter/core/FormatterUtils.java | 1 + .../formatter/core/FormattingOptions.java | 30 ++++++++----------- .../core/FormattingTreeModifier.java | 20 ++++++++----- .../core/FunctionFormattingOptions.java | 2 +- 41 files changed, 396 insertions(+), 36 deletions(-) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index 88d4fe12eb0b..ad805f5b6324 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -43,7 +43,6 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import java.util.Map; /** * Util class for compilation and format execution for formatting CLI tool. @@ -129,7 +128,8 @@ static void execute(List argList, boolean helpFlag, String moduleName, S try { project = BuildProject.load(projectPath, constructBuildOptions()); - options = constructFormattingOptions(project.currentPackage().manifest().getValue("format")); + options = FormattingOptions.builder() + .build(project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -196,7 +196,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S FormattingOptions options; try { project = BuildProject.load(sourceRootPath, constructBuildOptions()); - options = constructFormattingOptions(project.currentPackage().manifest().getValue("format")); + options = FormattingOptions.builder().build(project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -340,13 +340,6 @@ private static BuildOptions constructBuildOptions() { .build(); } - private static FormattingOptions constructFormattingOptions(Object configurations) { - if (configurations instanceof Map) { - return FormattingOptions.builder().build((Map) configurations); - } - return FormattingOptions.builder().build(); - } - /** * Check whether the given module name exists. * diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index 4366c04c0df8..4f8c09c942d2 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -29,6 +29,8 @@ import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; + /** * Format CLI tool test suit for testing tool's exceptions. @@ -51,6 +53,9 @@ public class FormatCmdTest { RES_DIR.resolve("BallerinaProject/source/ProjectTemp"); private static final Path BALLERINA_PROJECT_ASSERT = RES_DIR.resolve("BallerinaProject/assert/Project"); + private static final Path[] BALLERINA_CONFIGURATION_DIRS = + {RES_DIR.resolve("configurations/general/source"), RES_DIR.resolve("configurations/functions/source"), + RES_DIR.resolve("configurations/blocks/source"), RES_DIR.resolve("configurations/imports/source")}; @Test(description = "Test single file project formatting") public void formatCLIOnASingleFileProject() { @@ -82,6 +87,30 @@ public void formatCLIOnBallerinaProject() { } } + @Test(description = "Test ballerina project formatting") + public void formatCLIOnBallerinaProjectWithConfigurations() { + List argList = new ArrayList<>(); + for (Path dir : BALLERINA_CONFIGURATION_DIRS) { + try { + List subDirs = Files.list(dir) + .filter(Files::isDirectory) + .filter(d -> !d.getFileName().toString().endsWith("Temp")) + .collect(Collectors.toList()); + for (Path subDir : subDirs) { + Path tempDir = subDir.resolveSibling(subDir.getFileName() + "Temp"); + Path assertDir = Paths.get(subDir.toString().replace("/source/", "/assert/")); + + FormatUtil.execute(argList, false, null, null, false, subDir); + Assert.assertEquals(Files.readString(subDir.resolve("main.bal")), + Files.readString(assertDir.resolve("main.bal"))); + FileUtils.copyDirectory(tempDir.toFile(), subDir.toFile()); + } + } catch (IOException e) { + Assert.fail("Failed to update the source file."); + } + } + } + @Test(description = "Test ballerina project formatting with dot op", dependsOnMethods = "formatCLIOnBallerinaProject") public void formatCLIOnBallerinaProjectWithDotOp() { diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal new file mode 100644 index 000000000000..13d800f082aa --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal @@ -0,0 +1,12 @@ +function getGrades(int score) returns string { + int i = 0; + if 0 < score && score < 55 { + return "F"; + } + else if 55 <= score && score < 65 { + return "C"; + } + else { + return "Invalid grade"; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal new file mode 100644 index 000000000000..6a02e7972421 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal @@ -0,0 +1,28 @@ +import ballerina/io; + +function loop(int times) { + int count = 1; + while (count <= times) { count += 1; } +} + +function getSign(int number) returns string { + if number <= 0 { return "+"; } + else { return "-"; } +} + +function btoi(boolean? b) returns int { + match b { + true => { return 1; } + false => { return 0; } + } + return 0; +} + +function printFalse() { + boolean b = false; + if b { + io:println(1); + } else { + io:println(0); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml new file mode 100644 index 000000000000..46da4d2ea121 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml @@ -0,0 +1,2 @@ +[format.block] +elseBlockOnANewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal new file mode 100644 index 000000000000..0ef276a11ccd --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal @@ -0,0 +1,10 @@ +function getGrades(int score) returns string { + int i = 0; + if 0 < score && score < 55 { + return "F"; + } else if 55 <= score && score < 65 { + return "C" ; + } else { + return "Invalid grade"; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml new file mode 100644 index 000000000000..46da4d2ea121 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml @@ -0,0 +1,2 @@ +[format.block] +elseBlockOnANewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal new file mode 100644 index 000000000000..0ef276a11ccd --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal @@ -0,0 +1,10 @@ +function getGrades(int score) returns string { + int i = 0; + if 0 < score && score < 55 { + return "F"; + } else if 55 <= score && score < 65 { + return "C" ; + } else { + return "Invalid grade"; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml new file mode 100644 index 000000000000..e564c5b8e750 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml @@ -0,0 +1,2 @@ +[format.block] +allowShortBlocksOnASingleLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal new file mode 100644 index 000000000000..ebc7abe07844 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal @@ -0,0 +1,28 @@ +import ballerina/io; + +function loop(int times) { + int count = 1; + while (count <= times) {count+= 1;} +} + +function getSign(int number) returns string { + if number <= 0 { return "+"; } + else { return "-"; } +} + +function btoi(boolean? b) returns int { + match b { + true => { return 1; } + false => { return 0; } + } + return 0; +} + +function printFalse() { + boolean b = false; + if b { + io:println(1); + } else { + io:println(0); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml new file mode 100644 index 000000000000..e564c5b8e750 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml @@ -0,0 +1,2 @@ +[format.block] +allowShortBlocksOnASingleLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal new file mode 100644 index 000000000000..ebc7abe07844 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal @@ -0,0 +1,28 @@ +import ballerina/io; + +function loop(int times) { + int count = 1; + while (count <= times) {count+= 1;} +} + +function getSign(int number) returns string { + if number <= 0 { return "+"; } + else { return "-"; } +} + +function btoi(boolean? b) returns int { + match b { + true => { return 1; } + false => { return 0; } + } + return 0; +} + +function printFalse() { + boolean b = false; + if b { + io:println(1); + } else { + io:println(0); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal new file mode 100644 index 000000000000..4ed9faab0f06 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal @@ -0,0 +1,12 @@ +function add(int first, + int second, + int third, + int fourth, + int fifth, + int sixth, + int seventh, + int eighth, + int ninth, + int tenth) returns int { + return first + second + third + fourth + fifth + sixth + seventh + eighth + ninth + tenth; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal new file mode 100644 index 000000000000..8cf2924eb59a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal @@ -0,0 +1,5 @@ +function add(int first, int second, int third, int fourth, int fifth, int sixth, + int seventh, int eighth, int ninth, int tenth) returns int { + return first + second + third + fourth + fifth + sixth + seventh + eighth + + ninth + tenth; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal new file mode 100644 index 000000000000..645895d5a3b4 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal @@ -0,0 +1,12 @@ +function add(int first, + int second, + int third, + int fourth, + int fifth, + int sixth, + int seventh, + int eighth, + int ninth, + int tenth) returns int { + return first + second + third + fourth + fifth + sixth + seventh + eighth + ninth + tenth; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml new file mode 100644 index 000000000000..2d973bf34d28 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 120 + +[format.function] +oneArgPerLine = true +paranAlign = false diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml new file mode 100644 index 000000000000..2d973bf34d28 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 120 + +[format.function] +oneArgPerLine = true +paranAlign = false diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml new file mode 100644 index 000000000000..3db3e0dffd45 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 80 + +[format.function] +oneArgPerLine = false +paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml new file mode 100644 index 000000000000..fc8043bfb8d5 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 120 + +[format.function] +oneArgPerLine = true +paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml new file mode 100644 index 000000000000..fc8043bfb8d5 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 120 + +[format.function] +oneArgPerLine = true +paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml new file mode 100644 index 000000000000..3db3e0dffd45 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +columnLimit = 80 + +[format.function] +oneArgPerLine = false +paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal new file mode 100644 index 000000000000..3e45b4fc3c3c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal @@ -0,0 +1,3 @@ +function add ( int first, int second,int third,int fourth, int fifth, int sixth, int seventh, int eighth, int ninth,int tenth) returns int { + return first+ second + third + fourth + fifth + sixth + seventh+eighth + ninth+ tenth ; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal new file mode 100644 index 000000000000..d471072bc4e6 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal @@ -0,0 +1,30 @@ +const int MAX_STUDENTS = 100; +const string WELCOME_MESSAGE = "Welcome"; +const int MAX_AGE = 20; + +type Student record { + string name; + int age; +}; + +function registerStudent(Student[] students, string name, int age, + int numStudents) returns boolean { + if numStudents < MAX_STUDENTS { + students.push({ name, age }); + return true; + } else { + return false; + } +} + +function queryTest() { + int[] nums = [1, 2, 3, 4]; + int[] numsTimes10 = from var i in nums + select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml new file mode 100644 index 000000000000..5228a18778ab --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +tabWidth = 2 +recordBraceSpacing = true +columnLimit = 80 +alignMultiLineQueries = true +alignConsecutiveDefinitions = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal new file mode 100644 index 000000000000..c7d45c69e9ae --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal @@ -0,0 +1,28 @@ +const int MAX_STUDENTS = 100; +const string WELCOME_MESSAGE = "Welcome"; +const int MAX_AGE = 20; + +type Student record { + string name; + int age; +}; + +function registerStudent(Student[] students, string name, int age, int numStudents) returns boolean { + if numStudents < MAX_STUDENTS { + students.push({name, age}); + return true; + } else { + return false; + } +} + +function queryTest() { + int[] nums = [1 , 2,3, 4]; + int[] numsTimes10 = from var i in nums select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml new file mode 100644 index 000000000000..5228a18778ab --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml @@ -0,0 +1,6 @@ +[format] +tabWidth = 2 +recordBraceSpacing = true +columnLimit = 80 +alignMultiLineQueries = true +alignConsecutiveDefinitions = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal new file mode 100644 index 000000000000..c7d45c69e9ae --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal @@ -0,0 +1,28 @@ +const int MAX_STUDENTS = 100; +const string WELCOME_MESSAGE = "Welcome"; +const int MAX_AGE = 20; + +type Student record { + string name; + int age; +}; + +function registerStudent(Student[] students, string name, int age, int numStudents) returns boolean { + if numStudents < MAX_STUDENTS { + students.push({name, age}); + return true; + } else { + return false; + } +} + +function queryTest() { + int[] nums = [1 , 2,3, 4]; + int[] numsTimes10 = from var i in nums select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal new file mode 100644 index 000000000000..5011afcd4765 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal @@ -0,0 +1,10 @@ +import cal.add; +import cal.err; +import cal.sub; + +import ballerina/file; +import ballerina/http; +import ballerina/io; +import ballerina/log; +import ballerinax/googleapis.gmail as gmail; + diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml new file mode 100644 index 000000000000..b3f9282ffb26 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml @@ -0,0 +1,3 @@ +[format.import] +groupImports = true +sortImports = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal new file mode 100644 index 000000000000..bd15866e8e63 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal @@ -0,0 +1,8 @@ +import ballerinax/googleapis.gmail as gmail; +import ballerina/http; +import cal.add; +import ballerina/log; +import ballerina/file; +import ballerina/io; +import cal.sub; +import cal.err; diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml new file mode 100644 index 000000000000..b3f9282ffb26 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml @@ -0,0 +1,3 @@ +[format.import] +groupImports = true +sortImports = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal new file mode 100644 index 000000000000..bd15866e8e63 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal @@ -0,0 +1,8 @@ +import ballerinax/googleapis.gmail as gmail; +import ballerina/http; +import cal.add; +import ballerina/log; +import ballerina/file; +import ballerina/io; +import cal.sub; +import cal.err; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 1552400e2606..9f8b758318b8 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -183,6 +183,7 @@ static boolean isBlockOnASingleLine(BlockFormattingOptions options, BlockStateme static int getConstDefLength(ConstantDeclarationNode node) { int size = node.visibilityQualifier().isPresent() ? node.visibilityQualifier().get().text().length() : 0; size += node.constKeyword().text().length(); + size += node.typeDescriptor().isPresent() ? node.typeDescriptor().get().toSourceCode().length() : 0; size += node.variableName().text().length(); return size; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java index 76395d6bf3f2..1a4f65c75ae7 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java @@ -53,18 +53,7 @@ public class FormattingOptions { private BlockFormattingOptions blockFormattingOptions; private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, - int continuationIndent, ForceFormattingOptions forceFormattingOptions, - ImportFormattingOptions importFormattingOptions) { - this.tabSize = tabSize; - this.wsCharacter = wsCharacter; - this.columnLimit = columnLimit; - this.lineWrapping = lineWrapping; - this.continuationIndent = continuationIndent; - this.forceFormattingOptions = forceFormattingOptions; - this.importFormattingOptions = importFormattingOptions; - } - - FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, + int continuationIndent, ForceFormattingOptions forceFormattingOptions, boolean recordBraceSpacing, boolean alignConsecutiveDefinitions, @@ -76,6 +65,7 @@ private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, bool this.wsCharacter = wsCharacter; this.columnLimit = columnLimit; this.lineWrapping = lineWrapping; + this.continuationIndent = continuationIndent; this.forceFormattingOptions = forceFormattingOptions; this.recordBraceSpacing = recordBraceSpacing; this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; @@ -275,11 +265,16 @@ public FormattingOptions.FormattingOptionsBuilder setImportFormattingOptions( } public FormattingOptions build() { - return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, - forceFormattingOptions, importFormattingOptions); + return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, forceFormattingOptions, + recordBraceSpacing, alignConsecutiveDefinitions, alignMultiLineQueries, importFormattingOptions, + functionBuilder.build(), blockBuilder.build()); } - public FormattingOptions build(Map configurations) { + public FormattingOptions build(Object data) { + if (!(data instanceof Map)) { + return build(); + } + Map configurations = (Map) data; for (Map.Entry entry : configurations.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); @@ -369,9 +364,8 @@ public FormattingOptions build(Map configurations) { break; } } - return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, forceFormattingOptions, - recordBraceSpacing, - alignConsecutiveDefinitions, alignMultiLineQueries, importBuilder.build(), + return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, forceFormattingOptions, + recordBraceSpacing, alignConsecutiveDefinitions, alignMultiLineQueries, importBuilder.build(), functionBuilder.build(), blockBuilder.build()); } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 53e3f821975b..8952668f32ad 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -382,8 +382,13 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo boolean oneArgPerLine = options.getFunctionFormattingOptions().oneArgPerLine(); SeparatedNodeList parameters = formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, - oneArgPerLine ? 1 : 0, - 0, 0); + oneArgPerLine ? 1 : 0, 0, 0, true); + + if (paranAlign) { + unalign(); + } else { + unindent(2); + } Token closePara; ReturnTypeDescriptorNode returnTypeDesc = null; @@ -1103,7 +1108,6 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC env.currentIndentation = prevIndentation; Token functionCallClosePara = formatToken(functionCallExpressionNode.closeParenToken(), env.trailingWS, env.trailingNL); - unindent(2); return functionCallExpressionNode.modify() .withFunctionName(functionName) .withOpenParenToken(functionCallOpenPara) @@ -2867,8 +2871,8 @@ public CollectClauseNode transform(CollectClauseNode collectClauseNode) { @Override public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { - int indentation = env.currentIndentation; - if (indentation != 0) { + int length = options.alignMultiLineQueries() ? env.currentIndentation : env.lineLength; + if (length != 0) { if (options.alignMultiLineQueries()) { align(); } else { @@ -2889,7 +2893,7 @@ public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { OnConflictClauseNode onConflictClause = formatNode(queryExpressionNode.onConflictClause().orElse(null), env.trailingWS, env.trailingNL); - if (indentation != 0) { + if (length != 0) { if (options.alignMultiLineQueries()) { unalign(); } else { @@ -4183,7 +4187,9 @@ protected SeparatedNodeList formatSeparatedNodeList(Separate if (allowInAndMultiLine) { separatorTrailingWS = 0; separatorTrailingNL = 0; - if (hasNonWSMinutiae(oldSeparator.trailingMinutiae())) { + if (hasNonWSMinutiae(oldSeparator.trailingMinutiae()) || + (options.getFunctionFormattingOptions().oneArgPerLine() && + oldNode.parent().kind() == SyntaxKind.FUNCTION_SIGNATURE)) { separatorTrailingNL++; } else { separatorTrailingWS++; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java index 12beb82b3b21..8a17f7342ae6 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java @@ -61,7 +61,7 @@ public FunctionFormattingOptions.FunctionFormattingOptionsBuilder setOneArgPerLi } public FunctionFormattingOptions build() { - return new FunctionFormattingOptions(oneArgPerLine, paranAlign); + return new FunctionFormattingOptions(paranAlign, oneArgPerLine); } } } From 4b55ce4452f05cf9964860b98e056a3c06e8b675 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Fri, 8 Sep 2023 18:29:55 +0530 Subject: [PATCH 05/22] Update formatting in LS --- .../main/resources/ballerina-toml-schema.json | 58 +++++++---- .../BallerinaTextDocumentService.java | 17 +++- .../langserver/formatting/FormattingTest.java | 30 ++++++ .../formatting/project/Ballerina.toml | 12 +++ .../resources/formatting/project/main.bal | 15 +++ .../formatting/projectExpected/main.bal | 19 ++++ .../config/table_array_context/config1.json | 28 ++++++ .../config/table_context/config1.json | 28 ++++++ .../config/table_context/config2.json | 28 ++++++ .../formatter/cli/FormatUtil.java | 1 - .../formatter/cli/FormatCmdTest.java | 58 ++++++----- .../core/BlockFormattingOptions.java | 18 +--- .../formatter/core/FormatterUtils.java | 12 +-- .../core/FormattingTreeModifier.java | 96 +++++++++++-------- .../core/FunctionFormattingOptions.java | 8 +- 15 files changed, 318 insertions(+), 110 deletions(-) create mode 100644 language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml create mode 100644 language-server/modules/langserver-core/src/test/resources/formatting/project/main.bal create mode 100644 language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal diff --git a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json index bc4ff00f6810..cd093532cef0 100644 --- a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json +++ b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json @@ -356,33 +356,39 @@ "type": "object", "additionalProperties": true, "properties": { - "columnLimit": { - "type": "integer" - }, - "tabWidth": { - "type": "integer" - }, - "allowShortBlocksOnASingleLine": { - "type": "boolean" - }, - "allowShortMatchLabelsOnASingleLine": { - "type": "boolean" - }, - "allowShortIfStatementsOnASingleLine": { - "type": "boolean" - }, - "allowShortLoopsOnASingleLine": { - "type": "boolean" - }, "alignConsecutiveDefinitions": { "type": "boolean" }, - "elseBlocksOnANewLine": { - "type": "boolean" + "columnLimit": { + "type": "integer" }, "recordBraceSpacing": { "type": "boolean" }, + "tabWidth": { + "type": "integer" + }, + "block": { + "type": "object", + "additionalProperties": true, + "properties": { + "allowShortBlocksOnASingleLine": { + "type": "boolean" + }, + "allowShortMatchLabelsOnASingleLine": { + "type": "boolean" + }, + "allowShortIfStatementsOnASingleLine": { + "type": "boolean" + }, + "allowShortLoopsOnASingleLine": { + "type": "boolean" + }, + "elseBlocksOnANewLine": { + "type": "boolean" + } + } + }, "function": { "type": "object", "additionalProperties": true, @@ -394,6 +400,18 @@ "type": "boolean" } } + }, + "import": { + "type": "object", + "additionalProperties": true, + "properties": { + "groupImports": { + "type": "boolean" + }, + "sortImports": { + "type": "boolean" + } + } } } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index fc48c05a3737..ea4676ae38f1 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -16,11 +16,15 @@ package org.ballerinalang.langserver; import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.projects.BuildOptions; import io.ballerina.projects.Module; +import io.ballerina.projects.ProjectKind; +import io.ballerina.projects.directory.BuildProject; import io.ballerina.tools.text.LinePosition; import io.ballerina.tools.text.LineRange; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormattingOptions; import org.ballerinalang.langserver.codelenses.CodeLensUtil; import org.ballerinalang.langserver.codelenses.LSCodeLensesProviderHolder; import org.ballerinalang.langserver.common.utils.PathUtil; @@ -439,7 +443,18 @@ public CompletableFuture> formatting(DocumentFormatting if (syntaxTree.isEmpty()) { return Collections.emptyList(); } - String formattedSource = Formatter.format(syntaxTree.get()).toSourceCode(); + String formattedSource; + if (context.currentModule().isPresent() && + !(context.currentModule().get().project().kind() == ProjectKind.SINGLE_FILE_PROJECT)) { + Path rootPath = context.workspace().projectRoot(context.filePath()); + BuildProject project = BuildProject.load(rootPath, BuildOptions.builder().build()); + FormattingOptions options = FormattingOptions.builder() + .build(project.currentPackage().manifest().getValue("format")); + formattedSource = Formatter.format(syntaxTree.get(), options).toSourceCode(); + } else { + formattedSource = Formatter.format(syntaxTree.get()).toSourceCode(); + } + LinePosition eofPos = syntaxTree.get().rootNode().lineRange().endLine(); Range range = new Range(new Position(0, 0), new Position(eofPos.line() + 1, eofPos.offset())); TextEdit textEdit = new TextEdit(range, formattedSource); diff --git a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java index fd75eb2fe1d3..9b9fb900e2bf 100644 --- a/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java +++ b/language-server/modules/langserver-core/src/test/java/org/ballerinalang/langserver/formatting/FormattingTest.java @@ -77,6 +77,36 @@ public void formatTestSuit() throws IOException { Assert.assertEquals(actual, expected); } + @Test(description = "test formatting functionality on functions with configurations") + public void formatTestSuiteWithConfigurations() throws IOException { + Path inputProject = formattingDirectory.resolve("project"); + Path expectedProject = formattingDirectory.resolve("projectExpected"); + Path expectedFilePath = expectedProject.resolve("main.bal"); + Path inputFilePath = inputProject.resolve("main.bal"); + + String expected = new String(Files.readAllBytes(expectedFilePath)); + expected = expected.replaceAll("\\r\\n", "\n"); + DocumentFormattingParams documentFormattingParams = new DocumentFormattingParams(); + + TextDocumentIdentifier textDocumentIdentifier1 = new TextDocumentIdentifier(); + textDocumentIdentifier1.setUri(Paths.get(inputFilePath.toString()).toUri().toString()); + + FormattingOptions formattingOptions = new FormattingOptions(); + + documentFormattingParams.setOptions(formattingOptions); + documentFormattingParams.setTextDocument(textDocumentIdentifier1); + + TestUtil.openDocument(this.serviceEndpoint, inputFilePath); + + String result = TestUtil.getFormattingResponse(documentFormattingParams, this.serviceEndpoint); + Gson gson = new Gson(); + ResponseMessage responseMessage = gson.fromJson(result, ResponseMessage.class); + String actual = (String) ((LinkedTreeMap) ((List) responseMessage.getResult()).get(0)).get("newText"); + actual = actual.replaceAll("\\r\\n", "\n"); + TestUtil.closeDocument(this.serviceEndpoint, inputFilePath); + Assert.assertEquals(actual, expected); + } + @AfterClass public void shutdownLanguageServer() throws IOException { TestUtil.shutdownLanguageServer(this.serviceEndpoint); diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml new file mode 100644 index 000000000000..04ab55c5f850 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml @@ -0,0 +1,12 @@ +[format] +columnLimit = 80 +tabWidth = 2 +recordBraceSpacing = true + +[format.function] +oneArgPerLine = false +paranAlign = true + +[format.block] +allowShortMatchLabelsOnASingleLine = true +elseBlocksOnANewLine = true diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/main.bal b/language-server/modules/langserver-core/src/test/resources/formatting/project/main.bal new file mode 100644 index 000000000000..57e3a6ae2350 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/main.bal @@ -0,0 +1,15 @@ +function getDateFormatIncludingDayName (string year,int month,int day, int dayNumber ) returns string { + string? text = () ; + match dayNumber { + 1 => {text = "Sunday";} + 2 => { text = "Monday";} + 3 => { text = "Tuesday"; } + 4 => {text = "Wednesday";} + 5 => {text = "Thursday" ;} + 6 => {text = "Friday";} + 7 => {text = "Saturday" ;} + } + if text !is () { return string`${year} ${month} ${text} ${day}`; + } + else { return string`${year} ${month} ${day}`; } +} diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal b/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal new file mode 100644 index 000000000000..73cd652fd302 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal @@ -0,0 +1,19 @@ +function getDateFormatIncludingDayName(string year, int month, int day, + int dayNumber) returns string { + string? text = (); + match dayNumber { + 1 => { text = "Sunday"; } + 2 => { text = "Monday"; } + 3 => { text = "Tuesday"; } + 4 => { text = "Wednesday"; } + 5 => { text = "Thursday"; } + 6 => { text = "Friday"; } + 7 => { text = "Saturday"; } + } + if text !is () { + return string `${year} ${month} ${text} ${day}`; + } + else { + return string `${year} ${month} ${day}`; + } +} diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json index b7f3c1b473b2..b52f405b033a 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json @@ -92,6 +92,34 @@ "detail": "Table Array", "sortText": "C", "insertText": "[[dependency]]" + }, + { + "label": "format", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format]" + }, + { + "label": "format.function", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.function]" + }, + { + "label": "format.import", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.import]" + }, + { + "label": "format.block", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.block]" } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json index 3eae823649f8..37d4a6e08445 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json @@ -113,6 +113,34 @@ "detail": "Boolean", "sortText": "A", "insertText": "template=${1:false}" + }, + { + "label": "format", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format]" + }, + { + "label": "format.function", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.function]" + }, + { + "label": "format.import", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.import]" + }, + { + "label": "format.block", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.block]" } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json index 1503e59c3beb..c0bbe33d33a4 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json @@ -113,6 +113,34 @@ "detail": "Boolean", "sortText": "A", "insertText": "template=${1:false}" + }, + { + "label": "format", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format]" + }, + { + "label": "format.function", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.function]" + }, + { + "label": "format.import", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.import]" + }, + { + "label": "format.block", + "kind": "Snippet", + "detail": "Table", + "sortText": "C", + "insertText": "[format.block]" } ] } diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index ad805f5b6324..c490432660ba 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -29,7 +29,6 @@ import org.ballerinalang.formatter.core.FormatterException; import org.ballerinalang.formatter.core.FormattingOptions; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index 4f8c09c942d2..754194dac817 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -20,6 +20,7 @@ import io.ballerina.cli.launcher.BLauncherException; import org.apache.commons.io.FileUtils; import org.testng.Assert; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; @@ -29,8 +30,6 @@ import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - /** * Format CLI tool test suit for testing tool's exceptions. @@ -53,9 +52,6 @@ public class FormatCmdTest { RES_DIR.resolve("BallerinaProject/source/ProjectTemp"); private static final Path BALLERINA_PROJECT_ASSERT = RES_DIR.resolve("BallerinaProject/assert/Project"); - private static final Path[] BALLERINA_CONFIGURATION_DIRS = - {RES_DIR.resolve("configurations/general/source"), RES_DIR.resolve("configurations/functions/source"), - RES_DIR.resolve("configurations/blocks/source"), RES_DIR.resolve("configurations/imports/source")}; @Test(description = "Test single file project formatting") public void formatCLIOnASingleFileProject() { @@ -87,30 +83,46 @@ public void formatCLIOnBallerinaProject() { } } - @Test(description = "Test ballerina project formatting") - public void formatCLIOnBallerinaProjectWithConfigurations() { + @Test(description = "Test ballerina project formatting with configurations", + dataProvider = "provideConfigurationProjects") + public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List dirs) { List argList = new ArrayList<>(); - for (Path dir : BALLERINA_CONFIGURATION_DIRS) { - try { - List subDirs = Files.list(dir) - .filter(Files::isDirectory) - .filter(d -> !d.getFileName().toString().endsWith("Temp")) - .collect(Collectors.toList()); - for (Path subDir : subDirs) { - Path tempDir = subDir.resolveSibling(subDir.getFileName() + "Temp"); - Path assertDir = Paths.get(subDir.toString().replace("/source/", "/assert/")); + try { + for (Path dir : dirs) { + Path tempDir = dir.resolveSibling(dir.getFileName() + "Temp"); + Path assertDir = Paths.get(dir.toString().replace("/source/", "/assert/")); - FormatUtil.execute(argList, false, null, null, false, subDir); - Assert.assertEquals(Files.readString(subDir.resolve("main.bal")), - Files.readString(assertDir.resolve("main.bal"))); - FileUtils.copyDirectory(tempDir.toFile(), subDir.toFile()); - } - } catch (IOException e) { - Assert.fail("Failed to update the source file."); + FormatUtil.execute(argList, false, null, null, false, dir); + Assert.assertEquals(Files.readString(dir.resolve("main.bal")), + Files.readString(assertDir.resolve("main.bal"))); + FileUtils.copyDirectory(tempDir.toFile(), dir.toFile()); } + } catch (IOException e) { + Assert.fail(testCase + " test failed to update the source file."); } } + @DataProvider(name = "provideConfigurationProjects") + private Object[][] provideConfigurationProjects() { + return new Object[][]{ + {"general", List.of( + RES_DIR.resolve("configurations/general/source/project") + )}, + {"function", List.of( + RES_DIR.resolve("configurations/functions/source/oneArg"), + RES_DIR.resolve("configurations/functions/source/paranAlign"), + RES_DIR.resolve("configurations/functions/source/paranAlignOneArg") + )}, + {"blocks", List.of( + RES_DIR.resolve("configurations/blocks/source/ifelse"), + RES_DIR.resolve("configurations/blocks/source/short") + )}, + {"import", List.of( + RES_DIR.resolve("configurations/imports/source/project") + )} + }; + } + @Test(description = "Test ballerina project formatting with dot op", dependsOnMethods = "formatCLIOnBallerinaProject") public void formatCLIOnBallerinaProjectWithDotOp() { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java index 3f8d577b8a29..dd4944b57e9a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java @@ -22,15 +22,11 @@ */ public class BlockFormattingOptions { - private boolean allowShortBlocksOnASingleLine; - - private boolean allowShortMatchLabelsOnASingleLine; - - private boolean allowShortIfStatementsOnASingleLine; - - private boolean allowShortLoopsOnASingleLine; - - private boolean elseBlockOnANewLine; + private final boolean allowShortBlocksOnASingleLine; + private final boolean allowShortMatchLabelsOnASingleLine; + private final boolean allowShortIfStatementsOnASingleLine; + private final boolean allowShortLoopsOnASingleLine; + private final boolean elseBlockOnANewLine; public BlockFormattingOptions(boolean allowShortBlocksOnASingleLine, boolean allowShortMatchLabelsOnASingleLine, boolean allowShortIfStatementsOnASingleLine, boolean allowShortLoopsOnASingleLine, @@ -72,13 +68,9 @@ public static BlockFormattingOptions.BlockFormattingOptionsBuilder builder() { public static class BlockFormattingOptionsBuilder { private boolean allowShortBlocksOnASingleLine = false; - private boolean allowShortMatchLabelsOnASingleLine = false; - private boolean allowShortIfStatementsOnASingleLine = false; - private boolean allowShortLoopsOnASingleLine = false; - private boolean elseBlockOnANewLine = false; public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortBlocksOnASingleLine( diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 9f8b758318b8..336b48f55b32 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -165,22 +165,22 @@ private static boolean hasEmptyLineAtEnd(MinutiaeList minutiaeList) { minutiaeList.get(size - 2).kind() == SyntaxKind.END_OF_LINE_MINUTIAE; } - static boolean isBlockOnASingleLine(BlockFormattingOptions options, BlockStatementNode node) { + static int openBraceTrailingNLs(BlockFormattingOptions options, BlockStatementNode node) { if (node.lineRange().startLine().line() != node.lineRange().endLine().line()) { - return false; + return 1; } if (options.allowShortBlocksOnASingleLine()) { - return true; + return 0; } SyntaxKind parentKind = node.parent().kind(); - return (options.allowShortIfStatementsOnASingleLine() && parentKind == SyntaxKind.IF_ELSE_STATEMENT) || + return (options.allowShortIfStatementsOnASingleLine() && parentKind == SyntaxKind.IF_ELSE_STATEMENT) || (options.allowShortLoopsOnASingleLine() && parentKind == SyntaxKind.WHILE_STATEMENT) || - (options.allowShortMatchLabelsOnASingleLine() && parentKind == SyntaxKind.MATCH_CLAUSE); + (options.allowShortMatchLabelsOnASingleLine() && parentKind == SyntaxKind.MATCH_CLAUSE) ? 0 : 1; } - static int getConstDefLength(ConstantDeclarationNode node) { + static int getConstDefWidth(ConstantDeclarationNode node) { int size = node.visibilityQualifier().isPresent() ? node.visibilityQualifier().get().text().length() : 0; size += node.constKeyword().text().length(); size += node.typeDescriptor().isPresent() ? node.typeDescriptor().get().toSourceCode().length() : 0; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 8952668f32ad..df2029226bc9 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -259,8 +259,8 @@ import java.util.stream.Collectors; import static org.ballerinalang.formatter.core.FormatterUtils.isInlineRange; -import static org.ballerinalang.formatter.core.FormatterUtils.isBlockOnASingleLine; -import static org.ballerinalang.formatter.core.FormatterUtils.getConstDefLength; +import static org.ballerinalang.formatter.core.FormatterUtils.openBraceTrailingNLs; +import static org.ballerinalang.formatter.core.FormatterUtils.getConstDefWidth; import static org.ballerinalang.formatter.core.FormatterUtils.sortImportDeclarations; import static org.ballerinalang.formatter.core.FormatterUtils.swapLeadingMinutiae; @@ -372,23 +372,14 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo } Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); - boolean paranAlign = options.getFunctionFormattingOptions().paranAlign(); + boolean paranAlign = options.getFunctionFormattingOptions().getParanAlign(); // Start a new indentation of two tabs for the parameters. - if (paranAlign) { - align(); - } else { - indent(options.getContinuationIndent()); - } - boolean oneArgPerLine = options.getFunctionFormattingOptions().oneArgPerLine(); + alignOrIndent(paranAlign, options.getContinuationIndent()); + boolean oneArgPerLine = options.getFunctionFormattingOptions().getOneArgPerLine(); SeparatedNodeList parameters = formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, oneArgPerLine ? 1 : 0, 0, 0, true); - - if (paranAlign) { - unalign(); - } else { - unindent(2); - } + unalignOrUnindent(paranAlign, options.getContinuationIndent()); Token closePara; ReturnTypeDescriptorNode returnTypeDesc = null; @@ -578,7 +569,7 @@ public ElseBlockNode transform(ElseBlockNode elseBlockNode) { public BlockStatementNode transform(BlockStatementNode blockStatementNode) { boolean preserveIndent = env.preserveIndentation; preserveIndentation(blockStatementNode.openBraceToken().isMissing() && preserveIndent); - int trailingNL = isBlockOnASingleLine(options.getBlockFormattingOptions(), blockStatementNode) ? 0 : 1; + int trailingNL = openBraceTrailingNLs(options.getBlockFormattingOptions(), blockStatementNode); int trailingWS = 1 - trailingNL; Token openBrace = formatToken(blockStatementNode.openBraceToken(), trailingWS, trailingNL); preserveIndentation(preserveIndent); @@ -586,11 +577,9 @@ public BlockStatementNode transform(BlockStatementNode blockStatementNode) { NodeList statements = formatNodeList(blockStatementNode.statements(), 0, 1, trailingWS, trailingNL); unindent(); // end the indentation - int closingNewLine = - (options.getBlockFormattingOptions().elseBlockOnANewLine() && - blockStatementNode.parent().kind() == SyntaxKind.IF_ELSE_STATEMENT) ? 1 : - env.trailingNL; - Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, closingNewLine); + int closingNL = (options.getBlockFormattingOptions().elseBlockOnANewLine() && + blockStatementNode.parent().kind() == SyntaxKind.IF_ELSE_STATEMENT) ? 1 : env.trailingNL; + Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, closingNL); return blockStatementNode.modify() .withOpenBraceToken(openBrace) @@ -1169,7 +1158,7 @@ public ConstantDeclarationNode transform(ConstantDeclarationNode constantDeclara Token constKeyword = formatToken(constantDeclarationNode.constKeyword(), 1, 0); TypeDescriptorNode typeDescriptorNode = formatNode(constantDeclarationNode.typeDescriptor().orElse(null), 1, 0); int wSBeforeEqual = !options.alignConsecutiveDefinitions() ? 1 : - env.maxConstDefWidth - getConstDefLength(constantDeclarationNode) + 1; + env.maxConstDefWidth - getConstDefWidth(constantDeclarationNode) + 1; Token variableName = formatToken(constantDeclarationNode.variableName(), wSBeforeEqual, 0); Token equalsToken = formatToken(constantDeclarationNode.equalsToken(), 1, 0); Node initializer = formatNode(constantDeclarationNode.initializer(), 0, 0); @@ -2873,11 +2862,7 @@ public CollectClauseNode transform(CollectClauseNode collectClauseNode) { public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { int length = options.alignMultiLineQueries() ? env.currentIndentation : env.lineLength; if (length != 0) { - if (options.alignMultiLineQueries()) { - align(); - } else { - indent(); - } + alignOrIndent(options.alignMultiLineQueries()); } QueryConstructTypeNode queryConstructType = @@ -2894,11 +2879,7 @@ public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { OnConflictClauseNode onConflictClause = formatNode(queryExpressionNode.onConflictClause().orElse(null), env.trailingWS, env.trailingNL); if (length != 0) { - if (options.alignMultiLineQueries()) { - unalign(); - } else { - unindent(); - } + unalignOrUnindent(options.alignMultiLineQueries()); } return queryExpressionNode.modify() @@ -3940,7 +3921,7 @@ protected NodeList formatMemberDeclarations(NodeList memb if (options.alignConsecutiveDefinitions()) { env.maxConstDefWidth = members.stream() .filter(member -> member.kind() == SyntaxKind.CONST_DECLARATION) - .mapToInt(member -> getConstDefLength((ConstantDeclarationNode) member)) + .mapToInt(member -> getConstDefWidth((ConstantDeclarationNode) member)) .max() .orElse(1); } @@ -4184,16 +4165,9 @@ protected SeparatedNodeList formatSeparatedNodeList(Separate } Token oldSeparator = nodeList.getSeparator(index); - if (allowInAndMultiLine) { + if (allowInAndMultiLine && hasNonWSMinutiae(oldSeparator.trailingMinutiae())) { + separatorTrailingNL = separatorTrailingNL > 0 ? separatorTrailingNL : 1; separatorTrailingWS = 0; - separatorTrailingNL = 0; - if (hasNonWSMinutiae(oldSeparator.trailingMinutiae()) || - (options.getFunctionFormattingOptions().oneArgPerLine() && - oldNode.parent().kind() == SyntaxKind.FUNCTION_SIGNATURE)) { - separatorTrailingNL++; - } else { - separatorTrailingWS++; - } } Token newSeparator = formatToken(oldSeparator, separatorTrailingWS, separatorTrailingNL); newNodes[(2 * index) + 1] = newSeparator; @@ -4562,6 +4536,9 @@ private void indent(int step) { env.currentIndentation += (options.getTabSize() * step); } + /** + * Align the code with the previous line. + */ private void align() { env.preservedIndentation = env.currentIndentation; env.currentIndentation = env.lineLength; @@ -4588,10 +4565,45 @@ private void unindent(int step) { env.currentIndentation -= (options.getTabSize() * step); } + /** + * Undo the alignment with the previous line. + */ private void unalign() { env.currentIndentation = env.preservedIndentation; } + private void alignOrIndent(boolean shouldAlign) { + if (shouldAlign) { + align(); + } else { + indent(); + } + } + + private void alignOrIndent(boolean shouldAlign, int step) { + if (shouldAlign) { + align(); + } else { + indent(step); + } + } + + private void unalignOrUnindent(boolean shouldAlign) { + if (shouldAlign) { + unalign(); + } else { + unindent(); + } + } + + private void unalignOrUnindent(boolean shouldAlign, int step) { + if (shouldAlign) { + unalign(); + } else { + unindent(step); + } + } + /** * Set the indentation for the code to follow. * diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java index 8a17f7342ae6..c2941ff29b19 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java @@ -22,19 +22,19 @@ */ public class FunctionFormattingOptions { - private boolean paranAlign; - private boolean oneArgPerLine; + private final boolean paranAlign; + private final boolean oneArgPerLine; private FunctionFormattingOptions(boolean paranAlign, boolean oneArgPerLine) { this.paranAlign = paranAlign; this.oneArgPerLine = oneArgPerLine; } - public boolean paranAlign() { + public boolean getParanAlign() { return paranAlign; } - public boolean oneArgPerLine() { + public boolean getOneArgPerLine() { return oneArgPerLine; } From 53a8a3eeb95b464b6dcfa65a6a84b2e759db5599 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 2 Oct 2023 12:25:26 +0530 Subject: [PATCH 06/22] Add updated formatting options and updated names --- .../BallerinaTextDocumentService.java | 2 +- .../formatter/cli/FormatUtil.java | 2 +- .../formatter/cli/FormatCmdTest.java | 36 +- .../blocks/source/ifelse/Ballerina.toml | 2 - .../blocks/source/ifelseTemp/Ballerina.toml | 2 - .../blocks/source/short/Ballerina.toml | 2 - .../blocks/source/shortTemp/Ballerina.toml | 2 - .../brace/assert/project/main.bal | 19 + .../brace/source/project/Ballerina.toml | 2 + .../brace/source/project/Format.toml | 3 + .../brace/source/project/main.bal | 16 + .../brace/source/projectTemp/main.bal | 16 + .../functionCall/assert/chopDown/main.bal | 21 + .../functionCall/assert/noWrap/main.bal | 19 + .../functionCall/assert/wrap/main.bal | 22 ++ .../source/chopDown/Ballerina.toml | 2 + .../functionCall/source/chopDown/Format.toml | 7 + .../functionCall/source/chopDown/main.bal | 14 + .../functionCall/source/chopDownTemp/main.bal | 14 + .../functionCall/source/noWrap/Ballerina.toml | 2 + .../functionCall/source/noWrap/Format.toml | 6 + .../functionCall/source/noWrap/main.bal | 14 + .../functionCall/source/noWrapTemp/main.bal | 14 + .../functionCall/source/wrap/Ballerina.toml | 2 + .../functionCall/source/wrap/Format.toml | 8 + .../functionCall/source/wrap/main.bal | 14 + .../functionCall/source/wrapTemp/main.bal | 14 + .../assert/chopDown/main.bal | 13 + .../assert/noWrap}/main.bal | 3 +- .../functionDeclaration/assert/wrap/main.bal | 7 + .../source/chopDown/Ballerina.toml | 2 + .../source/chopDown/Format.toml | 6 + .../source/chopDown}/main.bal | 0 .../source/chopDownTemp}/main.bal | 0 .../source/noWrap/Ballerina.toml | 2 + .../source/noWrap/Format.toml | 5 + .../source/noWrap}/main.bal | 0 .../source/noWrapTemp}/main.bal | 0 .../source/wrap/Ballerina.toml | 2 + .../source/wrap/Format.toml | 8 + .../source/wrap}/main.bal | 0 .../source/wrapTemp}/main.bal | 0 .../functions/assert/oneArg/main.bal | 12 - .../assert/paranAlignOneArg/main.bal | 12 - .../functions/source/oneArg/Ballerina.toml | 6 - .../source/oneArgTemp/Ballerina.toml | 6 - .../source/paranAlign/Ballerina.toml | 6 - .../source/paranAlignOneArg/Ballerina.toml | 6 - .../paranAlignOneArgTemp/Ballerina.toml | 6 - .../source/paranAlignTemp/Ballerina.toml | 6 - .../general/assert/project/main.bal | 30 -- .../general/source/project/Ballerina.toml | 6 - .../general/source/project/main.bal | 28 -- .../general/source/projectTemp/Ballerina.toml | 6 - .../general/source/projectTemp/main.bal | 28 -- .../assert/ifelse/main.bal | 0 .../ifStatement/source/ifelse/Ballerina.toml | 2 + .../ifStatement/source/ifelse/Format.toml | 2 + .../source/ifelse/main.bal | 0 .../source/ifelseTemp/main.bal | 0 .../imports/source/project/Ballerina.toml | 5 +- .../Ballerina.toml => project/Format.toml} | 2 +- .../indent/assert/project/main.bal | 4 + .../indent/source/project/Ballerina.toml | 2 + .../indent/source/project/Format.toml | 3 + .../indent/source/project/main.bal | 4 + .../indent/source/projectTemp/main.bal | 4 + .../query/assert/project/main.bal | 11 + .../query/source/project/Ballerina.toml | 2 + .../query/source/project/Format.toml | 2 + .../query/source/project/main.bal | 10 + .../query/source/projectTemp/main.bal | 10 + .../spacing/assert/project/main.bal | 16 + .../spacing/source/project/Ballerina.toml | 2 + .../spacing/source/project/Format.toml | 3 + .../spacing/source/project/main.bal | 16 + .../spacing/source/projectTemp/main.bal | 16 + .../assert/project}/main.bal | 2 + .../wrapping/source/project/Ballerina.toml | 2 + .../wrapping/source/project/Format.toml | 5 + .../source/project}/main.bal | 12 +- .../source/projectTemp}/main.bal | 12 +- .../modules/formatter-core/build.gradle | 1 + .../src/main/java/module-info.java | 2 + .../core/BlockFormattingOptions.java | 111 ------ .../formatter/core/Formatter.java | 1 + .../formatter/core/FormatterUtils.java | 84 +++- .../formatter/core/FormattingOptions.java | 372 ------------------ .../core/FormattingTreeModifier.java | 145 ++++--- .../core/FunctionFormattingOptions.java | 67 ---- .../core/options/BraceFormattingOptions.java | 85 ++++ .../formatter/core/options/BraceStyle.java | 16 + .../{ => options}/ForceFormattingOptions.java | 4 +- .../core/options/FormattingOptions.java | 204 ++++++++++ .../FunctionCallFormattingOptions.java | 124 ++++++ .../FunctionDeclFormattingOptions.java | 117 ++++++ .../options/IfStatementFormattingOptions.java | 68 ++++ .../ImportFormattingOptions.java | 10 +- .../core/options/IndentFormattingOptions.java | 92 +++++ .../core/options/QueryFormattingOptions.java | 68 ++++ .../options/SpacingFormattingOptions.java | 96 +++++ .../options/WrappingFormattingOptions.java | 144 +++++++ .../core/options/WrappingMethod.java | 17 + .../formatter/core/FormatterTest.java | 6 +- .../declarations/ImportDeclarationsTest.java | 4 +- .../jsonmapper/JsonToRecordMapper.java | 4 +- .../converters/JsonToRecordConverter.java | 4 +- .../XMLToRecordConverter.java | 4 +- 108 files changed, 1659 insertions(+), 823 deletions(-) delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/assert/paranAlign => functionDeclaration/assert/noWrap}/main.bal (64%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/oneArg => functionDeclaration/source/chopDown}/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/oneArgTemp => functionDeclaration/source/chopDownTemp}/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/paranAlign => functionDeclaration/source/noWrap}/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/paranAlignOneArg => functionDeclaration/source/noWrapTemp}/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/paranAlignOneArgTemp => functionDeclaration/source/wrap}/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functions/source/paranAlignTemp => functionDeclaration/source/wrapTemp}/main.bal (100%) delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks => ifStatement}/assert/ifelse/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks => ifStatement}/source/ifelse/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks => ifStatement}/source/ifelseTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/{projectTemp/Ballerina.toml => project/Format.toml} (70%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks/assert/short => wrapping/assert/project}/main.bal (90%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks/source/short => wrapping/source/project}/main.bal (60%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{blocks/source/shortTemp => wrapping/source/projectTemp}/main.bal (60%) delete mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java delete mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java delete mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java rename misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/{ => options}/ForceFormattingOptions.java (94%) create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java rename misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/{ => options}/ImportFormattingOptions.java (94%) create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index ea4676ae38f1..85cfd7b2dba8 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -24,7 +24,7 @@ import io.ballerina.tools.text.LineRange; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; -import org.ballerinalang.formatter.core.FormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; import org.ballerinalang.langserver.codelenses.CodeLensUtil; import org.ballerinalang.langserver.codelenses.LSCodeLensesProviderHolder; import org.ballerinalang.langserver.common.utils.PathUtil; diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index c490432660ba..ae9ffa7a1d33 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -27,7 +27,7 @@ import io.ballerina.projects.directory.SingleFileProject; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; -import org.ballerinalang.formatter.core.FormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; import java.io.File; import java.io.FileOutputStream; diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index 754194dac817..d1165e0929ac 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -105,20 +105,36 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< @DataProvider(name = "provideConfigurationProjects") private Object[][] provideConfigurationProjects() { return new Object[][]{ - {"general", List.of( - RES_DIR.resolve("configurations/general/source/project") + {"brace", List.of( + RES_DIR.resolve("configurations/brace/source/project") )}, - {"function", List.of( - RES_DIR.resolve("configurations/functions/source/oneArg"), - RES_DIR.resolve("configurations/functions/source/paranAlign"), - RES_DIR.resolve("configurations/functions/source/paranAlignOneArg") + {"functionCall", List.of( + RES_DIR.resolve("configurations/functionCall/source/chopDown"), + RES_DIR.resolve("configurations/functionCall/source/noWrap"), + RES_DIR.resolve("configurations/functionCall/source/wrap") )}, - {"blocks", List.of( - RES_DIR.resolve("configurations/blocks/source/ifelse"), - RES_DIR.resolve("configurations/blocks/source/short") + {"functionDeclaration", List.of( + RES_DIR.resolve("configurations/functionDeclaration/source/chopDown"), + RES_DIR.resolve("configurations/functionDeclaration/source/noWrap"), + RES_DIR.resolve("configurations/functionDeclaration/source/wrap") )}, - {"import", List.of( + {"ifStatement", List.of( + RES_DIR.resolve("configurations/ifStatement/source/ifelse") + )}, + {"imports", List.of( RES_DIR.resolve("configurations/imports/source/project") + )}, + {"indent", List.of( + RES_DIR.resolve("configurations/indent/source/project") + )}, + {"query", List.of( + RES_DIR.resolve("configurations/query/source/project") + )}, + {"spacing", List.of( + RES_DIR.resolve("configurations/spacing/source/project") + )}, + {"wrapping", List.of( + RES_DIR.resolve("configurations/wrapping/source/project") )} }; } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml deleted file mode 100644 index 46da4d2ea121..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format.block] -elseBlockOnANewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml deleted file mode 100644 index 46da4d2ea121..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format.block] -elseBlockOnANewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml deleted file mode 100644 index e564c5b8e750..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format.block] -allowShortBlocksOnASingleLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml deleted file mode 100644 index e564c5b8e750..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format.block] -allowShortBlocksOnASingleLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal new file mode 100644 index 000000000000..3cb9884d74d9 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal @@ -0,0 +1,19 @@ +import ballerina/io; + +class Student +{ + final string name; + int age; + + function init(string name, int age) + { + self.name = name; + self.age = age; + } +} + +public function main() +{ + Student student = new Student("Alice", 52); + io:println(student); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml new file mode 100644 index 000000000000..068140f77031 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/brace/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml new file mode 100644 index 000000000000..2158b8c5afa9 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml @@ -0,0 +1,3 @@ +[braces] +classBraceStyle = "NEWLINE" +methodBraceStyle = "NEWLINE" \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal new file mode 100644 index 000000000000..7fa7b277884f --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; + +class Student { + final string name; + int age; + + function init(string name, int age) { + self.name = name; + self.age = age; + } +} + +public function main() { + Student student = new Student("Alice", 52); + io:println(student); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal new file mode 100644 index 000000000000..7fa7b277884f --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; + +class Student { + final string name; + int age; + + function init(string name, int age) { + self.name = name; + self.age = age; + } +} + +public function main() { + Student student = new Student("Alice", 52); + io:println(student); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal new file mode 100644 index 000000000000..76670124ea95 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal @@ -0,0 +1,21 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, + string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail( + "sender@example.com", + "recipient@example.com", + "This is a test email from Ballerina.", + "Hello from Ballerina"); + if (isEmailSent) { + io:println( + "Email sent successfully!"); + } else { + io:println( + "Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal new file mode 100644 index 000000000000..90bf4f431fc2 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal @@ -0,0 +1,19 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, + string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = + sendEmail( + "sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println( + "Email sent successfully!"); + } else { + io:println( + "Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal new file mode 100644 index 000000000000..ba25691b3c98 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal @@ -0,0 +1,22 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, + string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail( + "sender@example.com", "recipient@example.com", + "This is a test email from Ballerina.", "Hello from Ballerina" + ); + if (isEmailSent) { + io:println( + "Email sent successfully!" + ); + } else { + io:println( + "Email sending failed." + ); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml new file mode 100644 index 000000000000..15a10f1fa75a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionCall/source/chopDown/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml new file mode 100644 index 000000000000..b4e91caf722c --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml @@ -0,0 +1,7 @@ +[methodCall] +parametersWrap = "CHOPDOWN" +alignMultilineParameters = true +newLineAfterLeftParen = true + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml new file mode 100644 index 000000000000..2ec06e5d391e --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionCall/source/noWrap/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml new file mode 100644 index 000000000000..4443d793f996 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml @@ -0,0 +1,6 @@ +[methodCall] +parametersWrap = "NOWRAP" +newLineAfterLeftParen = true + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml new file mode 100644 index 000000000000..3238dd1c3aac --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionCall/source/wrap/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml new file mode 100644 index 000000000000..062102291729 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml @@ -0,0 +1,8 @@ +[methodCall] +parametersWrap = "WRAP" +alignMultilineParameters = true +newLineAfterLeftParen = true +rightParenOnNewLine = true + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal new file mode 100644 index 000000000000..c95ace1b8a29 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal @@ -0,0 +1,13 @@ +function add(int first, + int second, + int third, + int fourth, + int fifth, + int sixth, + int seventh, + int eighth, + int ninth, + int tenth) returns int { + return first + second + third + fourth + fifth + sixth + seventh + eighth + + ninth + tenth; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/noWrap/main.bal similarity index 64% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/noWrap/main.bal index 8cf2924eb59a..c177f3c7a648 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlign/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/noWrap/main.bal @@ -1,5 +1,4 @@ -function add(int first, int second, int third, int fourth, int fifth, int sixth, - int seventh, int eighth, int ninth, int tenth) returns int { +function add(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth, int tenth) returns int { return first + second + third + fourth + fifth + sixth + seventh + eighth + ninth + tenth; } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal new file mode 100644 index 000000000000..dc1ac45df310 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal @@ -0,0 +1,7 @@ +function add( + int first, int second, int third, int fourth, int fifth, int sixth, + int seventh, int eighth, int ninth, int tenth +) returns int { + return first + second + third + fourth + fifth + sixth + seventh + eighth + + ninth + tenth; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml new file mode 100644 index 000000000000..e5df81b20e7b --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml new file mode 100644 index 000000000000..e35dc616dafb --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml @@ -0,0 +1,6 @@ +[methodDeclaration] +parametersWrap = "CHOPDOWN" +alignMultilineParameters = true + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDownTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDownTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml new file mode 100644 index 000000000000..f453f3503efb --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml new file mode 100644 index 000000000000..318ca73b7bfd --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml @@ -0,0 +1,5 @@ +[methodDeclaration] +parametersWrap = "NOWRAP" + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml new file mode 100644 index 000000000000..2f28a15c1484 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml new file mode 100644 index 000000000000..52f7b162002b --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml @@ -0,0 +1,8 @@ +[methodDeclaration] +parametersWrap = "WRAP" +alignMultilineParameters = true +newLineAfterLeftParen = true +rightParenOnNewLine = true + +[wrapping] +maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal deleted file mode 100644 index 4ed9faab0f06..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/oneArg/main.bal +++ /dev/null @@ -1,12 +0,0 @@ -function add(int first, - int second, - int third, - int fourth, - int fifth, - int sixth, - int seventh, - int eighth, - int ninth, - int tenth) returns int { - return first + second + third + fourth + fifth + sixth + seventh + eighth + ninth + tenth; -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal deleted file mode 100644 index 645895d5a3b4..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/assert/paranAlignOneArg/main.bal +++ /dev/null @@ -1,12 +0,0 @@ -function add(int first, - int second, - int third, - int fourth, - int fifth, - int sixth, - int seventh, - int eighth, - int ninth, - int tenth) returns int { - return first + second + third + fourth + fifth + sixth + seventh + eighth + ninth + tenth; -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml deleted file mode 100644 index 2d973bf34d28..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArg/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 120 - -[format.function] -oneArgPerLine = true -paranAlign = false diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml deleted file mode 100644 index 2d973bf34d28..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/oneArgTemp/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 120 - -[format.function] -oneArgPerLine = true -paranAlign = false diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml deleted file mode 100644 index 3db3e0dffd45..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlign/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 80 - -[format.function] -oneArgPerLine = false -paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml deleted file mode 100644 index fc8043bfb8d5..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArg/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 120 - -[format.function] -oneArgPerLine = true -paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml deleted file mode 100644 index fc8043bfb8d5..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignOneArgTemp/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 120 - -[format.function] -oneArgPerLine = true -paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml deleted file mode 100644 index 3db3e0dffd45..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functions/source/paranAlignTemp/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -columnLimit = 80 - -[format.function] -oneArgPerLine = false -paranAlign = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal deleted file mode 100644 index d471072bc4e6..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/assert/project/main.bal +++ /dev/null @@ -1,30 +0,0 @@ -const int MAX_STUDENTS = 100; -const string WELCOME_MESSAGE = "Welcome"; -const int MAX_AGE = 20; - -type Student record { - string name; - int age; -}; - -function registerStudent(Student[] students, string name, int age, - int numStudents) returns boolean { - if numStudents < MAX_STUDENTS { - students.push({ name, age }); - return true; - } else { - return false; - } -} - -function queryTest() { - int[] nums = [1, 2, 3, 4]; - int[] numsTimes10 = from var i in nums - select i * 10; - int[] evenNums = from int i in nums - where i % 2 == 0 - select i; - int[] numsReversed = from int i in nums - order by i descending - select i; -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml deleted file mode 100644 index 5228a18778ab..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -tabWidth = 2 -recordBraceSpacing = true -columnLimit = 80 -alignMultiLineQueries = true -alignConsecutiveDefinitions = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal deleted file mode 100644 index c7d45c69e9ae..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/project/main.bal +++ /dev/null @@ -1,28 +0,0 @@ -const int MAX_STUDENTS = 100; -const string WELCOME_MESSAGE = "Welcome"; -const int MAX_AGE = 20; - -type Student record { - string name; - int age; -}; - -function registerStudent(Student[] students, string name, int age, int numStudents) returns boolean { - if numStudents < MAX_STUDENTS { - students.push({name, age}); - return true; - } else { - return false; - } -} - -function queryTest() { - int[] nums = [1 , 2,3, 4]; - int[] numsTimes10 = from var i in nums select i * 10; - int[] evenNums = from int i in nums - where i % 2 == 0 - select i; - int[] numsReversed = from int i in nums - order by i descending - select i; -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml deleted file mode 100644 index 5228a18778ab..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/Ballerina.toml +++ /dev/null @@ -1,6 +0,0 @@ -[format] -tabWidth = 2 -recordBraceSpacing = true -columnLimit = 80 -alignMultiLineQueries = true -alignConsecutiveDefinitions = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal deleted file mode 100644 index c7d45c69e9ae..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/general/source/projectTemp/main.bal +++ /dev/null @@ -1,28 +0,0 @@ -const int MAX_STUDENTS = 100; -const string WELCOME_MESSAGE = "Welcome"; -const int MAX_AGE = 20; - -type Student record { - string name; - int age; -}; - -function registerStudent(Student[] students, string name, int age, int numStudents) returns boolean { - if numStudents < MAX_STUDENTS { - students.push({name, age}); - return true; - } else { - return false; - } -} - -function queryTest() { - int[] nums = [1 , 2,3, 4]; - int[] numsTimes10 = from var i in nums select i * 10; - int[] evenNums = from int i in nums - where i % 2 == 0 - select i; - int[] numsReversed = from int i in nums - order by i descending - select i; -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/assert/ifelse/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/ifelse/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/assert/ifelse/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml new file mode 100644 index 000000000000..52240e47f5d7 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/ifStatement/source/ifelse/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml new file mode 100644 index 000000000000..3b51a1f181c4 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml @@ -0,0 +1,2 @@ +[ifStatement] +elseOnNewLine = true \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelse/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelseTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/ifelseTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelseTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml index b3f9282ffb26..98a99c665ffa 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml @@ -1,3 +1,2 @@ -[format.import] -groupImports = true -sortImports = true +[format] +configPath = "src/test/resources/configurations/imports/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Format.toml similarity index 70% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Format.toml index b3f9282ffb26..0c18730a61a2 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Format.toml @@ -1,3 +1,3 @@ -[format.import] +[import] groupImports = true sortImports = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal new file mode 100644 index 000000000000..7e4fe3435a00 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal @@ -0,0 +1,4 @@ +function foo(int veryDescriptiveArgumentNumberOne, int veryDescriptiveArgumentTwo, + int veryDescriptiveArgumentThree, int veryDescriptiveArgumentFour) returns int { + return veryDescriptiveArgumentNumberOne + veryDescriptiveArgumentTwo + veryDescriptiveArgumentThree - veryDescriptiveArgumentFour; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml new file mode 100644 index 000000000000..267ba8abf527 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/indent/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml new file mode 100644 index 000000000000..1157c440c32b --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml @@ -0,0 +1,3 @@ +[indent] +indentSize = 2 +continuationIndentSize = 2 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal new file mode 100644 index 000000000000..787752735cb5 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal @@ -0,0 +1,4 @@ +function foo(int veryDescriptiveArgumentNumberOne, int veryDescriptiveArgumentTwo, + int veryDescriptiveArgumentThree, int veryDescriptiveArgumentFour) returns int { + return veryDescriptiveArgumentNumberOne + veryDescriptiveArgumentTwo + veryDescriptiveArgumentThree - veryDescriptiveArgumentFour; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal new file mode 100644 index 000000000000..787752735cb5 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal @@ -0,0 +1,4 @@ +function foo(int veryDescriptiveArgumentNumberOne, int veryDescriptiveArgumentTwo, + int veryDescriptiveArgumentThree, int veryDescriptiveArgumentFour) returns int { + return veryDescriptiveArgumentNumberOne + veryDescriptiveArgumentTwo + veryDescriptiveArgumentThree - veryDescriptiveArgumentFour; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal new file mode 100644 index 000000000000..db9ab7182b04 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal @@ -0,0 +1,11 @@ +function queryTest() { + int[] nums = [1, 2, 3, 4]; + int[] numsTimes10 = from var i in nums + select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml new file mode 100644 index 000000000000..62fe4497a106 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/query/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml new file mode 100644 index 000000000000..5dcf217e304a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml @@ -0,0 +1,2 @@ +[query] +alignMultiLineQueries = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal new file mode 100644 index 000000000000..b7a1af09fcd7 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal @@ -0,0 +1,10 @@ +function queryTest() { + int[] nums = [1 , 2,3, 4]; + int[] numsTimes10 = from var i in nums select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal new file mode 100644 index 000000000000..b7a1af09fcd7 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal @@ -0,0 +1,10 @@ +function queryTest() { + int[] nums = [1 , 2,3, 4]; + int[] numsTimes10 = from var i in nums select i * 10; + int[] evenNums = from int i in nums + where i % 2 == 0 + select i; + int[] numsReversed = from int i in nums + order by i descending + select i; +} \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal new file mode 100644 index 000000000000..3cf689230b67 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; + +type Student record {| + string name; + int age; +|}; + +public function main(string... args) { + decimal d = 10.0; + float|decimal fd = d; + float b = fd; + io:println(b); + + Student student = { name: "Harry", age: 12 }; + io:println(student.name); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml new file mode 100644 index 000000000000..fa2196feb3ce --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/spacing/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml new file mode 100644 index 000000000000..81f8fc8ad7b4 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml @@ -0,0 +1,3 @@ +[spacing] +afterTypeCast = true +aroundRecordBraces = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal new file mode 100644 index 000000000000..6de9063e50cc --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; + +type Student record {| + string name; + int age; +|}; + +public function main(string... args) { + decimal d = 10.0; + float|decimal fd = d; + float b = fd; + io:println(b); + + Student student = {name: "Harry", age: 12}; + io:println(student.name); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal new file mode 100644 index 000000000000..6de9063e50cc --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal @@ -0,0 +1,16 @@ +import ballerina/io; + +type Student record {| + string name; + int age; +|}; + +public function main(string... args) { + decimal d = 10.0; + float|decimal fd = d; + float b = fd; + io:println(b); + + Student student = {name: "Harry", age: 12}; + io:println(student.name); +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/assert/project/main.bal similarity index 90% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/assert/project/main.bal index 6a02e7972421..84af31689add 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/assert/short/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/assert/project/main.bal @@ -26,3 +26,5 @@ function printFalse() { io:println(0); } } + +function hello() returns string { return "hello"; } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml new file mode 100644 index 000000000000..54925bd97844 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/wrapping/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml new file mode 100644 index 000000000000..72e2b5bb4744 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml @@ -0,0 +1,5 @@ +[wrapping] +maxLineLength = 80 +keepLineBreaks = true +simpleBlocksInOneLine = true +simpleMethodsInOneLine = true \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/main.bal similarity index 60% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/main.bal index ebc7abe07844..fd77ddc7e56e 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/short/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/main.bal @@ -2,18 +2,18 @@ import ballerina/io; function loop(int times) { int count = 1; - while (count <= times) {count+= 1;} + while (count <= times) { count += 1;} } function getSign(int number) returns string { - if number <= 0 { return "+"; } - else { return "-"; } + if number <= 0 {return "+";} + else {return "-";} } function btoi(boolean? b) returns int { match b { - true => { return 1; } - false => { return 0; } + true => {return 1;} + false => {return 0;} } return 0; } @@ -26,3 +26,5 @@ function printFalse() { io:println(0); } } + +function hello() returns string {return "hello";} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/projectTemp/main.bal similarity index 60% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/projectTemp/main.bal index ebc7abe07844..fd77ddc7e56e 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/blocks/source/shortTemp/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/projectTemp/main.bal @@ -2,18 +2,18 @@ import ballerina/io; function loop(int times) { int count = 1; - while (count <= times) {count+= 1;} + while (count <= times) { count += 1;} } function getSign(int number) returns string { - if number <= 0 { return "+"; } - else { return "-"; } + if number <= 0 {return "+";} + else {return "-";} } function btoi(boolean? b) returns int { match b { - true => { return 1; } - false => { return 0; } + true => {return 1;} + false => {return 0;} } return 0; } @@ -26,3 +26,5 @@ function printFalse() { io:println(0); } } + +function hello() returns string {return "hello";} diff --git a/misc/formatter/modules/formatter-core/build.gradle b/misc/formatter/modules/formatter-core/build.gradle index bf1853563fb5..a5e02e12782a 100755 --- a/misc/formatter/modules/formatter-core/build.gradle +++ b/misc/formatter/modules/formatter-core/build.gradle @@ -28,6 +28,7 @@ dependencies { implementation project(':ballerina-parser') implementation project(':ballerina-lang') implementation "org.apache.commons:commons-lang3:${project.apacheCommonsLang3Version}" + implementation project(path: ':toml-parser') testImplementation 'com.google.code.gson:gson' testImplementation 'org.testng:testng' diff --git a/misc/formatter/modules/formatter-core/src/main/java/module-info.java b/misc/formatter/modules/formatter-core/src/main/java/module-info.java index aeb3b390c559..e5138a285491 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/module-info.java +++ b/misc/formatter/modules/formatter-core/src/main/java/module-info.java @@ -4,6 +4,8 @@ requires io.ballerina.tools.api; requires org.apache.commons.lang3; requires org.slf4j; + requires io.ballerina.toml; exports org.ballerinalang.formatter.core; + exports org.ballerinalang.formatter.core.options; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java deleted file mode 100644 index dd4944b57e9a..000000000000 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/BlockFormattingOptions.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ballerinalang.formatter.core; - -/** - * A model for formatting of functions by the API user, that could be passed onto the formatter. - * - * @since 2201.8.0 - */ -public class BlockFormattingOptions { - - private final boolean allowShortBlocksOnASingleLine; - private final boolean allowShortMatchLabelsOnASingleLine; - private final boolean allowShortIfStatementsOnASingleLine; - private final boolean allowShortLoopsOnASingleLine; - private final boolean elseBlockOnANewLine; - - public BlockFormattingOptions(boolean allowShortBlocksOnASingleLine, boolean allowShortMatchLabelsOnASingleLine, - boolean allowShortIfStatementsOnASingleLine, boolean allowShortLoopsOnASingleLine, - boolean elseBlockOnANewLine) { - this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; - this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; - this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; - this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; - this.elseBlockOnANewLine = elseBlockOnANewLine; - } - - public boolean allowShortBlocksOnASingleLine() { - return allowShortBlocksOnASingleLine; - } - - public boolean allowShortMatchLabelsOnASingleLine() { - return allowShortMatchLabelsOnASingleLine; - } - - public boolean allowShortIfStatementsOnASingleLine() { - return allowShortIfStatementsOnASingleLine; - } - - public boolean allowShortLoopsOnASingleLine() { - return allowShortLoopsOnASingleLine; - } - - public boolean elseBlockOnANewLine() { - return elseBlockOnANewLine; - } - - public static BlockFormattingOptions.BlockFormattingOptionsBuilder builder() { - return new BlockFormattingOptions.BlockFormattingOptionsBuilder(); - } - - /** - * A builder for the {@code BlockFormattingOptions}. - */ - public static class BlockFormattingOptionsBuilder { - - private boolean allowShortBlocksOnASingleLine = false; - private boolean allowShortMatchLabelsOnASingleLine = false; - private boolean allowShortIfStatementsOnASingleLine = false; - private boolean allowShortLoopsOnASingleLine = false; - private boolean elseBlockOnANewLine = false; - - public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortBlocksOnASingleLine( - boolean allowShortBlocksOnASingleLine) { - this.allowShortBlocksOnASingleLine = allowShortBlocksOnASingleLine; - return this; - } - - public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortMatchLabelsOnASingleLine( - boolean allowShortMatchLabelsOnASingleLine) { - this.allowShortMatchLabelsOnASingleLine = allowShortMatchLabelsOnASingleLine; - return this; - } - - public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortIfStatementsOnASingleLine( - boolean allowShortIfStatementsOnASingleLine) { - this.allowShortIfStatementsOnASingleLine = allowShortIfStatementsOnASingleLine; - return this; - } - - public BlockFormattingOptions.BlockFormattingOptionsBuilder setAllowShortLoopsOnASingleLine( - boolean allowShortLoopsOnASingleLine) { - this.allowShortLoopsOnASingleLine = allowShortLoopsOnASingleLine; - return this; - } - - public BlockFormattingOptions.BlockFormattingOptionsBuilder setElseBlockOnANewLine( - boolean elseBlockOnANewLine) { - this.elseBlockOnANewLine = elseBlockOnANewLine; - return this; - } - - public BlockFormattingOptions build() { - return new BlockFormattingOptions(allowShortBlocksOnASingleLine, allowShortMatchLabelsOnASingleLine, - allowShortIfStatementsOnASingleLine, allowShortLoopsOnASingleLine, elseBlockOnANewLine); - } - } -} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java index 95315bff590d..11bc29a40e50 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/Formatter.java @@ -53,6 +53,7 @@ import io.ballerina.tools.text.LineRange; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; +import org.ballerinalang.formatter.core.options.FormattingOptions; /** * Class that exposes the formatting APIs. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 336b48f55b32..63e9fb65cf08 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -15,7 +15,6 @@ */ package org.ballerinalang.formatter.core; -import io.ballerina.compiler.syntax.tree.BlockStatementNode; import io.ballerina.compiler.syntax.tree.ConstantDeclarationNode; import io.ballerina.compiler.syntax.tree.ImportDeclarationNode; import io.ballerina.compiler.syntax.tree.ImportOrgNameNode; @@ -25,16 +24,30 @@ import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.projects.TomlDocument; +import io.ballerina.toml.semantic.ast.TomlTableNode; import io.ballerina.tools.text.LineRange; import org.apache.commons.lang3.builder.CompareToBuilder; +import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; /** * Class that contains the util functions used by the formatting tree modifier. */ -class FormatterUtils { +public class FormatterUtils { private FormatterUtils() { @@ -42,6 +55,62 @@ private FormatterUtils() { static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); + public static Map getFormattingConfigurations(String path) throws FormatterException { + String content; + if (isLocalFile(path)) { + try { + content = Files.readString(Path.of(path), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new FormatterException("Failed to retrieve local formatting configuration file"); + } + } else { + content = readRemoteFormatFile(path); + } + + TomlDocument document = TomlDocument.from(path, content); + TomlTableNode tomlAstNode = document.toml().rootNode(); + + Map formatConfigs = new HashMap<>(); + if (!tomlAstNode.entries().isEmpty()) { + Map tomlMap = document.toml().toMap(); + for (Map.Entry entry : tomlMap.entrySet()) { + formatConfigs.put(entry.getKey(), entry.getValue()); + } + } + return formatConfigs; + } + + public static boolean isLocalFile(String path) { + return new File(path).exists(); + } + + static String readRemoteFormatFile(String fileUrl) throws FormatterException { + StringBuilder fileContent = new StringBuilder(); + + try { + URL url = new URL(fileUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + int responseCode = connection.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + fileContent.append(line).append(NEWLINE_SYMBOL); + } + } + } else { + throw new FormatterException("Failed to retrieve remote file. HTTP response code: " + responseCode); + } + connection.disconnect(); + } catch (IOException e) { + throw new FormatterException("Failed to retrieve remote formatting configuration file"); + } + return fileContent.toString(); + } + static boolean isInlineRange(Node node, LineRange lineRange) { if (lineRange == null) { return true; @@ -165,19 +234,16 @@ private static boolean hasEmptyLineAtEnd(MinutiaeList minutiaeList) { minutiaeList.get(size - 2).kind() == SyntaxKind.END_OF_LINE_MINUTIAE; } - static int openBraceTrailingNLs(BlockFormattingOptions options, BlockStatementNode node) { + static int openBraceTrailingNLs(WrappingFormattingOptions options, Node node) { if (node.lineRange().startLine().line() != node.lineRange().endLine().line()) { return 1; } - if (options.allowShortBlocksOnASingleLine()) { + SyntaxKind parentKind = node.parent().kind(); + if (options.isSimpleBlocksInOneLine() && parentKind != SyntaxKind.METHOD_DECLARATION) { return 0; } - - SyntaxKind parentKind = node.parent().kind(); - return (options.allowShortIfStatementsOnASingleLine() && parentKind == SyntaxKind.IF_ELSE_STATEMENT) || - (options.allowShortLoopsOnASingleLine() && parentKind == SyntaxKind.WHILE_STATEMENT) || - (options.allowShortMatchLabelsOnASingleLine() && parentKind == SyntaxKind.MATCH_CLAUSE) ? 0 : 1; + return (options.isSimpleMethodsInOneLine() && parentKind == SyntaxKind.METHOD_DECLARATION) ? 0 : 1; } static int getConstDefWidth(ConstantDeclarationNode node) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java deleted file mode 100644 index 1a4f65c75ae7..000000000000 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingOptions.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2020, WSO2 Inc. (http://wso2.com) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ballerinalang.formatter.core; - -import java.util.Map; - -/** - * A model for formatting options that could be passed onto the formatter. - */ -public class FormattingOptions { - - // Size of a tab in spaces. - private int tabSize; - - // Prefer spaces over tabs. - private String wsCharacter; - - private int columnLimit; - - private boolean lineWrapping; - - private int continuationIndent; - - private boolean paranAlignedIndentation; - - private boolean oneArgPerLine; - - private boolean recordBraceSpacing; - - private boolean alignConsecutiveDefinitions; - - private boolean alignMultiLineQueries; - - private ForceFormattingOptions forceFormattingOptions; - - private ImportFormattingOptions importFormattingOptions; - - private FunctionFormattingOptions functionFormattingOptions; - - private BlockFormattingOptions blockFormattingOptions; - - private FormattingOptions(int tabSize, String wsCharacter, int columnLimit, boolean lineWrapping, - int continuationIndent, - ForceFormattingOptions forceFormattingOptions, - boolean recordBraceSpacing, - boolean alignConsecutiveDefinitions, - boolean alignMultiLineQueries, - ImportFormattingOptions importFormattingOptions, - FunctionFormattingOptions functionFormattingOptions, - BlockFormattingOptions blockFormattingOptions) { - this.tabSize = tabSize; - this.wsCharacter = wsCharacter; - this.columnLimit = columnLimit; - this.lineWrapping = lineWrapping; - this.continuationIndent = continuationIndent; - this.forceFormattingOptions = forceFormattingOptions; - this.recordBraceSpacing = recordBraceSpacing; - this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; - this.alignMultiLineQueries = alignMultiLineQueries; - this.importFormattingOptions = importFormattingOptions; - this.functionFormattingOptions = functionFormattingOptions; - this.blockFormattingOptions = blockFormattingOptions; - - } - - /** - * @deprecated - * This constructor is no longer acceptable to instantiate Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public FormattingOptions(int tabSize, String wsCharacter) { - this.tabSize = tabSize; - this.wsCharacter = wsCharacter; - this.columnLimit = 120; - this.lineWrapping = false; - } - - /** - * @deprecated - * This constructor is no longer acceptable to instantiate Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public FormattingOptions(boolean lineWrapping, int columnLimit) { - this.tabSize = 4; - this.wsCharacter = " "; - this.columnLimit = columnLimit; - this.lineWrapping = lineWrapping; - } - - /** - * @deprecated - * This constructor is no longer acceptable to instantiate Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public FormattingOptions(int tabSize, String wsCharacter, boolean lineWrapping, int columnLimit) { - this.tabSize = tabSize; - this.wsCharacter = wsCharacter; - this.columnLimit = columnLimit; - this.lineWrapping = lineWrapping; - } - - public int getTabSize() { - return tabSize; - } - - /** - * @deprecated - * This setter method is no longer acceptable to set Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public void setTabSize(int tabSize) { - this.tabSize = tabSize; - } - - public String getWSCharacter() { - return wsCharacter; - } - - /** - * @deprecated - * This setter method is no longer acceptable to set Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public void setWSCharacter(String wsCharacter) { - this.wsCharacter = wsCharacter; - } - - public int getColumnLimit() { - return this.columnLimit; - } - - /** - * @deprecated - * This setter method is no longer acceptable to set Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public void setColumnLimit(int columnLimit) { - this.columnLimit = columnLimit; - } - - public boolean getLineWrapping() { - return lineWrapping; - } - - /** - * @deprecated - * This setter method is no longer acceptable to set Formatting Options. - *

Use {@link FormattingOptions#builder()} instead. - */ - @Deprecated - public void setLineWrapping(boolean lineWrapping) { - this.lineWrapping = lineWrapping; - } - - public int getContinuationIndent() { - return continuationIndent; - } - - public ForceFormattingOptions getForceFormattingOptions() { - return forceFormattingOptions; - } - - public ImportFormattingOptions getImportFormattingOptions() { - return importFormattingOptions; - } - - public FunctionFormattingOptions getFunctionFormattingOptions() { - return functionFormattingOptions; - } - - public BlockFormattingOptions getBlockFormattingOptions() { - return blockFormattingOptions; - } - - public boolean isRecordBraceSpacing() { - return recordBraceSpacing; - } - - public boolean alignConsecutiveDefinitions() { - return alignConsecutiveDefinitions; - } - - public boolean alignMultiLineQueries() { - return alignMultiLineQueries; - } - - public static FormattingOptionsBuilder builder() { - return new FormattingOptionsBuilder(); - } - - /** - * A builder for the {@code FormattingOptions}. - * - * @since 2201.3.0 - */ - public static class FormattingOptionsBuilder { - private int tabSize = 4; - private String wsCharacter = " "; - private int columnLimit = 120; - private boolean lineWrapping = false; - private int continuationIndent = 2; - private boolean paranAlignedIndentation = false; - private boolean oneArgPerLine = false; - private boolean recordBraceSpacing = false; - private boolean alignConsecutiveDefinitions = false; - private boolean alignMultiLineQueries = false; - private ForceFormattingOptions forceFormattingOptions = ForceFormattingOptions.builder().build(); - private ImportFormattingOptions.ImportFormattingOptionsBuilder importBuilder = - ImportFormattingOptions.builder(); - private FunctionFormattingOptions.FunctionFormattingOptionsBuilder functionBuilder = - FunctionFormattingOptions.builder(); - private BlockFormattingOptions.BlockFormattingOptionsBuilder blockBuilder = - BlockFormattingOptions.builder(); - private ImportFormattingOptions importFormattingOptions = importBuilder.build(); - - public FormattingOptions.FormattingOptionsBuilder setTabSize(int tabSize) { - this.tabSize = tabSize; - return this; - } - - public FormattingOptions.FormattingOptionsBuilder setWSCharacter(String wsCharacter) { - this.wsCharacter = wsCharacter; - return this; - } - - public FormattingOptions.FormattingOptionsBuilder setColumnLimit(int columnLimit) { - this.columnLimit = columnLimit; - return this; - } - - public FormattingOptions.FormattingOptionsBuilder setLineWrapping(boolean lineWrapping) { - this.lineWrapping = lineWrapping; - return this; - } - - public FormattingOptions.FormattingOptionsBuilder setForceFormattingOptions( - ForceFormattingOptions forceFormattingOptions) { - this.forceFormattingOptions = forceFormattingOptions; - return this; - } - - public FormattingOptions.FormattingOptionsBuilder setImportFormattingOptions( - ImportFormattingOptions importFormattingOptions) { - this.importFormattingOptions = importFormattingOptions; - return this; - } - - public FormattingOptions build() { - return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, forceFormattingOptions, - recordBraceSpacing, alignConsecutiveDefinitions, alignMultiLineQueries, importFormattingOptions, - functionBuilder.build(), blockBuilder.build()); - } - - public FormattingOptions build(Object data) { - if (!(data instanceof Map)) { - return build(); - } - Map configurations = (Map) data; - for (Map.Entry entry : configurations.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - switch (key) { - case "columnLimit": - this.columnLimit = ((Number) value).intValue(); - this.lineWrapping = true; - break; - case "tabWidth": - this.tabSize = ((Number) value).intValue(); - break; - case "alignConsecutiveDefinitions": - this.alignConsecutiveDefinitions = ((Boolean) value); - break; - case "recordBraceSpacing": - this.recordBraceSpacing = ((Boolean) value); - break; - case "alignMultiLineQueries": - this.alignMultiLineQueries = ((Boolean) value); - break; - case "block": - Map blockConfigurations = (Map) value; - for (Map.Entry funcEntry : blockConfigurations.entrySet()) { - String blockKey = funcEntry.getKey(); - boolean blockValue = (Boolean) funcEntry.getValue(); - switch (blockKey) { - case "elseBlockOnANewLine": - this.blockBuilder.setElseBlockOnANewLine(blockValue); - break; - case "allowShortMatchLabelsOnASingleLine": - this.blockBuilder.setAllowShortMatchLabelsOnASingleLine( - blockValue); - break; - case "allowShortIfStatementsOnASingleLine": - this.blockBuilder.setAllowShortIfStatementsOnASingleLine( - blockValue); - break; - case "allowShortLoopsOnASingleLine": - this.blockBuilder.setAllowShortLoopsOnASingleLine(blockValue); - break; - case "allowShortBlocksOnASingleLine": - this.blockBuilder.setAllowShortBlocksOnASingleLine(blockValue); - break; - default: - break; - } - } - break; - case "function": - Map funcConfigurations = (Map) value; - for (Map.Entry funcEntry : funcConfigurations.entrySet()) { - String funcKey = funcEntry.getKey(); - boolean funcValue = (Boolean) funcEntry.getValue(); - switch (funcKey) { - case "paranAlign": - this.functionBuilder.setParanAlign(funcValue); - break; - case "oneArgPerLine": - this.functionBuilder.setOneArgPerLine(funcValue); - break; - default: - break; - } - } - break; - case "import": - Map importConfigurations = (Map) value; - for (Map.Entry funcEntry : importConfigurations.entrySet()) { - String funcKey = funcEntry.getKey(); - boolean importValue = (Boolean) funcEntry.getValue(); - switch (funcKey) { - case "groupImports": - this.importBuilder.setGroupImports(importValue); - break; - case "sortImports": - this.importBuilder.setSortImports(importValue); - break; - case "removeUnusedImports": - this.importBuilder.setRemoveUnusedImports(importValue); - break; - default: - break; - } - } - break; - default: - break; - } - } - return new FormattingOptions(tabSize, wsCharacter, columnLimit, lineWrapping, continuationIndent, forceFormattingOptions, - recordBraceSpacing, alignConsecutiveDefinitions, alignMultiLineQueries, importBuilder.build(), - functionBuilder.build(), blockBuilder.build()); - } - } -} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index df2029226bc9..67fd4bdf537e 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -249,6 +249,11 @@ import io.ballerina.compiler.syntax.tree.XMLTextNode; import io.ballerina.tools.text.LinePosition; import io.ballerina.tools.text.LineRange; +import org.ballerinalang.formatter.core.options.BraceStyle; +import org.ballerinalang.formatter.core.options.FormattingOptions; +import org.ballerinalang.formatter.core.options.FunctionCallFormattingOptions; +import org.ballerinalang.formatter.core.options.FunctionDeclFormattingOptions; +import org.ballerinalang.formatter.core.options.WrappingMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -318,7 +323,10 @@ public FunctionDefinitionNode transform(FunctionDefinitionNode functionDefinitio functionName = formatToken(functionDefinitionNode.functionName(), 1, 0); } NodeList relativeResourcePath = formatNodeList(functionDefinitionNode.relativeResourcePath(), 0, 0, 0, 0); - FunctionSignatureNode functionSignatureNode = formatNode(functionDefinitionNode.functionSignature(), 1, 0); + int trailingNL = options.braceFormattingOptions().methodBraceStyle() == BraceStyle.NEWLINE ? 1 : 0; + FunctionSignatureNode functionSignatureNode = + formatNode(functionDefinitionNode.functionSignature(), 1 - trailingNL, + trailingNL); FunctionBodyNode functionBodyNode = formatNode(functionDefinitionNode.functionBody(), env.trailingWS, env.trailingNL); @@ -367,19 +375,25 @@ public ResourcePathParameterNode transform(ResourcePathParameterNode resourcePat @Override public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNode) { int parenTrailingNL = 0; - if (hasNonWSMinutiae(functionSignatureNode.openParenToken().trailingMinutiae())) { + FunctionDeclFormattingOptions funcOptions = options.functionDeclFormattingOptions(); + if (hasNonWSMinutiae(functionSignatureNode.openParenToken().trailingMinutiae()) || + funcOptions.newLineAfterLeftParen()) { parenTrailingNL++; } - Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); - boolean paranAlign = options.getFunctionFormattingOptions().getParanAlign(); + boolean paranAlign = funcOptions.alignMultilineParameters(); // Start a new indentation of two tabs for the parameters. - alignOrIndent(paranAlign, options.getContinuationIndent()); - boolean oneArgPerLine = options.getFunctionFormattingOptions().getOneArgPerLine(); + if (!functionSignatureNode.openParenToken().isMissing()) { + alignOrIndent(paranAlign, options.indentFormattingOptions().continuationIndentSize()); + } + Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); + + boolean oneArgPerLine = funcOptions.parametersWrap() == WrappingMethod.CHOPDOWN; + int closeParenLeadingNL = funcOptions.rightParenOnNewLine() ? 1 : 0; SeparatedNodeList parameters = formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, - oneArgPerLine ? 1 : 0, 0, 0, true); - unalignOrUnindent(paranAlign, options.getContinuationIndent()); + oneArgPerLine ? 1 : 0, 0, closeParenLeadingNL, true); + unalignOrUnindent(paranAlign, options.indentFormattingOptions().continuationIndentSize()); Token closePara; ReturnTypeDescriptorNode returnTypeDesc = null; @@ -389,13 +403,7 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo formatNode(functionSignatureNode.returnTypeDesc().get(), env.trailingWS, env.trailingNL); } else { closePara = formatToken(functionSignatureNode.closeParenToken(), env.trailingWS, env.trailingNL); - } - - if (paranAlign) { - unalign(); - } else { - unindent(options.getContinuationIndent()); - } + } return functionSignatureNode.modify() .withOpenParenToken(openPara) @@ -452,9 +460,11 @@ public IncludedRecordParameterNode transform(IncludedRecordParameterNode include @Override public FunctionBodyBlockNode transform(FunctionBodyBlockNode functionBodyBlockNode) { - Token openBrace = formatToken(functionBodyBlockNode.openBraceToken(), 0, 1); + int trailingNL = openBraceTrailingNLs(options.wrappingFormattingOptions(), functionBodyBlockNode); + Token openBrace = formatToken(functionBodyBlockNode.openBraceToken(), 1 - trailingNL, trailingNL); indent(); // increase indentation for the statements to follow. - NodeList statements = formatNodeList(functionBodyBlockNode.statements(), 0, 1, 0, 1); + NodeList statements = + formatNodeList(functionBodyBlockNode.statements(), 0, 1, 1 - trailingNL, trailingNL); NamedWorkerDeclarator namedWorkerDeclarator = formatNode(functionBodyBlockNode.namedWorkerDeclarator().orElse(null), 0, 1); @@ -487,7 +497,6 @@ public VariableDeclarationNode transform(VariableDeclarationNode variableDeclara setInlineAnnotation(true); ExpressionNode initializer = formatNode(variableDeclarationNode.initializer().orElse(null), 0, 0); setInlineAnnotation(previousInlineAnnotation); - Token semicolonToken = formatToken(variableDeclarationNode.semicolonToken(), env.trailingWS, env.trailingNL); return variableDeclarationNode.modify() @@ -537,7 +546,7 @@ public IfElseStatementNode transform(IfElseStatementNode ifElseStatementNode) { BlockStatementNode ifBody; Node elseBody = null; if (ifElseStatementNode.elseBody().isPresent()) { - boolean needNL = options.getBlockFormattingOptions().elseBlockOnANewLine(); + boolean needNL = options.ifStatementFormattingOptions().elseOnNewLine(); ifBody = formatNode(ifElseStatementNode.ifBody(), needNL ? 0 : 1, needNL ? 1 : 0); preserveIndentation(!hasTrailingNL(ifElseStatementNode.ifBody().closeBraceToken())); @@ -569,7 +578,7 @@ public ElseBlockNode transform(ElseBlockNode elseBlockNode) { public BlockStatementNode transform(BlockStatementNode blockStatementNode) { boolean preserveIndent = env.preserveIndentation; preserveIndentation(blockStatementNode.openBraceToken().isMissing() && preserveIndent); - int trailingNL = openBraceTrailingNLs(options.getBlockFormattingOptions(), blockStatementNode); + int trailingNL = openBraceTrailingNLs(options.wrappingFormattingOptions(), blockStatementNode); int trailingWS = 1 - trailingNL; Token openBrace = formatToken(blockStatementNode.openBraceToken(), trailingWS, trailingNL); preserveIndentation(preserveIndent); @@ -577,7 +586,7 @@ public BlockStatementNode transform(BlockStatementNode blockStatementNode) { NodeList statements = formatNodeList(blockStatementNode.statements(), 0, 1, trailingWS, trailingNL); unindent(); // end the indentation - int closingNL = (options.getBlockFormattingOptions().elseBlockOnANewLine() && + int closingNL = (options.ifStatementFormattingOptions().elseOnNewLine() && blockStatementNode.parent().kind() == SyntaxKind.IF_ELSE_STATEMENT) ? 1 : env.trailingNL; Token closeBrace = formatToken(blockStatementNode.closeBraceToken(), env.trailingWS, closingNL); @@ -1085,18 +1094,29 @@ public ReturnStatementNode transform(ReturnStatementNode returnStatementNode) { @Override public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionCallExpressionNode) { NameReferenceNode functionName = formatNode(functionCallExpressionNode.functionName(), 0, 0); - Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, 0); + FunctionCallFormattingOptions callOptions = options.functionCallFormattingOptions(); int prevIndentation = env.currentIndentation; - if (functionCallExpressionNode.arguments().size() > 0) { - if (!isScopedFunctionArgument(functionCallExpressionNode.arguments().get(0))) { - indent(options.getContinuationIndent()); - } - } - SeparatedNodeList arguments = formatSeparatedNodeList(functionCallExpressionNode - .arguments(), 0, 0, 0, 0, true); - env.currentIndentation = prevIndentation; +// if (functionCallExpressionNode.arguments().size() > 0) { +// if (!isScopedFunctionArgument(functionCallExpressionNode.arguments().get(0))) { +// indented = true; + alignOrIndent(callOptions.alignMultilineParameters(), + options.indentFormattingOptions().continuationIndentSize()); +// } +// } + Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, + callOptions.newLineAfterLeftParen() ? 1 : 0); + + boolean oneArgPerLine = callOptions.parametersWrap() == WrappingMethod.CHOPDOWN; + int closeParenLeadingNL = callOptions.rightParenOnNewLine() ? 1 : 0; + SeparatedNodeList arguments = + formatSeparatedNodeList(functionCallExpressionNode.arguments(), 0, 0, oneArgPerLine ? 0 : 1, + oneArgPerLine ? 1 : 0, 0, closeParenLeadingNL, true); + setIndentation(prevIndentation); Token functionCallClosePara = formatToken(functionCallExpressionNode.closeParenToken(), env.trailingWS, env.trailingNL); +// if (indented) { + +// } return functionCallExpressionNode.modify() .withFunctionName(functionName) .withOpenParenToken(functionCallOpenPara) @@ -1157,7 +1177,7 @@ public ConstantDeclarationNode transform(ConstantDeclarationNode constantDeclara Token visibilityQualifier = formatToken(constantDeclarationNode.visibilityQualifier().orElse(null), 1, 0); Token constKeyword = formatToken(constantDeclarationNode.constKeyword(), 1, 0); TypeDescriptorNode typeDescriptorNode = formatNode(constantDeclarationNode.typeDescriptor().orElse(null), 1, 0); - int wSBeforeEqual = !options.alignConsecutiveDefinitions() ? 1 : + int wSBeforeEqual = !options.spacingFormattingOptions().alignConsecutiveDefinitions() ? 1 : env.maxConstDefWidth - getConstDefWidth(constantDeclarationNode) + 1; Token variableName = formatToken(constantDeclarationNode.variableName(), wSBeforeEqual, 0); Token equalsToken = formatToken(constantDeclarationNode.equalsToken(), 1, 0); @@ -1273,7 +1293,7 @@ public MappingConstructorExpressionNode transform( } else { fieldTrailingWS++; } - int innerWS = options.isRecordBraceSpacing() ? 1 : 0; + int innerWS = options.spacingFormattingOptions().aroundRecordBraces() ? 1 : 0; Token openBrace = formatToken(mappingConstructorExpressionNode.openBrace(), innerWS, fieldTrailingNL); indent(); SeparatedNodeList fields = formatSeparatedNodeList( @@ -1439,7 +1459,8 @@ public ExpressionFunctionBodyNode transform(ExpressionFunctionBodyNode expressio public TypeCastExpressionNode transform(TypeCastExpressionNode typeCastExpressionNode) { Token ltToken = formatToken(typeCastExpressionNode.ltToken(), 0, 0); TypeCastParamNode typeCastParam = formatNode(typeCastExpressionNode.typeCastParam(), 0, 0); - Token gtToken = formatToken(typeCastExpressionNode.gtToken(), 0, 0); + Token gtToken = formatToken(typeCastExpressionNode.gtToken(), + options.spacingFormattingOptions().afterTypeCast() ? 1 : 0, 0); ExpressionNode expression = formatNode(typeCastExpressionNode.expression(), env.trailingWS, env.trailingNL); return typeCastExpressionNode.modify() @@ -1870,7 +1891,7 @@ public MarkdownCodeLineNode transform(MarkdownCodeLineNode markdownCodeLineNode) @Override public PositionalArgumentNode transform(PositionalArgumentNode positionalArgumentNode) { if (env.lineLength != 0 && isScopedFunctionArgument(positionalArgumentNode)) { - env.currentIndentation = env.lineLength; + align(); } ExpressionNode expression = formatNode(positionalArgumentNode.expression(), env.trailingWS, env.trailingNL); return positionalArgumentNode.modify() @@ -2860,9 +2881,10 @@ public CollectClauseNode transform(CollectClauseNode collectClauseNode) { @Override public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { - int length = options.alignMultiLineQueries() ? env.currentIndentation : env.lineLength; + boolean alignMultiLineQueries = options.queryFormattingOptions().alignMultiLineQueries(); + int length = alignMultiLineQueries ? env.currentIndentation : env.lineLength; if (length != 0) { - alignOrIndent(options.alignMultiLineQueries()); + alignOrIndent(alignMultiLineQueries); } QueryConstructTypeNode queryConstructType = @@ -2879,7 +2901,7 @@ public QueryExpressionNode transform(QueryExpressionNode queryExpressionNode) { OnConflictClauseNode onConflictClause = formatNode(queryExpressionNode.onConflictClause().orElse(null), env.trailingWS, env.trailingNL); if (length != 0) { - unalignOrUnindent(options.alignMultiLineQueries()); + unalignOrUnindent(alignMultiLineQueries); } return queryExpressionNode.modify() @@ -3513,7 +3535,9 @@ public ClassDefinitionNode transform(ClassDefinitionNode classDefinitionNode) { Token visibilityQualifier = formatToken(classDefinitionNode.visibilityQualifier().orElse(null), 1, 0); NodeList classTypeQualifiers = formatNodeList(classDefinitionNode.classTypeQualifiers(), 1, 0, 1, 0); Token classKeyword = formatToken(classDefinitionNode.classKeyword(), 1, 0); - Token className = formatToken(classDefinitionNode.className(), 1, 0); + int trailingNL = options.braceFormattingOptions().classBraceStyle() == BraceStyle.NEWLINE ? 1 : 0; + Token className = formatToken(classDefinitionNode.className(), 1 - trailingNL, + trailingNL); Token openBrace = formatToken(classDefinitionNode.openBrace(), 0, 1); indent(); @@ -3808,7 +3832,7 @@ private T formatNode(T node, int trailingWS, int trailingNL, Bo node = (T) node.apply(this); - if (options.getLineWrapping() && shouldWrapLine(oldNode, parent)) { + if (options.wrappingFormattingOptions().lineWrap() && shouldWrapLine(oldNode, parent)) { node = wrapLine(oldNode, parent); } @@ -3918,7 +3942,7 @@ protected NodeList formatMemberDeclarations(NodeList memb boolean nodeModified = false; int size = members.size(); - if (options.alignConsecutiveDefinitions()) { + if (options.spacingFormattingOptions().alignConsecutiveDefinitions()) { env.maxConstDefWidth = members.stream() .filter(member -> member.kind() == SyntaxKind.CONST_DECLARATION) .mapToInt(member -> getConstDefWidth((ConstantDeclarationNode) member)) @@ -4150,7 +4174,8 @@ protected SeparatedNodeList formatSeparatedNodeList(Separate boolean nodeModified = false; int size = nodeList.size(); Node[] newNodes = new Node[size * 2 - 1]; - + int prevSeparatorTrailingNL = separatorTrailingNL; + int prevSeparatorTrailingWS = separatorTrailingWS; for (int index = 0; index < size; index++) { T oldNode = nodeList.get(index); T newNode = formatListItem(itemTrailingWS, itemTrailingNL, listTrailingWS, listTrailingNL, size, @@ -4165,7 +4190,11 @@ protected SeparatedNodeList formatSeparatedNodeList(Separate } Token oldSeparator = nodeList.getSeparator(index); + separatorTrailingNL = prevSeparatorTrailingNL; + separatorTrailingWS = prevSeparatorTrailingWS; if (allowInAndMultiLine && hasNonWSMinutiae(oldSeparator.trailingMinutiae())) { + prevSeparatorTrailingNL = separatorTrailingNL; + prevSeparatorTrailingWS = separatorTrailingWS; separatorTrailingNL = separatorTrailingNL > 0 ? separatorTrailingNL : 1; separatorTrailingWS = 0; } @@ -4230,7 +4259,7 @@ private void checkForNewline(T node) { * @return Flag indicating whether to wrap the current line or not */ private boolean shouldWrapLine(Node node, Node parent) { - boolean exceedsColumnLimit = env.lineLength > options.getColumnLimit(); + boolean exceedsColumnLimit = env.lineLength > options.wrappingFormattingOptions().maxLineLength(); boolean descendantNeedWrapping = env.nodeToWrap == node; if (!exceedsColumnLimit && !descendantNeedWrapping) { return false; @@ -4246,17 +4275,25 @@ private boolean shouldWrapLine(Node node, Node parent) { } return true; - // Parameters + // Function Definition case DEFAULTABLE_PARAM: case REQUIRED_PARAM: case REST_PARAM: + case RETURN_TYPE_DESCRIPTOR: + if (options.functionDeclFormattingOptions().parametersWrap() == WrappingMethod.NOWRAP) { + return false; + } + return true; // Func-call arguments case POSITIONAL_ARG: case NAMED_ARG: case REST_ARG: + if (options.functionCallFormattingOptions().parametersWrap() == WrappingMethod.NOWRAP) { + return false; + } + return true; - case RETURN_TYPE_DESCRIPTOR: case ANNOTATION_ATTACH_POINT: return true; @@ -4302,7 +4339,7 @@ private T wrapLine(T node, Node parent) { // Sometimes wrapping the current node wouldn't be enough. Therefore, if the column // length exceeds even after wrapping current node, then ask the parent node to warp. - if (env.lineLength > options.getColumnLimit()) { + if (env.lineLength > options.wrappingFormattingOptions().maxLineLength()) { env.nodeToWrap = parent; } else { env.nodeToWrap = null; @@ -4367,7 +4404,7 @@ private MinutiaeList getLeadingMinutiae(Token token) { if (!env.preserveIndentation) { int indentation = env.currentIndentation; if (isClosingTypeToken(token)) { - indentation += options.getTabSize(); + indentation += options.indentFormattingOptions().indentSize(); } // Then add padding to match the current indentation level addWhitespace(indentation, leadingMinutiae); @@ -4533,7 +4570,7 @@ private void indent() { * @param step Number of tabs. */ private void indent(int step) { - env.currentIndentation += (options.getTabSize() * step); + env.currentIndentation += (options.indentFormattingOptions().indentSize() * step); } /** @@ -4557,12 +4594,12 @@ private void unindent() { * @param step Number of tabs. */ private void unindent(int step) { - if (env.currentIndentation < (options.getTabSize() * step)) { + if (env.currentIndentation < (options.indentFormattingOptions().indentSize() * step)) { env.currentIndentation = 0; return; } - env.currentIndentation -= (options.getTabSize() * step); + env.currentIndentation -= (options.indentFormattingOptions().indentSize() * step); } /** @@ -4644,7 +4681,7 @@ private int getPreservedIndentation(Token token) { break; } } - int tabSize = options.getTabSize(); + int tabSize = options.indentFormattingOptions().indentSize(); if (env.currentIndentation % tabSize == 0 && env.currentIndentation > position) { return env.currentIndentation; } @@ -4679,7 +4716,7 @@ private String getWSContent(int count) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { - sb.append(options.getWSCharacter()); + sb.append(options.indentFormattingOptions().wsCharacter()); } return sb.toString(); @@ -4717,7 +4754,7 @@ private boolean shouldExpand(Node node) { NodeList objectConstructorMembers = objectConstructor.members(); return shouldExpandObjectMembers(objectConstructorMembers); case RECORD_TYPE_DESC: - if (options.getForceFormattingOptions().getForceFormatRecordFields()) { + if (options.forceFormattingOptions().forceFormatRecordFields()) { return true; } @@ -4867,7 +4904,7 @@ private NodeList arrangeAndFormatImportDeclarations( List thirdPartyImports = new ArrayList<>(); for (ImportDeclarationNode importDeclarationNode : importDeclarationNodes) { - if (importDeclarationNode.orgName().isEmpty() || !options.getImportFormattingOptions().getGroupImports()) { + if (importDeclarationNode.orgName().isEmpty() || !options.importFormattingOptions().groupImports()) { moduleImports.add(importDeclarationNode); } else { if (List.of("ballerina", "ballerinax") @@ -4878,7 +4915,7 @@ private NodeList arrangeAndFormatImportDeclarations( } } } - if (options.getImportFormattingOptions().getSortImports()) { + if (options.importFormattingOptions().sortImports()) { sortImportDeclarations(moduleImports); sortImportDeclarations(stdLibImports); sortImportDeclarations(thirdPartyImports); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java deleted file mode 100644 index c2941ff29b19..000000000000 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FunctionFormattingOptions.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ballerinalang.formatter.core; - -/** - * A model for formatting of functions by the API user, that could be passed onto the formatter. - * - * @since 2201.8.0 - */ -public class FunctionFormattingOptions { - - private final boolean paranAlign; - private final boolean oneArgPerLine; - - private FunctionFormattingOptions(boolean paranAlign, boolean oneArgPerLine) { - this.paranAlign = paranAlign; - this.oneArgPerLine = oneArgPerLine; - } - - public boolean getParanAlign() { - return paranAlign; - } - - public boolean getOneArgPerLine() { - return oneArgPerLine; - } - - public static FunctionFormattingOptions.FunctionFormattingOptionsBuilder builder() { - return new FunctionFormattingOptions.FunctionFormattingOptionsBuilder(); - } - - /** - * A builder for the {@code FunctionFormattingOptions}. - */ - public static class FunctionFormattingOptionsBuilder { - - private boolean paranAlign = false; - private boolean oneArgPerLine = false; - - public FunctionFormattingOptions.FunctionFormattingOptionsBuilder setParanAlign(boolean paranAlign) { - this.paranAlign = paranAlign; - return this; - } - - public FunctionFormattingOptions.FunctionFormattingOptionsBuilder setOneArgPerLine(boolean oneArgPerLine) { - this.oneArgPerLine = oneArgPerLine; - return this; - } - - public FunctionFormattingOptions build() { - return new FunctionFormattingOptions(paranAlign, oneArgPerLine); - } - } -} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java new file mode 100644 index 000000000000..74ced3ff74b8 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +import java.util.Map; + +/** + * A model for formatting of brace settings by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class BraceFormattingOptions { + private final BraceStyle classBraceStyle; + private final BraceStyle methodBraceStyle; + + public BraceFormattingOptions(BraceStyle classBraceStyle, BraceStyle methodBraceStyle) { + this.classBraceStyle = classBraceStyle; + this.methodBraceStyle = methodBraceStyle; + } + + public BraceStyle classBraceStyle() { + return classBraceStyle; + } + + public BraceStyle methodBraceStyle() { + return methodBraceStyle; + } + + public static BraceFormattingOptions.BraceFormattingOptionsBuilder builder() { + return new BraceFormattingOptionsBuilder(); + } + + public static class BraceFormattingOptionsBuilder { + + private BraceStyle classBraceStyle = BraceStyle.ENDOFLINE; + private BraceStyle methodBraceStyle = BraceStyle.ENDOFLINE; + + public BraceFormattingOptionsBuilder setClassBraceStyle(BraceStyle classBraceStyle) { + this.classBraceStyle = classBraceStyle; + return this; + } + + public BraceFormattingOptionsBuilder setMethodBraceStyle(BraceStyle methodBraceStyle) { + this.methodBraceStyle = methodBraceStyle; + return this; + } + + public BraceFormattingOptions build() { + return new BraceFormattingOptions(classBraceStyle, methodBraceStyle); + } + + public BraceFormattingOptions build(Map configs) throws FormatterException { + for (Map.Entry bracesEntry : configs.entrySet()) { + String bracesKey = bracesEntry.getKey(); + BraceStyle style = BraceStyle.fromString((String) bracesEntry.getValue()); + switch (bracesKey) { + case "classBraceStyle": + setClassBraceStyle(style); + break; + case "methodBraceStyle": + setMethodBraceStyle(style); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java new file mode 100644 index 000000000000..32c8d20734ae --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -0,0 +1,16 @@ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +public enum BraceStyle { + NEWLINE, + ENDOFLINE; + + public static BraceStyle fromString(String value) throws FormatterException { + try { + return BraceStyle.valueOf(value); + } catch (IllegalArgumentException e) { + throw new FormatterException("Invalid Brace style: " + value); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ForceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java similarity index 94% rename from misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ForceFormattingOptions.java rename to misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java index b887a4b5a66f..fc3e69367c16 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ForceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ballerinalang.formatter.core; +package org.ballerinalang.formatter.core.options; /** * A model for formatting options that can be forced by the API user, that could be passed onto the formatter. @@ -27,7 +27,7 @@ private ForceFormattingOptions(boolean forceFormatRecordFields) { this.forceFormatRecordFields = forceFormatRecordFields; } - public boolean getForceFormatRecordFields() { + public boolean forceFormatRecordFields() { return forceFormatRecordFields; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java new file mode 100644 index 000000000000..c4d13613a321 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2020, WSO2 Inc. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +import java.util.Map; + +import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; + +/** + * A model for formatting options that could be passed onto the formatter. + */ +public class FormattingOptions { + + private IndentFormattingOptions indentFormattingOptions; + private WrappingFormattingOptions wrappingFormattingOptions; + private BraceFormattingOptions braceFormattingOptions; + private FunctionDeclFormattingOptions functionDeclFormattingOptions; + private FunctionCallFormattingOptions functionCallFormattingOptions; + private IfStatementFormattingOptions ifStatementFormattingOptions; + private SpacingFormattingOptions spacingFormattingOptions; + private ForceFormattingOptions forceFormattingOptions; + private ImportFormattingOptions importFormattingOptions; + private QueryFormattingOptions queryFormattingOptions; + + public FormattingOptions(IndentFormattingOptions indentFormattingOptions, + WrappingFormattingOptions wrappingFormattingOptions, + BraceFormattingOptions braceFormattingOptions, + FunctionDeclFormattingOptions functionDeclFormattingOptions, + FunctionCallFormattingOptions functionCallFormattingOptions, + IfStatementFormattingOptions ifStatementFormattingOptions, + SpacingFormattingOptions spacingFormattingOptions, + ForceFormattingOptions forceFormattingOptions, + ImportFormattingOptions importFormattingOptions, + QueryFormattingOptions queryFormattingOptions) { + this.indentFormattingOptions = indentFormattingOptions; + this.wrappingFormattingOptions = wrappingFormattingOptions; + this.braceFormattingOptions = braceFormattingOptions; + this.functionDeclFormattingOptions = functionDeclFormattingOptions; + this.functionCallFormattingOptions = functionCallFormattingOptions; + this.ifStatementFormattingOptions = ifStatementFormattingOptions; + this.spacingFormattingOptions = spacingFormattingOptions; + this.forceFormattingOptions = forceFormattingOptions; + this.importFormattingOptions = importFormattingOptions; + this.queryFormattingOptions = queryFormattingOptions; + } + + public ForceFormattingOptions forceFormattingOptions() { + return forceFormattingOptions; + } + + public ImportFormattingOptions importFormattingOptions() { + return importFormattingOptions; + } + + public IndentFormattingOptions indentFormattingOptions() { + return indentFormattingOptions; + } + + public WrappingFormattingOptions wrappingFormattingOptions() { + return wrappingFormattingOptions; + } + + public BraceFormattingOptions braceFormattingOptions() { + return braceFormattingOptions; + } + + public FunctionDeclFormattingOptions functionDeclFormattingOptions() { + return functionDeclFormattingOptions; + } + + public FunctionCallFormattingOptions functionCallFormattingOptions() { + return functionCallFormattingOptions; + } + + public IfStatementFormattingOptions ifStatementFormattingOptions() { + return ifStatementFormattingOptions; + } + + public SpacingFormattingOptions spacingFormattingOptions() { + return spacingFormattingOptions; + } + + public QueryFormattingOptions queryFormattingOptions() { + return queryFormattingOptions; + } + + public static FormattingOptionsBuilder builder() { + return new FormattingOptionsBuilder(); + } + + /** + * A builder for the {@code FormattingOptions}. + * + * @since 2201.3.0 + */ + public static class FormattingOptionsBuilder { + + private IndentFormattingOptions indentFormattingOptions = IndentFormattingOptions.builder().build(); + private WrappingFormattingOptions wrappingFormattingOptions = WrappingFormattingOptions.builder().build(); + private BraceFormattingOptions braceFormattingOptions = BraceFormattingOptions.builder().build(); + private FunctionDeclFormattingOptions functionDeclFormattingOptions = + FunctionDeclFormattingOptions.builder().build(); + private FunctionCallFormattingOptions functionCallFormattingOptions = + FunctionCallFormattingOptions.builder().build(); + private IfStatementFormattingOptions ifStatementFormattingOptions = + IfStatementFormattingOptions.builder().build(); + private SpacingFormattingOptions spacingFormattingOptions = SpacingFormattingOptions.builder().build(); + private ImportFormattingOptions importFormattingOptions = ImportFormattingOptions.builder().build(); + private QueryFormattingOptions queryFormattingOptions = QueryFormattingOptions.builder().build(); + private ForceFormattingOptions forceFormattingOptions = ForceFormattingOptions.builder().build(); + + public FormattingOptionsBuilder setForceFormattingOptions(ForceFormattingOptions forceFormattingOptions) { + this.forceFormattingOptions = forceFormattingOptions; + return this; + } + + public FormattingOptionsBuilder setImportFormattingOptions(ImportFormattingOptions importFormattingOptions) { + this.importFormattingOptions = importFormattingOptions; + return this; + } + + public FormattingOptionsBuilder setWrappingFormattingOptions( + WrappingFormattingOptions wrappingFormattingOptions) { + this.wrappingFormattingOptions = wrappingFormattingOptions; + return this; + } + + public FormattingOptions build() { + return new FormattingOptions(indentFormattingOptions, wrappingFormattingOptions, braceFormattingOptions, + functionDeclFormattingOptions, functionCallFormattingOptions, ifStatementFormattingOptions, + spacingFormattingOptions, forceFormattingOptions, importFormattingOptions, queryFormattingOptions); + } + + public FormattingOptions build(Object data) throws FormatterException { + if (!(data instanceof Map)) { + return build(); + } + Map balTomlConfigurations = (Map) data; + Object path = balTomlConfigurations.get("configPath"); + if (path == null) { + return build(); + } + Map configurations = getFormattingConfigurations((String) path.toString()); + + for (Map.Entry entry : configurations.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (!(value instanceof Map)) { + continue; + } + Map configs = (Map) value; + switch (key) { + case "indent": + indentFormattingOptions = IndentFormattingOptions.builder().build(configs); + break; + case "wrapping": + wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); + break; + case "braces": + braceFormattingOptions = BraceFormattingOptions.builder().build(configs); + break; + case "methodDeclaration": + functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); + break; + case "methodCall": + functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); + break; + case "ifStatement": + ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); + break; + case "query": + queryFormattingOptions = QueryFormattingOptions.builder().build(configs); + break; + case "spacing": + spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); + break; +// case "import": +// importFormattingOptions = ImportFormattingOptions.builder().build(configs); +// break; + default: + break; + } + } + + return build(); + } + } + +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java new file mode 100644 index 000000000000..a7b30de81c06 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +import java.util.Map; + +/** + * A model for formatting of if statement by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class FunctionCallFormattingOptions { + + private final WrappingMethod parametersWrap; + private final boolean alignMultilineParameters; + private final boolean newLineAfterLeftParen; + private final boolean rightParenOnNewLine; + + public FunctionCallFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { + this.parametersWrap = parametersWrap; + this.alignMultilineParameters = alignMultilineParameters; + this.newLineAfterLeftParen = newLineAfterLeftParen; + this.rightParenOnNewLine = rightParenOnNewLine; + } + + public WrappingMethod parametersWrap() { + return parametersWrap; + } + + public boolean alignMultilineParameters() { + return alignMultilineParameters; + } + + public boolean newLineAfterLeftParen() { + return newLineAfterLeftParen; + } + + public boolean rightParenOnNewLine() { + return rightParenOnNewLine; + } + + public static FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder builder() { + return new FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder(); + } + + /** + * A builder for the {@code FunctionFormattingOptions}. + */ + public static class FunctionCallFormattingOptionsBuilder { + + private WrappingMethod parametersWrap = WrappingMethod.WRAP; + private boolean alignMultilineParameters = false; + private boolean newLineAfterLeftParen = false; + private boolean rightParenOnNewLine = false; + + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setParametersWrap( + WrappingMethod parametersWrap) { + this.parametersWrap = parametersWrap; + return this; + } + + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setAlignMultilineParameters( + boolean alignMultilineParameters) { + this.alignMultilineParameters = alignMultilineParameters; + return this; + } + + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setNewLineAfterLeftParen( + boolean newLineAfterLeftParen) { + this.newLineAfterLeftParen = newLineAfterLeftParen; + return this; + } + + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setRightParenOnNewLine( + boolean rightParenOnNewLine) { + this.rightParenOnNewLine = rightParenOnNewLine; + return this; + } + + public FunctionCallFormattingOptions build() { + return new FunctionCallFormattingOptions(parametersWrap, alignMultilineParameters, newLineAfterLeftParen, + rightParenOnNewLine); + } + + public FunctionCallFormattingOptions build(Map configs) throws FormatterException { + for (Map.Entry methodCallEntry : configs.entrySet()) { + String methodCallKey = methodCallEntry.getKey(); + switch (methodCallKey) { + case "parametersWrap": + setParametersWrap(WrappingMethod.fromString((String) methodCallEntry.getValue())); + break; + case "alignMultilineParameters": + setAlignMultilineParameters((Boolean) methodCallEntry.getValue()); + break; + case "newLineAfterLeftParen": + setNewLineAfterLeftParen((Boolean) methodCallEntry.getValue()); + break; + case "rightParenOnNewLine": + setRightParenOnNewLine((Boolean) methodCallEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java new file mode 100644 index 000000000000..944fe8f5d8a8 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +import java.util.Map; + +/** + * A model for formatting of function declarations by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class FunctionDeclFormattingOptions { + + private final WrappingMethod parametersWrap; + private final boolean alignMultilineParameters; + private final boolean newLineAfterLeftParen; + private final boolean rightParenOnNewLine; + + public FunctionDeclFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { + this.parametersWrap = parametersWrap; + this.alignMultilineParameters = alignMultilineParameters; + this.newLineAfterLeftParen = newLineAfterLeftParen; + this.rightParenOnNewLine = rightParenOnNewLine; + } + + public WrappingMethod parametersWrap() { + return parametersWrap; + } + + public boolean alignMultilineParameters() { + return alignMultilineParameters; + } + + public boolean newLineAfterLeftParen() { + return newLineAfterLeftParen; + } + + public boolean rightParenOnNewLine() { + return rightParenOnNewLine; + } + + public static FunctionDeclFormattingOptionsBuilder builder() { + return new FunctionDeclFormattingOptions.FunctionDeclFormattingOptionsBuilder(); + } + + public static class FunctionDeclFormattingOptionsBuilder { + + private WrappingMethod parametersWrap = WrappingMethod.WRAP; + private boolean alignMultilineParameters = false; + private boolean newLineAfterLeftParen = false; + private boolean rightParenOnNewLine = false; + + public FunctionDeclFormattingOptionsBuilder setParametersWrap(WrappingMethod parametersWrap) { + this.parametersWrap = parametersWrap; + return this; + } + + public FunctionDeclFormattingOptionsBuilder setAlignMultilineParameters(boolean alignMultilineParameters) { + this.alignMultilineParameters = alignMultilineParameters; + return this; + } + + public FunctionDeclFormattingOptionsBuilder setNewLineAfterLeftParen(boolean newLineAfterLeftParen) { + this.newLineAfterLeftParen = newLineAfterLeftParen; + return this; + } + + public FunctionDeclFormattingOptionsBuilder setRightParenOnNewLine(boolean rightParenOnNewLine) { + this.rightParenOnNewLine = rightParenOnNewLine; + return this; + } + + public FunctionDeclFormattingOptions build() { + return new FunctionDeclFormattingOptions(parametersWrap, alignMultilineParameters, + newLineAfterLeftParen, rightParenOnNewLine); + } + + public FunctionDeclFormattingOptions build(Map configs) throws FormatterException { + for (Map.Entry methodDeclarationEntry : configs.entrySet()) { + String methodDeclarationKey = methodDeclarationEntry.getKey(); + switch (methodDeclarationKey) { + case "parametersWrap": + setParametersWrap(WrappingMethod.fromString((String) methodDeclarationEntry.getValue())); + break; + case "alignMultilineParameters": + setAlignMultilineParameters((Boolean) methodDeclarationEntry.getValue()); + break; + case "newLineAfterLeftParen": + setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); + break; + case "rightParenOnNewLine": + setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java new file mode 100644 index 000000000000..63e9ab3b282e --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import java.util.Map; + +/** + * A model for formatting of indent settings by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class IfStatementFormattingOptions { + + private final boolean elseOnNewLine; + + public IfStatementFormattingOptions(boolean elseOnNewLine) { + this.elseOnNewLine = elseOnNewLine; + } + + public boolean elseOnNewLine() { + return elseOnNewLine; + } + + public static IfStatementFormattingOptions.IfStatementFormattingOptionsBuilder builder() { + return new IfStatementFormattingOptionsBuilder(); + } + + public static class IfStatementFormattingOptionsBuilder { + + private boolean elseOnNewLine = false; + + public IfStatementFormattingOptionsBuilder setElseOnNewLine(boolean elseOnNewLine) { + this.elseOnNewLine = elseOnNewLine; + return this; + } + + public IfStatementFormattingOptions build() { + return new IfStatementFormattingOptions(elseOnNewLine); + } + + public IfStatementFormattingOptions build(Map configs) { + for (Map.Entry ifStatementEntry : configs.entrySet()) { + String ifStatementKey = ifStatementEntry.getKey(); + switch (ifStatementKey) { + case "elseOnNewLine": + setElseOnNewLine((Boolean) ifStatementEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java similarity index 94% rename from misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ImportFormattingOptions.java rename to misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index c10f7ea9adf5..c645f190b736 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ballerinalang.formatter.core; +package org.ballerinalang.formatter.core.options; /** * A model for formatting and optimizing imports by the API user, that could be passed onto the formatter. @@ -21,6 +21,7 @@ * @since 2201.8.0 */ public class ImportFormattingOptions { + private boolean groupImports; private boolean sortImports; private boolean removeUnusedImports; @@ -31,11 +32,11 @@ private ImportFormattingOptions(boolean groupImports, boolean sortImports, boole this.removeUnusedImports = removeUnusedImports; } - public boolean getGroupImports() { + public boolean groupImports() { return groupImports; } - public boolean getSortImports() { + public boolean sortImports() { return sortImports; } @@ -51,6 +52,7 @@ public static ImportFormattingOptions.ImportFormattingOptionsBuilder builder() { * A builder for the {@code ImportFormattingOptions}. */ public static class ImportFormattingOptionsBuilder { + private boolean groupImports = true; private boolean sortImports = true; private boolean removeUnusedImports = false; @@ -62,7 +64,7 @@ public ImportFormattingOptions.ImportFormattingOptionsBuilder setGroupImports(bo public ImportFormattingOptions.ImportFormattingOptionsBuilder setSortImports(boolean sortImports) { this.sortImports = sortImports; - return this; + return this; } public ImportFormattingOptions.ImportFormattingOptionsBuilder setRemoveUnusedImports( diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java new file mode 100644 index 000000000000..8302ca3c2425 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import java.util.Map; + +/** + * A model for formatting of indent settings by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class IndentFormattingOptions { + private final int indentSize; + private final int continuationIndentSize; + private final String wsCharacter; + + + public IndentFormattingOptions(int indentSize, int continuationIndentSize, String wsCharacter) { + this.indentSize = indentSize; + this.continuationIndentSize = continuationIndentSize; + this.wsCharacter = wsCharacter; + } + + public int indentSize() { + return indentSize; + } + + public String wsCharacter() { + return wsCharacter; + } + + public int continuationIndentSize() { + return continuationIndentSize; + } + + public static IndentFormattingOptions.IndentFormattingOptionsBuilder builder() { + return new IndentFormattingOptionsBuilder(); + } + + /** + * A builder for the {@code IndentFormattingOptions}. + */ + public static class IndentFormattingOptionsBuilder { + private int indentSize = 4; + private int continuationIndentSize = 2; + private String wsCharacter = " "; + + public IndentFormattingOptionsBuilder setIndentSize(int indentSize) { + this.indentSize = indentSize; + return this; + } + + public IndentFormattingOptionsBuilder setContinuationIndentSize(int continuationIndentSize) { + this.continuationIndentSize = continuationIndentSize; + return this; + } + + public IndentFormattingOptions build() { + return new IndentFormattingOptions(indentSize, continuationIndentSize, wsCharacter); + } + + public IndentFormattingOptions build(Map configs) { + for (Map.Entry indentEntry : configs.entrySet()) { + String indentKey = indentEntry.getKey(); + switch (indentKey) { + case "indentSize": + setIndentSize(((Number) indentEntry.getValue()).intValue()); + break; + case "continuationIndentSize": + setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java new file mode 100644 index 000000000000..10a905acca7d --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import java.util.Map; + +/** + * A model for formatting of the queries by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class QueryFormattingOptions { + + private final boolean alignMultiLineQueries; + + public QueryFormattingOptions(boolean alignMultiLineQueries) { + this.alignMultiLineQueries = alignMultiLineQueries; + } + + public boolean alignMultiLineQueries() { + return alignMultiLineQueries; + } + + public static QueryFormattingOptions.QueryFormattingOptionsBuilder builder() { + return new QueryFormattingOptionsBuilder(); + } + + public static class QueryFormattingOptionsBuilder { + + private boolean alignMultiLineQueries = false; + + public QueryFormattingOptionsBuilder setAlignMultiLineQueries(boolean alignMultiLineQueries) { + this.alignMultiLineQueries = alignMultiLineQueries; + return this; + } + + public QueryFormattingOptions build() { + return new QueryFormattingOptions(alignMultiLineQueries); + } + + public QueryFormattingOptions build(Map configs) { + for (Map.Entry queryStatementEntry : configs.entrySet()) { + String queryStatementKey = queryStatementEntry.getKey(); + switch (queryStatementKey) { + case "alignMultiLineQueries": + setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java new file mode 100644 index 000000000000..65d412ffcb99 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import java.util.Map; + +/** + * A model for formatting of spacing by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class SpacingFormattingOptions { + + private final boolean afterTypeCast; + private final boolean aroundRecordBraces; + private final boolean alignConsecutiveDefinitions; + + public SpacingFormattingOptions(boolean afterTypeCast, boolean aroundRecordBraces, + boolean alignConsecutiveDefinitions) { + this.afterTypeCast = afterTypeCast; + this.aroundRecordBraces = aroundRecordBraces; + this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; + } + + public boolean afterTypeCast() { + return afterTypeCast; + } + + public boolean aroundRecordBraces() { + return aroundRecordBraces; + } + + public boolean alignConsecutiveDefinitions() { + return alignConsecutiveDefinitions; + } + + public static SpacingFormattingOptions.SpacingFormattingOptionsBuilder builder() { + return new SpacingFormattingOptionsBuilder(); + } + + public static class SpacingFormattingOptionsBuilder { + + private boolean afterTypeCast = false; + private boolean aroundRecordBraces = false; + private boolean alignConsecutiveDefinitions = false; + + public SpacingFormattingOptionsBuilder setAfterTypeCast(boolean afterTypeCast) { + this.afterTypeCast = afterTypeCast; + return this; + } + + public SpacingFormattingOptionsBuilder setAroundRecordBraces(boolean aroundRecordBraces) { + this.aroundRecordBraces = aroundRecordBraces; + return this; + } + + public SpacingFormattingOptionsBuilder setAlignConsecutiveDefinitions(boolean alignConsecutiveDefinitions) { + this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; + return this; + } + + public SpacingFormattingOptions build() { + return new SpacingFormattingOptions(afterTypeCast, aroundRecordBraces, alignConsecutiveDefinitions); + } + + public SpacingFormattingOptions build(Map configs) { + for (Map.Entry spacingEntry : configs.entrySet()) { + String spacingKey = spacingEntry.getKey(); + switch (spacingKey) { + case "afterTypeCast": + setAfterTypeCast((Boolean) spacingEntry.getValue()); + break; + case "aroundRecordBraces": + setAroundRecordBraces((Boolean) spacingEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java new file mode 100644 index 000000000000..e62e6957bbd7 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import java.util.Map; + +/** + * A model for formatting of wrapping settings by the API user, that could be passed onto the formatter. + * + * @since 2201.8.0 + */ +public class WrappingFormattingOptions { + + private final int maxLineLength; + private final boolean lineWrap; + private final boolean multipleExpressionsInOneLine; + private final boolean keepLineBreaks; + private final boolean simpleBlocksInOneLine; + private final boolean simpleMethodsInOneLine; + + public WrappingFormattingOptions(int maxLineLength, boolean lineWrap, boolean multipleExpressionsInOneLine, + boolean keepLineBreaks, boolean simpleBlocksInOneLine, + boolean simpleMethodsInOneLine) { + this.maxLineLength = maxLineLength; + this.lineWrap = lineWrap; + this.multipleExpressionsInOneLine = multipleExpressionsInOneLine; + this.keepLineBreaks = keepLineBreaks; + this.simpleBlocksInOneLine = simpleBlocksInOneLine; + this.simpleMethodsInOneLine = simpleMethodsInOneLine; + } + + public int maxLineLength() { + return maxLineLength; + } + + public boolean isMultipleExpressionsInOneLine() { + return multipleExpressionsInOneLine; + } + + public boolean isKeepLineBreaks() { + return keepLineBreaks; + } + + public boolean isSimpleBlocksInOneLine() { + return simpleBlocksInOneLine; + } + + public boolean isSimpleMethodsInOneLine() { + return simpleMethodsInOneLine; + } + + public boolean lineWrap() { + return lineWrap; + } + + public static WrappingFormattingOptions.WrappingFormattingOptionsBuilder builder() { + return new WrappingFormattingOptionsBuilder(); + } + + public static class WrappingFormattingOptionsBuilder { + + private int maxLineLength = 120; + private boolean multipleExpressionsInOneLine = false; + private boolean keepLineBreaks = true; + private boolean simpleBlocksInOneLine = false; + private boolean simpleMethodsInOneLine = false; + private boolean lineWrap = false; + + public WrappingFormattingOptionsBuilder setMaxLineLength(int maxLineLength) { + this.maxLineLength = maxLineLength; + return this; + } + + public WrappingFormattingOptionsBuilder setMultipleExpressionsInOneLine(boolean multipleExpressionsInOneLine) { + this.multipleExpressionsInOneLine = multipleExpressionsInOneLine; + return this; + } + + public WrappingFormattingOptionsBuilder setKeepLineBreaks(boolean keepLineBreaks) { + this.keepLineBreaks = keepLineBreaks; + return this; + } + + public WrappingFormattingOptionsBuilder setSimpleBlocksInOneLine(boolean simpleBlocksInOneLine) { + this.simpleBlocksInOneLine = simpleBlocksInOneLine; + return this; + } + + public WrappingFormattingOptionsBuilder setLineWrap(boolean lineWrap) { + this.lineWrap = lineWrap; + return this; + } + + public WrappingFormattingOptionsBuilder setSimpleMethodsInOneLine(boolean simpleMethodsInOneLine) { + this.simpleMethodsInOneLine = simpleMethodsInOneLine; + return this; + } + + public WrappingFormattingOptions build() { + return new WrappingFormattingOptions(maxLineLength, lineWrap, multipleExpressionsInOneLine, + keepLineBreaks, simpleBlocksInOneLine, simpleMethodsInOneLine); + } + + public WrappingFormattingOptions build(Map configs) { + for (Map.Entry wrappingEntry : configs.entrySet()) { + String wrappingKey = wrappingEntry.getKey(); + switch (wrappingKey) { + case "maxLineLength": + setMaxLineLength(((Number) wrappingEntry.getValue()).intValue()); + setLineWrap(true); + break; + case "multipleExpressionsInOneLine": + setMultipleExpressionsInOneLine((Boolean) wrappingEntry.getValue()); + break; + case "keepLineBreaks": + setKeepLineBreaks((Boolean) wrappingEntry.getValue()); + break; + case "simpleBlocksInOneLine": + setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); + break; + case "simpleMethodsInOneLine": + setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); + break; + default: + break; + } + } + return build(); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java new file mode 100644 index 000000000000..16cb3b0c80e2 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -0,0 +1,17 @@ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +public enum WrappingMethod { + CHOPDOWN, + WRAP, + NOWRAP; + + public static WrappingMethod fromString(String value) throws FormatterException { + try { + return WrappingMethod.valueOf(value); + } catch (IllegalArgumentException e) { + throw new FormatterException("Invalid WrappingMethod: " + value); + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java index f245a62a92be..f2b08518d78a 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java @@ -20,6 +20,8 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; +import org.ballerinalang.formatter.core.options.FormattingOptions; +import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -74,8 +76,8 @@ public void testWithOptions(String source, String sourcePath) throws IOException String content = getSourceText(sourceFilePath); TextDocument textDocument = TextDocuments.from(content); SyntaxTree syntaxTree = SyntaxTree.from(textDocument); - FormattingOptions formattingOptions = - FormattingOptions.builder().setLineWrapping(true).setColumnLimit(120).build(); + FormattingOptions formattingOptions = FormattingOptions.builder().setWrappingFormattingOptions( + WrappingFormattingOptions.builder().setMaxLineLength(120).setLineWrap(true).build()).build(); try { SyntaxTree newSyntaxTree = Formatter.format(syntaxTree, formattingOptions); Assert.assertEquals(newSyntaxTree.toSourceCode(), getSourceText(assertFilePath)); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java index ad19a1c53d7d..a53dbffa8290 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/declarations/ImportDeclarationsTest.java @@ -16,8 +16,8 @@ package org.ballerinalang.formatter.core.declarations; import org.ballerinalang.formatter.core.FormatterTest; -import org.ballerinalang.formatter.core.FormattingOptions; -import org.ballerinalang.formatter.core.ImportFormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; +import org.ballerinalang.formatter.core.options.ImportFormattingOptions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java index 3ff8dbb28463..269e5c04cc80 100644 --- a/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java +++ b/misc/json-to-record-converter/src/main/java/io/ballerina/jsonmapper/JsonToRecordMapper.java @@ -47,10 +47,10 @@ import io.ballerina.jsonmapper.diagnostic.DiagnosticMessage; import io.ballerina.jsonmapper.diagnostic.DiagnosticUtils; import org.apache.commons.lang3.StringUtils; -import org.ballerinalang.formatter.core.ForceFormattingOptions; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; -import org.ballerinalang.formatter.core.FormattingOptions; +import org.ballerinalang.formatter.core.options.ForceFormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; import org.ballerinalang.langserver.commons.workspace.WorkspaceManager; import org.javatuples.Pair; diff --git a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java index 9733c285c61d..d2efad2a97c9 100644 --- a/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java +++ b/misc/ls-extensions/modules/json-to-record-converter/src/main/java/io/ballerina/converters/JsonToRecordConverter.java @@ -49,10 +49,10 @@ import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.parser.core.models.SwaggerParseResult; import org.apache.commons.lang3.StringUtils; -import org.ballerinalang.formatter.core.ForceFormattingOptions; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; -import org.ballerinalang.formatter.core.FormattingOptions; +import org.ballerinalang.formatter.core.options.ForceFormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; import java.io.IOException; import java.util.ArrayList; diff --git a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java index 8112eb446e55..ffe791123b64 100644 --- a/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java +++ b/misc/xml-to-record-converter/src/main/java/io/ballerina/xmltorecordconverter/XMLToRecordConverter.java @@ -47,10 +47,10 @@ import io.ballerina.xmltorecordconverter.diagnostic.DiagnosticMessage; import io.ballerina.xmltorecordconverter.diagnostic.DiagnosticUtils; import org.apache.commons.lang3.StringUtils; -import org.ballerinalang.formatter.core.ForceFormattingOptions; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; -import org.ballerinalang.formatter.core.FormattingOptions; +import org.ballerinalang.formatter.core.options.ForceFormattingOptions; +import org.ballerinalang.formatter.core.options.FormattingOptions; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; From 634e0e3c847d6d23541d0479ef182c31087054d7 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Tue, 3 Oct 2023 10:00:46 +0530 Subject: [PATCH 07/22] Add caching of remote file --- .../main/resources/ballerina-toml-schema.json | 58 +----------------- .../BallerinaTextDocumentService.java | 2 +- .../formatting/project/Ballerina.toml | 12 +--- .../resources/formatting/project/Format.toml | 13 ++++ .../formatting/projectExpected/main.bal | 6 +- .../config/table_array_context/config1.json | 21 ------- .../config/table_context/config1.json | 21 ------- .../config/table_context/config2.json | 21 ------- .../formatter/cli/FormatUtil.java | 5 +- .../brace/source/project/Format.toml | 4 +- .../functionCall/source/chopDown/Format.toml | 2 +- .../functionCall/source/noWrap/Format.toml | 2 +- .../functionCall/source/wrap/Format.toml | 2 +- .../source/chopDown/Format.toml | 2 +- .../source/noWrap/Format.toml | 2 +- .../source/wrap/Format.toml | 2 +- .../formatter-core/spotbugs-exclude.xml | 4 +- .../formatter/core/FormatterUtils.java | 38 +++++++++++- .../core/FormattingTreeModifier.java | 12 ++-- .../core/options/BraceFormattingOptions.java | 7 ++- .../formatter/core/options/BraceStyle.java | 4 +- .../core/options/FormattingOptions.java | 60 ++++++++++++++----- .../FunctionCallFormattingOptions.java | 6 +- .../FunctionDeclFormattingOptions.java | 6 +- .../options/IfStatementFormattingOptions.java | 2 +- .../core/options/ImportFormattingOptions.java | 19 ++++++ .../core/options/IndentFormattingOptions.java | 5 +- .../core/options/QueryFormattingOptions.java | 2 +- .../options/SpacingFormattingOptions.java | 7 ++- .../options/WrappingFormattingOptions.java | 39 ++---------- .../core/options/WrappingMethod.java | 8 +-- 31 files changed, 166 insertions(+), 228 deletions(-) create mode 100644 language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml diff --git a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json index cd093532cef0..177c47cb0c65 100644 --- a/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json +++ b/compiler/ballerina-lang/src/main/resources/ballerina-toml-schema.json @@ -356,62 +356,8 @@ "type": "object", "additionalProperties": true, "properties": { - "alignConsecutiveDefinitions": { - "type": "boolean" - }, - "columnLimit": { - "type": "integer" - }, - "recordBraceSpacing": { - "type": "boolean" - }, - "tabWidth": { - "type": "integer" - }, - "block": { - "type": "object", - "additionalProperties": true, - "properties": { - "allowShortBlocksOnASingleLine": { - "type": "boolean" - }, - "allowShortMatchLabelsOnASingleLine": { - "type": "boolean" - }, - "allowShortIfStatementsOnASingleLine": { - "type": "boolean" - }, - "allowShortLoopsOnASingleLine": { - "type": "boolean" - }, - "elseBlocksOnANewLine": { - "type": "boolean" - } - } - }, - "function": { - "type": "object", - "additionalProperties": true, - "properties": { - "oneArgPerLine": { - "type": "boolean" - }, - "paranAlign": { - "type": "boolean" - } - } - }, - "import": { - "type": "object", - "additionalProperties": true, - "properties": { - "groupImports": { - "type": "boolean" - }, - "sortImports": { - "type": "boolean" - } - } + "configPath": { + "type": "string" } } } diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index 85cfd7b2dba8..4f1dac4fea3a 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -449,7 +449,7 @@ public CompletableFuture> formatting(DocumentFormatting Path rootPath = context.workspace().projectRoot(context.filePath()); BuildProject project = BuildProject.load(rootPath, BuildOptions.builder().build()); FormattingOptions options = FormattingOptions.builder() - .build(project.currentPackage().manifest().getValue("format")); + .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); formattedSource = Formatter.format(syntaxTree.get(), options).toSourceCode(); } else { formattedSource = Formatter.format(syntaxTree.get()).toSourceCode(); diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml index 04ab55c5f850..351f71b60982 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml @@ -1,12 +1,2 @@ [format] -columnLimit = 80 -tabWidth = 2 -recordBraceSpacing = true - -[format.function] -oneArgPerLine = false -paranAlign = true - -[format.block] -allowShortMatchLabelsOnASingleLine = true -elseBlocksOnANewLine = true +configPath = "src/test/resources/formatting/project/Format.toml" diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml new file mode 100644 index 000000000000..f310175dab69 --- /dev/null +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml @@ -0,0 +1,13 @@ +[indent] +indentSize = 2 + +[wrapping] +maxLineLength = 80 +simpleBlocksInOneLine = true +simpleMethodsInOneLine = true + +[methodDeclaration] +alignMultilineParameters = true + +[ifStatement] +elseOnNewLine = true diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal b/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal index 73cd652fd302..089e4fffa5fc 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal +++ b/language-server/modules/langserver-core/src/test/resources/formatting/projectExpected/main.bal @@ -1,5 +1,5 @@ function getDateFormatIncludingDayName(string year, int month, int day, - int dayNumber) returns string { + int dayNumber) returns string { string? text = (); match dayNumber { 1 => { text = "Sunday"; } @@ -13,7 +13,5 @@ function getDateFormatIncludingDayName(string year, int month, int day, if text !is () { return string `${year} ${month} ${text} ${day}`; } - else { - return string `${year} ${month} ${day}`; - } + else { return string `${year} ${month} ${day}`; } } diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json index b52f405b033a..e02de0000d0d 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_array_context/config1.json @@ -99,27 +99,6 @@ "detail": "Table", "sortText": "C", "insertText": "[format]" - }, - { - "label": "format.function", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.function]" - }, - { - "label": "format.import", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.import]" - }, - { - "label": "format.block", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.block]" } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json index 37d4a6e08445..b51eaa85c8d0 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config1.json @@ -120,27 +120,6 @@ "detail": "Table", "sortText": "C", "insertText": "[format]" - }, - { - "label": "format.function", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.function]" - }, - { - "label": "format.import", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.import]" - }, - { - "label": "format.block", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.block]" } ] } diff --git a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json index c0bbe33d33a4..c9f8c0ac3bd2 100644 --- a/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json +++ b/language-server/modules/langserver-core/src/test/resources/toml/ballerina_toml/completion/config/table_context/config2.json @@ -120,27 +120,6 @@ "detail": "Table", "sortText": "C", "insertText": "[format]" - }, - { - "label": "format.function", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.function]" - }, - { - "label": "format.import", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.import]" - }, - { - "label": "format.block", - "kind": "Snippet", - "detail": "Table", - "sortText": "C", - "insertText": "[format.block]" } ] } diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index ae9ffa7a1d33..9e6d9f24a96b 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -128,7 +128,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S try { project = BuildProject.load(projectPath, constructBuildOptions()); options = FormattingOptions.builder() - .build(project.currentPackage().manifest().getValue("format")); + .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -195,7 +195,8 @@ static void execute(List argList, boolean helpFlag, String moduleName, S FormattingOptions options; try { project = BuildProject.load(sourceRootPath, constructBuildOptions()); - options = FormattingOptions.builder().build(project.currentPackage().manifest().getValue("format")); + options = FormattingOptions.builder() + .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml index 2158b8c5afa9..c02a9e0e7ee2 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml @@ -1,3 +1,3 @@ [braces] -classBraceStyle = "NEWLINE" -methodBraceStyle = "NEWLINE" \ No newline at end of file +classBraceStyle = "NewLine" +methodBraceStyle = "NewLine" \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml index b4e91caf722c..0ac337ea0792 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml @@ -1,5 +1,5 @@ [methodCall] -parametersWrap = "CHOPDOWN" +parametersWrap = "ChopDown" alignMultilineParameters = true newLineAfterLeftParen = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml index 4443d793f996..fb4a25f74855 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml @@ -1,5 +1,5 @@ [methodCall] -parametersWrap = "NOWRAP" +parametersWrap = "NoWrap" newLineAfterLeftParen = true [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml index 062102291729..4dba90f4845b 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml @@ -1,5 +1,5 @@ [methodCall] -parametersWrap = "WRAP" +parametersWrap = "Wrap" alignMultilineParameters = true newLineAfterLeftParen = true rightParenOnNewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml index e35dc616dafb..0f87c05238a3 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml @@ -1,5 +1,5 @@ [methodDeclaration] -parametersWrap = "CHOPDOWN" +parametersWrap = "ChopDown" alignMultilineParameters = true [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml index 318ca73b7bfd..57909e17a020 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml @@ -1,5 +1,5 @@ [methodDeclaration] -parametersWrap = "NOWRAP" +parametersWrap = "NoWrap" [wrapping] maxLineLength = 80 \ No newline at end of file diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml index 52f7b162002b..80759d993a12 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml @@ -1,5 +1,5 @@ [methodDeclaration] -parametersWrap = "WRAP" +parametersWrap = "Wrap" alignMultilineParameters = true newLineAfterLeftParen = true rightParenOnNewLine = true diff --git a/misc/formatter/modules/formatter-core/spotbugs-exclude.xml b/misc/formatter/modules/formatter-core/spotbugs-exclude.xml index 3f0f4acbb145..0879ed47ef5b 100644 --- a/misc/formatter/modules/formatter-core/spotbugs-exclude.xml +++ b/misc/formatter/modules/formatter-core/spotbugs-exclude.xml @@ -17,7 +17,7 @@ --> - - + + diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 63e9fb65cf08..9d7c6312b762 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -31,7 +31,9 @@ import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -55,7 +57,7 @@ private FormatterUtils() { static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); - public static Map getFormattingConfigurations(String path) throws FormatterException { + public static Map getFormattingConfigurations(Path root, String path) throws FormatterException { String content; if (isLocalFile(path)) { try { @@ -64,7 +66,7 @@ public static Map getFormattingConfigurations(String path) throw throw new FormatterException("Failed to retrieve local formatting configuration file"); } } else { - content = readRemoteFormatFile(path); + content = readRemoteFormatFile(root, path); } TomlDocument document = TomlDocument.from(path, content); @@ -84,8 +86,17 @@ public static boolean isLocalFile(String path) { return new File(path).exists(); } - static String readRemoteFormatFile(String fileUrl) throws FormatterException { + static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { StringBuilder fileContent = new StringBuilder(); + Path cachePath = root.resolve("target").resolve("format").resolve("Format.toml"); + + if (Files.exists(cachePath)) { + try { + return Files.readString(cachePath, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new FormatterException("Failed to read cached formatting configuration file"); + } + } try { URL url = new URL(fileUrl); @@ -108,9 +119,30 @@ static String readRemoteFormatFile(String fileUrl) throws FormatterException { } catch (IOException e) { throw new FormatterException("Failed to retrieve remote formatting configuration file"); } + cacheRemoteConfigurationFile(root, fileContent.toString()); + return fileContent.toString(); } + private static void cacheRemoteConfigurationFile(Path root, String content) throws FormatterException { + if (Files.exists(root.resolve("target"))) { + if (!Files.exists(root.resolve("target").resolve("format"))) { + try { + Files.createDirectories(root.resolve("target").resolve("format")); + } catch (IOException e) { + throw new FormatterException("Failed to create format configuration cache directory"); + } + } + String filePath = root.resolve("target").resolve("format").resolve("Format.toml") + .toString(); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, StandardCharsets.UTF_8))) { + writer.write(content); + } catch (IOException e) { + throw new FormatterException("Failed to write format configuration cache file"); + } + } + } + static boolean isInlineRange(Node node, LineRange lineRange) { if (lineRange == null) { return true; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 67fd4bdf537e..eb99ac73ac2e 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -323,7 +323,7 @@ public FunctionDefinitionNode transform(FunctionDefinitionNode functionDefinitio functionName = formatToken(functionDefinitionNode.functionName(), 1, 0); } NodeList relativeResourcePath = formatNodeList(functionDefinitionNode.relativeResourcePath(), 0, 0, 0, 0); - int trailingNL = options.braceFormattingOptions().methodBraceStyle() == BraceStyle.NEWLINE ? 1 : 0; + int trailingNL = options.braceFormattingOptions().methodBraceStyle() == BraceStyle.NewLine ? 1 : 0; FunctionSignatureNode functionSignatureNode = formatNode(functionDefinitionNode.functionSignature(), 1 - trailingNL, trailingNL); @@ -388,7 +388,7 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo } Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); - boolean oneArgPerLine = funcOptions.parametersWrap() == WrappingMethod.CHOPDOWN; + boolean oneArgPerLine = funcOptions.parametersWrap() == WrappingMethod.ChopDown; int closeParenLeadingNL = funcOptions.rightParenOnNewLine() ? 1 : 0; SeparatedNodeList parameters = formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, @@ -1106,7 +1106,7 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, callOptions.newLineAfterLeftParen() ? 1 : 0); - boolean oneArgPerLine = callOptions.parametersWrap() == WrappingMethod.CHOPDOWN; + boolean oneArgPerLine = callOptions.parametersWrap() == WrappingMethod.ChopDown; int closeParenLeadingNL = callOptions.rightParenOnNewLine() ? 1 : 0; SeparatedNodeList arguments = formatSeparatedNodeList(functionCallExpressionNode.arguments(), 0, 0, oneArgPerLine ? 0 : 1, @@ -3535,7 +3535,7 @@ public ClassDefinitionNode transform(ClassDefinitionNode classDefinitionNode) { Token visibilityQualifier = formatToken(classDefinitionNode.visibilityQualifier().orElse(null), 1, 0); NodeList classTypeQualifiers = formatNodeList(classDefinitionNode.classTypeQualifiers(), 1, 0, 1, 0); Token classKeyword = formatToken(classDefinitionNode.classKeyword(), 1, 0); - int trailingNL = options.braceFormattingOptions().classBraceStyle() == BraceStyle.NEWLINE ? 1 : 0; + int trailingNL = options.braceFormattingOptions().classBraceStyle() == BraceStyle.NewLine ? 1 : 0; Token className = formatToken(classDefinitionNode.className(), 1 - trailingNL, trailingNL); Token openBrace = formatToken(classDefinitionNode.openBrace(), 0, 1); @@ -4280,7 +4280,7 @@ private boolean shouldWrapLine(Node node, Node parent) { case REQUIRED_PARAM: case REST_PARAM: case RETURN_TYPE_DESCRIPTOR: - if (options.functionDeclFormattingOptions().parametersWrap() == WrappingMethod.NOWRAP) { + if (options.functionDeclFormattingOptions().parametersWrap() == WrappingMethod.NoWrap) { return false; } return true; @@ -4289,7 +4289,7 @@ private boolean shouldWrapLine(Node node, Node parent) { case POSITIONAL_ARG: case NAMED_ARG: case REST_ARG: - if (options.functionCallFormattingOptions().parametersWrap() == WrappingMethod.NOWRAP) { + if (options.functionCallFormattingOptions().parametersWrap() == WrappingMethod.NoWrap) { return false; } return true; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 74ced3ff74b8..34e54f06cae7 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -25,10 +25,11 @@ * @since 2201.8.0 */ public class BraceFormattingOptions { + private final BraceStyle classBraceStyle; private final BraceStyle methodBraceStyle; - public BraceFormattingOptions(BraceStyle classBraceStyle, BraceStyle methodBraceStyle) { + private BraceFormattingOptions(BraceStyle classBraceStyle, BraceStyle methodBraceStyle) { this.classBraceStyle = classBraceStyle; this.methodBraceStyle = methodBraceStyle; } @@ -47,8 +48,8 @@ public static BraceFormattingOptions.BraceFormattingOptionsBuilder builder() { public static class BraceFormattingOptionsBuilder { - private BraceStyle classBraceStyle = BraceStyle.ENDOFLINE; - private BraceStyle methodBraceStyle = BraceStyle.ENDOFLINE; + private BraceStyle classBraceStyle = BraceStyle.EndOfLine; + private BraceStyle methodBraceStyle = BraceStyle.EndOfLine; public BraceFormattingOptionsBuilder setClassBraceStyle(BraceStyle classBraceStyle) { this.classBraceStyle = classBraceStyle; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index 32c8d20734ae..57c4827387cf 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -3,8 +3,8 @@ import org.ballerinalang.formatter.core.FormatterException; public enum BraceStyle { - NEWLINE, - ENDOFLINE; + NewLine, + EndOfLine; public static BraceStyle fromString(String value) throws FormatterException { try { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index c4d13613a321..786acc10ded8 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -17,6 +17,7 @@ import org.ballerinalang.formatter.core.FormatterException; +import java.nio.file.Path; import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; @@ -37,16 +38,16 @@ public class FormattingOptions { private ImportFormattingOptions importFormattingOptions; private QueryFormattingOptions queryFormattingOptions; - public FormattingOptions(IndentFormattingOptions indentFormattingOptions, - WrappingFormattingOptions wrappingFormattingOptions, - BraceFormattingOptions braceFormattingOptions, - FunctionDeclFormattingOptions functionDeclFormattingOptions, - FunctionCallFormattingOptions functionCallFormattingOptions, - IfStatementFormattingOptions ifStatementFormattingOptions, - SpacingFormattingOptions spacingFormattingOptions, - ForceFormattingOptions forceFormattingOptions, - ImportFormattingOptions importFormattingOptions, - QueryFormattingOptions queryFormattingOptions) { + private FormattingOptions(IndentFormattingOptions indentFormattingOptions, + WrappingFormattingOptions wrappingFormattingOptions, + BraceFormattingOptions braceFormattingOptions, + FunctionDeclFormattingOptions functionDeclFormattingOptions, + FunctionCallFormattingOptions functionCallFormattingOptions, + IfStatementFormattingOptions ifStatementFormattingOptions, + SpacingFormattingOptions spacingFormattingOptions, + ForceFormattingOptions forceFormattingOptions, + ImportFormattingOptions importFormattingOptions, + QueryFormattingOptions queryFormattingOptions) { this.indentFormattingOptions = indentFormattingOptions; this.wrappingFormattingOptions = wrappingFormattingOptions; this.braceFormattingOptions = braceFormattingOptions; @@ -110,6 +111,10 @@ public static FormattingOptionsBuilder builder() { */ public static class FormattingOptionsBuilder { + private int tabSize = 4; + private String wsCharacter = " "; + private int columnLimit = 120; + private boolean lineWrapping = false; private IndentFormattingOptions indentFormattingOptions = IndentFormattingOptions.builder().build(); private WrappingFormattingOptions wrappingFormattingOptions = WrappingFormattingOptions.builder().build(); private BraceFormattingOptions braceFormattingOptions = BraceFormattingOptions.builder().build(); @@ -124,6 +129,30 @@ public static class FormattingOptionsBuilder { private QueryFormattingOptions queryFormattingOptions = QueryFormattingOptions.builder().build(); private ForceFormattingOptions forceFormattingOptions = ForceFormattingOptions.builder().build(); + @Deprecated + public FormattingOptions.FormattingOptionsBuilder setTabSize(int tabSize) { + this.tabSize = tabSize; + return this; + } + + @Deprecated + public FormattingOptions.FormattingOptionsBuilder setWSCharacter(String wsCharacter) { + this.wsCharacter = wsCharacter; + return this; + } + + @Deprecated + public FormattingOptions.FormattingOptionsBuilder setColumnLimit(int columnLimit) { + this.columnLimit = columnLimit; + return this; + } + + @Deprecated + public FormattingOptions.FormattingOptionsBuilder setLineWrapping(boolean lineWrapping) { + this.lineWrapping = lineWrapping; + return this; + } + public FormattingOptionsBuilder setForceFormattingOptions(ForceFormattingOptions forceFormattingOptions) { this.forceFormattingOptions = forceFormattingOptions; return this; @@ -146,7 +175,7 @@ public FormattingOptions build() { spacingFormattingOptions, forceFormattingOptions, importFormattingOptions, queryFormattingOptions); } - public FormattingOptions build(Object data) throws FormatterException { + public FormattingOptions build(Path root, Object data) throws FormatterException { if (!(data instanceof Map)) { return build(); } @@ -155,7 +184,7 @@ public FormattingOptions build(Object data) throws FormatterException { if (path == null) { return build(); } - Map configurations = getFormattingConfigurations((String) path.toString()); + Map configurations = getFormattingConfigurations(root, path.toString()); for (Map.Entry entry : configurations.entrySet()) { String key = entry.getKey(); @@ -189,14 +218,13 @@ public FormattingOptions build(Object data) throws FormatterException { case "spacing": spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); break; -// case "import": -// importFormattingOptions = ImportFormattingOptions.builder().build(configs); -// break; + case "import": + importFormattingOptions = ImportFormattingOptions.builder().build(configs); + break; default: break; } } - return build(); } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index a7b30de81c06..a827a206b185 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -31,8 +31,8 @@ public class FunctionCallFormattingOptions { private final boolean newLineAfterLeftParen; private final boolean rightParenOnNewLine; - public FunctionCallFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, - boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { + private FunctionCallFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { this.parametersWrap = parametersWrap; this.alignMultilineParameters = alignMultilineParameters; this.newLineAfterLeftParen = newLineAfterLeftParen; @@ -64,7 +64,7 @@ public static FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder */ public static class FunctionCallFormattingOptionsBuilder { - private WrappingMethod parametersWrap = WrappingMethod.WRAP; + private WrappingMethod parametersWrap = WrappingMethod.Wrap; private boolean alignMultilineParameters = false; private boolean newLineAfterLeftParen = false; private boolean rightParenOnNewLine = false; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index 944fe8f5d8a8..6b7990a7b553 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -31,8 +31,8 @@ public class FunctionDeclFormattingOptions { private final boolean newLineAfterLeftParen; private final boolean rightParenOnNewLine; - public FunctionDeclFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, - boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { + private FunctionDeclFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { this.parametersWrap = parametersWrap; this.alignMultilineParameters = alignMultilineParameters; this.newLineAfterLeftParen = newLineAfterLeftParen; @@ -61,7 +61,7 @@ public static FunctionDeclFormattingOptionsBuilder builder() { public static class FunctionDeclFormattingOptionsBuilder { - private WrappingMethod parametersWrap = WrappingMethod.WRAP; + private WrappingMethod parametersWrap = WrappingMethod.Wrap; private boolean alignMultilineParameters = false; private boolean newLineAfterLeftParen = false; private boolean rightParenOnNewLine = false; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index 63e9ab3b282e..5fa6ddcadb1b 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -26,7 +26,7 @@ public class IfStatementFormattingOptions { private final boolean elseOnNewLine; - public IfStatementFormattingOptions(boolean elseOnNewLine) { + private IfStatementFormattingOptions(boolean elseOnNewLine) { this.elseOnNewLine = elseOnNewLine; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index c645f190b736..fea6d9055c17 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import java.util.Map; + /** * A model for formatting and optimizing imports by the API user, that could be passed onto the formatter. * @@ -76,5 +78,22 @@ public ImportFormattingOptions.ImportFormattingOptionsBuilder setRemoveUnusedImp public ImportFormattingOptions build() { return new ImportFormattingOptions(groupImports, sortImports, removeUnusedImports); } + + public ImportFormattingOptions build(Map configs) { + for (Map.Entry importEntry : configs.entrySet()) { + String ifStatementKey = importEntry.getKey(); + switch (ifStatementKey) { + case "sortImports": + setSortImports((Boolean) importEntry.getValue()); + break; + case "groupImports": + setGroupImports((Boolean) importEntry.getValue()); + break; + default: + break; + } + } + return build(); + } } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index 8302ca3c2425..9ff949b08301 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -23,12 +23,12 @@ * @since 2201.8.0 */ public class IndentFormattingOptions { + private final int indentSize; private final int continuationIndentSize; private final String wsCharacter; - - public IndentFormattingOptions(int indentSize, int continuationIndentSize, String wsCharacter) { + private IndentFormattingOptions(int indentSize, int continuationIndentSize, String wsCharacter) { this.indentSize = indentSize; this.continuationIndentSize = continuationIndentSize; this.wsCharacter = wsCharacter; @@ -54,6 +54,7 @@ public static IndentFormattingOptions.IndentFormattingOptionsBuilder builder() { * A builder for the {@code IndentFormattingOptions}. */ public static class IndentFormattingOptionsBuilder { + private int indentSize = 4; private int continuationIndentSize = 2; private String wsCharacter = " "; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index 10a905acca7d..4c4f7d99542b 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -26,7 +26,7 @@ public class QueryFormattingOptions { private final boolean alignMultiLineQueries; - public QueryFormattingOptions(boolean alignMultiLineQueries) { + private QueryFormattingOptions(boolean alignMultiLineQueries) { this.alignMultiLineQueries = alignMultiLineQueries; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 65d412ffcb99..d29ee4659042 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -28,8 +28,8 @@ public class SpacingFormattingOptions { private final boolean aroundRecordBraces; private final boolean alignConsecutiveDefinitions; - public SpacingFormattingOptions(boolean afterTypeCast, boolean aroundRecordBraces, - boolean alignConsecutiveDefinitions) { + private SpacingFormattingOptions(boolean afterTypeCast, boolean aroundRecordBraces, + boolean alignConsecutiveDefinitions) { this.afterTypeCast = afterTypeCast; this.aroundRecordBraces = aroundRecordBraces; this.alignConsecutiveDefinitions = alignConsecutiveDefinitions; @@ -86,6 +86,9 @@ public SpacingFormattingOptions build(Map configs) { case "aroundRecordBraces": setAroundRecordBraces((Boolean) spacingEntry.getValue()); break; + case "alignConsecutiveDefinitions": + setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); + break; default: break; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index e62e6957bbd7..bdb697528357 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -26,18 +26,13 @@ public class WrappingFormattingOptions { private final int maxLineLength; private final boolean lineWrap; - private final boolean multipleExpressionsInOneLine; - private final boolean keepLineBreaks; private final boolean simpleBlocksInOneLine; private final boolean simpleMethodsInOneLine; - public WrappingFormattingOptions(int maxLineLength, boolean lineWrap, boolean multipleExpressionsInOneLine, - boolean keepLineBreaks, boolean simpleBlocksInOneLine, - boolean simpleMethodsInOneLine) { + private WrappingFormattingOptions(int maxLineLength, boolean lineWrap, boolean simpleBlocksInOneLine, + boolean simpleMethodsInOneLine) { this.maxLineLength = maxLineLength; this.lineWrap = lineWrap; - this.multipleExpressionsInOneLine = multipleExpressionsInOneLine; - this.keepLineBreaks = keepLineBreaks; this.simpleBlocksInOneLine = simpleBlocksInOneLine; this.simpleMethodsInOneLine = simpleMethodsInOneLine; } @@ -46,14 +41,6 @@ public int maxLineLength() { return maxLineLength; } - public boolean isMultipleExpressionsInOneLine() { - return multipleExpressionsInOneLine; - } - - public boolean isKeepLineBreaks() { - return keepLineBreaks; - } - public boolean isSimpleBlocksInOneLine() { return simpleBlocksInOneLine; } @@ -73,8 +60,6 @@ public static WrappingFormattingOptions.WrappingFormattingOptionsBuilder builder public static class WrappingFormattingOptionsBuilder { private int maxLineLength = 120; - private boolean multipleExpressionsInOneLine = false; - private boolean keepLineBreaks = true; private boolean simpleBlocksInOneLine = false; private boolean simpleMethodsInOneLine = false; private boolean lineWrap = false; @@ -84,16 +69,6 @@ public WrappingFormattingOptionsBuilder setMaxLineLength(int maxLineLength) { return this; } - public WrappingFormattingOptionsBuilder setMultipleExpressionsInOneLine(boolean multipleExpressionsInOneLine) { - this.multipleExpressionsInOneLine = multipleExpressionsInOneLine; - return this; - } - - public WrappingFormattingOptionsBuilder setKeepLineBreaks(boolean keepLineBreaks) { - this.keepLineBreaks = keepLineBreaks; - return this; - } - public WrappingFormattingOptionsBuilder setSimpleBlocksInOneLine(boolean simpleBlocksInOneLine) { this.simpleBlocksInOneLine = simpleBlocksInOneLine; return this; @@ -110,8 +85,8 @@ public WrappingFormattingOptionsBuilder setSimpleMethodsInOneLine(boolean simple } public WrappingFormattingOptions build() { - return new WrappingFormattingOptions(maxLineLength, lineWrap, multipleExpressionsInOneLine, - keepLineBreaks, simpleBlocksInOneLine, simpleMethodsInOneLine); + return new WrappingFormattingOptions(maxLineLength, lineWrap, simpleBlocksInOneLine, + simpleMethodsInOneLine); } public WrappingFormattingOptions build(Map configs) { @@ -122,12 +97,6 @@ public WrappingFormattingOptions build(Map configs) { setMaxLineLength(((Number) wrappingEntry.getValue()).intValue()); setLineWrap(true); break; - case "multipleExpressionsInOneLine": - setMultipleExpressionsInOneLine((Boolean) wrappingEntry.getValue()); - break; - case "keepLineBreaks": - setKeepLineBreaks((Boolean) wrappingEntry.getValue()); - break; case "simpleBlocksInOneLine": setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); break; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index 16cb3b0c80e2..c0003e5c80dd 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -3,15 +3,15 @@ import org.ballerinalang.formatter.core.FormatterException; public enum WrappingMethod { - CHOPDOWN, - WRAP, - NOWRAP; + ChopDown, + Wrap, + NoWrap; public static WrappingMethod fromString(String value) throws FormatterException { try { return WrappingMethod.valueOf(value); } catch (IllegalArgumentException e) { - throw new FormatterException("Invalid WrappingMethod: " + value); + throw new FormatterException("Invalid wrapping method: " + value); } } } From 8093edd739faf5b69f4ed22e22540c897c557a45 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Thu, 5 Oct 2023 16:25:27 +0530 Subject: [PATCH 08/22] Add formatter core tests --- .../formatter/core/FormatterTest.java | 34 +++++++++++ .../LocalConfigurationTest.java | 60 +++++++++++++++++++ .../RemoteConfigurationTest.java | 59 ++++++++++++++++++ .../configurations/local/assert/main.bal | 27 +++++++++ .../local/source/Ballerina.toml | 2 + .../configurations/local/source/Format.toml | 12 ++++ .../configurations/local/source/main.bal | 27 +++++++++ .../configurations/remote/assert/main.bal | 27 +++++++++ .../remote/source/Ballerina.toml | 2 + .../configurations/remote/source/main.bal | 26 ++++++++ .../src/test/resources/testng.xml | 1 + 11 files changed, 277 insertions(+) create mode 100644 misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java create mode 100644 misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/assert/main.bal create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/main.bal diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java index f2b08518d78a..58f7f81c224c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java @@ -18,6 +18,9 @@ package org.ballerinalang.formatter.core; import io.ballerina.compiler.syntax.tree.SyntaxTree; +import io.ballerina.projects.TomlDocument; +import io.ballerina.projects.util.ProjectConstants; +import io.ballerina.toml.semantic.ast.TomlTableNode; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; import org.ballerinalang.formatter.core.options.FormattingOptions; @@ -33,7 +36,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * The abstract class that is extended by all formatting test classes. @@ -70,6 +75,35 @@ public void test(String source, String sourcePath) throws IOException { } } + public void testWithConfigurationFile(String source, String sourcePath) throws IOException, FormatterException { + Path assertFilePath = + Paths.get(resourceDirectory.toString(), sourcePath, ASSERT_DIR, source); + Path sourceDir = + Paths.get(resourceDirectory.toString(), sourcePath, SOURCE_DIR); + Path sourceFilePath = Paths.get(sourceDir.toString(), source); + Path tomlPath = Paths.get(sourceDir.toString(), ProjectConstants.BALLERINA_TOML); + String content = getSourceText(sourceFilePath); + TextDocument textDocument = TextDocuments.from(content); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); + String tomlContent = Files.readString(tomlPath); + TomlDocument ballerinaToml = TomlDocument.from(ProjectConstants.BALLERINA_TOML, tomlContent); + TomlTableNode tomlAstNode = ballerinaToml.toml().rootNode(); + Map formatConfigs = new HashMap<>(); + if (!tomlAstNode.entries().isEmpty()) { + Map tomlMap = ballerinaToml.toml().toMap(); + for (Map.Entry entry : tomlMap.entrySet()) { + formatConfigs.put(entry.getKey(), entry.getValue()); + } + } + FormattingOptions formattingOptions = FormattingOptions.builder().build(sourceDir, formatConfigs.get("format")); + try { + SyntaxTree newSyntaxTree = Formatter.format(syntaxTree, formattingOptions); + Assert.assertEquals(newSyntaxTree.toSourceCode(), getSourceText(assertFilePath)); + } catch (FormatterException e) { + Assert.fail(e.getMessage(), e); + } + } + public void testWithOptions(String source, String sourcePath) throws IOException { Path assertFilePath = Paths.get(resourceDirectory.toString(), sourcePath, ASSERT_DIR, source); Path sourceFilePath = Paths.get(resourceDirectory.toString(), sourcePath, SOURCE_DIR, source); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java new file mode 100644 index 000000000000..df97e0274897 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.configurations; + +import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; + +/** + * Test formatting with a local configuration file. + * + * @since 2.0.0 + */ +public class LocalConfigurationTest extends FormatterTest { + @Test(dataProvider = "test-file-provider") + public void test(String source, String sourcePath) throws IOException { + try { + super.testWithConfigurationFile(source, sourcePath); + } catch (FormatterException e) { + throw new RuntimeException(e); + } + } + + @DataProvider(name = "test-file-provider") + @Override + public Object[][] dataProvider() { + return this.getConfigsList(); + } + + @Override + public Object[][] testSubset() { + return new Object[][] { + {"main.bal", this.getTestResourceDir()} + }; + } + @Override + public String getTestResourceDir() { + Path path = Paths.get("configurations", "local"); + return path.toString(); + } +} + diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java new file mode 100644 index 000000000000..1ca343b34293 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.configurations; + +import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.nio.file.Paths; + +/** + * Test the formatting of additive expressions. + * + * @since 2.0.0 + */ +public class RemoteConfigurationTest extends FormatterTest { + + @Test(dataProvider = "test-file-provider") + public void test(String source, String sourcePath) throws IOException { + try { + super.testWithConfigurationFile(source, sourcePath); + } catch (FormatterException e) { + throw new RuntimeException(e); + } + } + + @DataProvider(name = "test-file-provider") + @Override + public Object[][] dataProvider() { + return this.getConfigsList(); + } + + @Override + public Object[][] testSubset() { + return new Object[][] { + {"main.bal", this.getTestResourceDir()} + }; + } + + @Override + public String getTestResourceDir() { + return Paths.get("configurations", "remote").toString(); + } +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal new file mode 100644 index 000000000000..f5e25fde52f7 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal @@ -0,0 +1,27 @@ +import ballerina/io; + +const int MAX_STUDENTS = 100; +const string WELCOME_MESSAGE = "Welcome"; +const int MAX_AGE = 20; + +type Employee record { + string firstName; + string lastName; + decimal score; +}; + +public function main() { + Employee[] employees = [ + { firstName: "Hayden", lastName: "Welsh", score: 1000.00 }, + { firstName: "John", lastName: "Frank", score: 5000.00 }, + { firstName: "Michael", lastName: "Wayne", score: 10000.00 }, + { firstName: "Tom", lastName: "Cruise", score: 2000.00 } + ]; + + Employee[] top3 = from var e in employees + order by e.salary descending + limit 3 + select e; + + foreach var emp in top3 { io:println(emp); } +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml new file mode 100644 index 000000000000..c12d157a7ac3 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/local/source/Format.toml" diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml new file mode 100644 index 000000000000..b6e9a1b6bd3e --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml @@ -0,0 +1,12 @@ +[indent] +indentSize = 2 + +[wrapping] +simpleBlocksInOneLine = true + +[spacing] +aroundRecordBraces = true +alignConsecutiveDefinitions = true + +[query] +alignMultiLineQueries = true \ No newline at end of file diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal new file mode 100644 index 000000000000..cc24aa2e6ca2 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal @@ -0,0 +1,27 @@ +import ballerina/io; + +const int MAX_STUDENTS = 100; +const string WELCOME_MESSAGE = "Welcome"; +const int MAX_AGE = 20; + +type Employee record { + string firstName; + string lastName; + decimal score; +}; + +public function main() { + Employee[] employees = [ + {firstName: "Hayden", lastName: "Welsh", score: 1000.00}, + {firstName: "John", lastName: "Frank", score: 5000.00}, + {firstName: "Michael", lastName: "Wayne", score: 10000.00}, + {firstName: "Tom", lastName: "Cruise", score: 2000.00} + ]; + + Employee[] top3 = from var e in employees + order by e.salary descending + limit 3 + select e; + + foreach var emp in top3 {io:println(emp);} +} \ No newline at end of file diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/assert/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/assert/main.bal new file mode 100644 index 000000000000..2c117339fa27 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/assert/main.bal @@ -0,0 +1,27 @@ +type Item record { + string name; + string status; + int price; +}; + +function checkOrderStatus(Item[] items, + string status) returns boolean { + foreach Item item in items { + if item.status != status { return false; } + } + return true; +} + +public function main() { + Item[] items = [ + { name: "Laptop", status: "A", price: 1000 }, + { name: "Smartphone", status: "NA", price: 500 }, + { name: "Tablet", status: "A", price: 300 }, + { name: "Headphones", status: "NA", price: 100 } + ]; + + Item[] affordableProducts = from Item item in items + where item.price < 500 + select item; + +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml new file mode 100644 index 000000000000..b5bd5e03c83e --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml" \ No newline at end of file diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/main.bal new file mode 100644 index 000000000000..68289701be17 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/main.bal @@ -0,0 +1,26 @@ +type Item record { + string name; + string status; + int price; +}; + +function checkOrderStatus(Item[] items, string status) returns boolean { + foreach Item item in items { + if item.status != status { return false;} + } + return true; +} + +public function main() { + Item[] items = [ + {name: "Laptop", status:"A", price:1000}, + {name:"Smartphone",status: "NA", price: 500}, + {name:"Tablet",status: "A", price:300}, + {name:"Headphones",status: "NA", price:100} + ]; + + Item[] affordableProducts = from Item item in items + where item.price < 500 + select item; + +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/testng.xml b/misc/formatter/modules/formatter-core/src/test/resources/testng.xml index f88916ed636a..6f8f89d66474 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/testng.xml +++ b/misc/formatter/modules/formatter-core/src/test/resources/testng.xml @@ -33,6 +33,7 @@ under the License. + From 2e2a5426fefeb7d5cfb90afdff4bc5e698e3a639 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Thu, 5 Oct 2023 22:30:50 +0530 Subject: [PATCH 09/22] Address suggestions and refactor --- .../brace/source/project/Format.toml | 2 +- .../functionCall/source/chopDown/Format.toml | 2 +- .../functionCall/source/noWrap/Format.toml | 2 +- .../functionCall/source/wrap/Format.toml | 2 +- .../source/chopDown/Format.toml | 2 +- .../source/noWrap/Format.toml | 2 +- .../source/wrap/Format.toml | 2 +- .../ifStatement/source/ifelse/Format.toml | 2 +- .../indent/source/project/Format.toml | 2 +- .../query/source/project/main.bal | 2 +- .../query/source/projectTemp/main.bal | 2 +- .../wrapping/source/project/Format.toml | 2 +- .../formatter/core/FormatterUtils.java | 24 ++++++++++--------- .../core/options/FormattingOptions.java | 20 ++++++++-------- .../formatter/core/FormatterTest.java | 23 +++++------------- 15 files changed, 41 insertions(+), 50 deletions(-) diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml index c02a9e0e7ee2..18845f1041a4 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml @@ -1,3 +1,3 @@ [braces] classBraceStyle = "NewLine" -methodBraceStyle = "NewLine" \ No newline at end of file +methodBraceStyle = "NewLine" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml index 0ac337ea0792..5c000c872f6e 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml @@ -4,4 +4,4 @@ alignMultilineParameters = true newLineAfterLeftParen = true [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml index fb4a25f74855..d2a006fec672 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml @@ -3,4 +3,4 @@ parametersWrap = "NoWrap" newLineAfterLeftParen = true [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml index 4dba90f4845b..365a236c13aa 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml @@ -5,4 +5,4 @@ newLineAfterLeftParen = true rightParenOnNewLine = true [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml index 0f87c05238a3..475a4cee5ca0 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml @@ -3,4 +3,4 @@ parametersWrap = "ChopDown" alignMultilineParameters = true [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml index 57909e17a020..0c5c088616de 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml @@ -2,4 +2,4 @@ parametersWrap = "NoWrap" [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml index 80759d993a12..5fc3a18b60f4 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml @@ -5,4 +5,4 @@ newLineAfterLeftParen = true rightParenOnNewLine = true [wrapping] -maxLineLength = 80 \ No newline at end of file +maxLineLength = 80 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml index 3b51a1f181c4..1539b331a1b6 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml @@ -1,2 +1,2 @@ [ifStatement] -elseOnNewLine = true \ No newline at end of file +elseOnNewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml index 1157c440c32b..a9ff5e340462 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml @@ -1,3 +1,3 @@ [indent] indentSize = 2 -continuationIndentSize = 2 \ No newline at end of file +continuationIndentSize = 2 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal index b7a1af09fcd7..39695d049ccd 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal @@ -7,4 +7,4 @@ function queryTest() { int[] numsReversed = from int i in nums order by i descending select i; -} \ No newline at end of file +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal index b7a1af09fcd7..39695d049ccd 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal @@ -7,4 +7,4 @@ function queryTest() { int[] numsReversed = from int i in nums order by i descending select i; -} \ No newline at end of file +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml index 72e2b5bb4744..7635233381c7 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml @@ -2,4 +2,4 @@ maxLineLength = 80 keepLineBreaks = true simpleBlocksInOneLine = true -simpleMethodsInOneLine = true \ No newline at end of file +simpleMethodsInOneLine = true diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 9d7c6312b762..5cfe3e687e54 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -69,17 +69,7 @@ public static Map getFormattingConfigurations(Path root, String content = readRemoteFormatFile(root, path); } - TomlDocument document = TomlDocument.from(path, content); - TomlTableNode tomlAstNode = document.toml().rootNode(); - - Map formatConfigs = new HashMap<>(); - if (!tomlAstNode.entries().isEmpty()) { - Map tomlMap = document.toml().toMap(); - for (Map.Entry entry : tomlMap.entrySet()) { - formatConfigs.put(entry.getKey(), entry.getValue()); - } - } - return formatConfigs; + return parseConfigurationToml(TomlDocument.from(path, content)); } public static boolean isLocalFile(String path) { @@ -143,6 +133,18 @@ private static void cacheRemoteConfigurationFile(Path root, String content) thro } } + public static Map parseConfigurationToml(TomlDocument document) { + TomlTableNode tomlAstNode = document.toml().rootNode(); + Map formatConfigs = new HashMap<>(); + if (!tomlAstNode.entries().isEmpty()) { + Map tomlMap = document.toml().toMap(); + for (Map.Entry entry : tomlMap.entrySet()) { + formatConfigs.put(entry.getKey(), entry.getValue()); + } + } + return formatConfigs; + } + static boolean isInlineRange(Node node, LineRange lineRange) { if (lineRange == null) { return true; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 786acc10ded8..f11bb2c1cbcc 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -27,16 +27,16 @@ */ public class FormattingOptions { - private IndentFormattingOptions indentFormattingOptions; - private WrappingFormattingOptions wrappingFormattingOptions; - private BraceFormattingOptions braceFormattingOptions; - private FunctionDeclFormattingOptions functionDeclFormattingOptions; - private FunctionCallFormattingOptions functionCallFormattingOptions; - private IfStatementFormattingOptions ifStatementFormattingOptions; - private SpacingFormattingOptions spacingFormattingOptions; - private ForceFormattingOptions forceFormattingOptions; - private ImportFormattingOptions importFormattingOptions; - private QueryFormattingOptions queryFormattingOptions; + private final IndentFormattingOptions indentFormattingOptions; + private final WrappingFormattingOptions wrappingFormattingOptions; + private final BraceFormattingOptions braceFormattingOptions; + private final FunctionDeclFormattingOptions functionDeclFormattingOptions; + private final FunctionCallFormattingOptions functionCallFormattingOptions; + private final IfStatementFormattingOptions ifStatementFormattingOptions; + private final SpacingFormattingOptions spacingFormattingOptions; + private final ForceFormattingOptions forceFormattingOptions; + private final ImportFormattingOptions importFormattingOptions; + private final QueryFormattingOptions queryFormattingOptions; private FormattingOptions(IndentFormattingOptions indentFormattingOptions, WrappingFormattingOptions wrappingFormattingOptions, diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java index 58f7f81c224c..f386e1621e59 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/FormatterTest.java @@ -20,7 +20,6 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.projects.TomlDocument; import io.ballerina.projects.util.ProjectConstants; -import io.ballerina.toml.semantic.ast.TomlTableNode; import io.ballerina.tools.text.TextDocument; import io.ballerina.tools.text.TextDocuments; import org.ballerinalang.formatter.core.options.FormattingOptions; @@ -36,7 +35,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -76,26 +74,17 @@ public void test(String source, String sourcePath) throws IOException { } public void testWithConfigurationFile(String source, String sourcePath) throws IOException, FormatterException { - Path assertFilePath = - Paths.get(resourceDirectory.toString(), sourcePath, ASSERT_DIR, source); - Path sourceDir = - Paths.get(resourceDirectory.toString(), sourcePath, SOURCE_DIR); + Path sourceDir = Paths.get(resourceDirectory.toString(), sourcePath, SOURCE_DIR); Path sourceFilePath = Paths.get(sourceDir.toString(), source); + Path assertFilePath = Paths.get(resourceDirectory.toString(), sourcePath, ASSERT_DIR, source); Path tomlPath = Paths.get(sourceDir.toString(), ProjectConstants.BALLERINA_TOML); String content = getSourceText(sourceFilePath); TextDocument textDocument = TextDocuments.from(content); - SyntaxTree syntaxTree = SyntaxTree.from(textDocument); String tomlContent = Files.readString(tomlPath); - TomlDocument ballerinaToml = TomlDocument.from(ProjectConstants.BALLERINA_TOML, tomlContent); - TomlTableNode tomlAstNode = ballerinaToml.toml().rootNode(); - Map formatConfigs = new HashMap<>(); - if (!tomlAstNode.entries().isEmpty()) { - Map tomlMap = ballerinaToml.toml().toMap(); - for (Map.Entry entry : tomlMap.entrySet()) { - formatConfigs.put(entry.getKey(), entry.getValue()); - } - } - FormattingOptions formattingOptions = FormattingOptions.builder().build(sourceDir, formatConfigs.get("format")); + TomlDocument tomlDocument = TomlDocument.from(ProjectConstants.BALLERINA_TOML, tomlContent); + Map tomlConfig = FormatterUtils.parseConfigurationToml(tomlDocument); + FormattingOptions formattingOptions = FormattingOptions.builder().build(sourceDir, tomlConfig.get("format")); + SyntaxTree syntaxTree = SyntaxTree.from(textDocument); try { SyntaxTree newSyntaxTree = Formatter.format(syntaxTree, formattingOptions); Assert.assertEquals(newSyntaxTree.toSourceCode(), getSourceText(assertFilePath)); From e26e669df3aa2b1bfe4414e9a5b2b91fd9476d29 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 23 Oct 2023 09:21:46 +0530 Subject: [PATCH 10/22] Opinionated filename for formatting file --- .../formatting/project/Ballerina.toml | 2 +- .../brace/source/project/Ballerina.toml | 2 +- .../source/chopDown/Ballerina.toml | 2 +- .../functionCall/source/noWrap/Ballerina.toml | 2 +- .../functionCall/source/wrap/Ballerina.toml | 2 +- .../source/chopDown/Ballerina.toml | 2 +- .../source/noWrap/Ballerina.toml | 2 -- .../source/wrap/Ballerina.toml | 2 +- .../ifStatement/source/ifelse/Ballerina.toml | 2 +- .../imports/source/project/Ballerina.toml | 2 +- .../indent/source/project/Ballerina.toml | 2 -- .../query/source/project/Ballerina.toml | 2 +- .../spacing/source/project/Ballerina.toml | 2 +- .../wrapping/source/project/Ballerina.toml | 2 -- .../formatter/core/FormatterUtils.java | 23 +++++++++++++++++++ .../core/options/FormattingOptions.java | 10 +++----- .../local/source/Ballerina.toml | 2 +- 17 files changed, 38 insertions(+), 25 deletions(-) diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml index 351f71b60982..9646948d7e80 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/formatting/project/Format.toml" +configPath = "src/test/resources/formatting/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml index 068140f77031..a11d3d8fd440 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/brace/source/project/Format.toml" +configPath = "src/test/resources/configurations/brace/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml index 15a10f1fa75a..8e54d8ed91c5 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/functionCall/source/chopDown/Format.toml" +configPath = "src/test/resources/configurations/functionCall/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml index 2ec06e5d391e..2d40e31f1346 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/functionCall/source/noWrap/Format.toml" +configPath = "src/test/resources/configurations/functionCall/source/noWrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml index 3238dd1c3aac..4d851c42c785 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/functionCall/source/wrap/Format.toml" +configPath = "src/test/resources/configurations/functionCall/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml index e5df81b20e7b..95eb41f51983 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml" +configPath = "src/test/resources/configurations/functionDeclaration/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml index f453f3503efb..e69de29bb2d1 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml index 2f28a15c1484..94de643f225c 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml" +configPath = "src/test/resources/configurations/functionDeclaration/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml index 52240e47f5d7..c56508296bfb 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/ifStatement/source/ifelse/Format.toml" +configPath = "src/test/resources/configurations/ifStatement/source/ifelse" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml index 98a99c665ffa..3be67308dc2b 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/imports/source/project/Format.toml" +configPath = "src/test/resources/configurations/imports/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml index 267ba8abf527..e69de29bb2d1 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/indent/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml index 62fe4497a106..26d2a66bc526 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/query/source/project/Format.toml" +configPath = "src/test/resources/configurations/query/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml index fa2196feb3ce..cea39276de7f 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/spacing/source/project/Format.toml" +configPath = "src/test/resources/configurations/spacing/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml index 54925bd97844..e69de29bb2d1 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/wrapping/source/project/Format.toml" diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 5cfe3e687e54..034d2f696be7 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -57,6 +57,29 @@ private FormatterUtils() { static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); + public static String getFormattingFilePath(Object data, String root) { + if (data instanceof Map) { + Object path = ((Map) data).get("configPath"); + if (path != null) { + String str = path.toString(); + if (str.endsWith(".toml")) { + return str; + } + return Path.of(str, "Format.toml").toString(); + } + } + File directory = new File(root); + File[] files = directory.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isFile() && file.getName().equals("Format.toml")) { + return file.getAbsolutePath(); + } + } + } + return null; + } + public static Map getFormattingConfigurations(Path root, String path) throws FormatterException { String content; if (isLocalFile(path)) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index f11bb2c1cbcc..2b11144a382a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -21,6 +21,7 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; +import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingFilePath; /** * A model for formatting options that could be passed onto the formatter. @@ -176,16 +177,11 @@ public FormattingOptions build() { } public FormattingOptions build(Path root, Object data) throws FormatterException { - if (!(data instanceof Map)) { - return build(); - } - Map balTomlConfigurations = (Map) data; - Object path = balTomlConfigurations.get("configPath"); + String path = getFormattingFilePath(data, root.toString()); if (path == null) { return build(); } - Map configurations = getFormattingConfigurations(root, path.toString()); - + Map configurations = getFormattingConfigurations(root, path); for (Map.Entry entry : configurations.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml index c12d157a7ac3..e65074998a5f 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/local/source/Format.toml" +configPath = "src/test/resources/configurations/local/source" From 1f807b78c21db0bcc59b7f62db3256be840c4e9b Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 27 Nov 2023 06:53:34 +0530 Subject: [PATCH 11/22] Address review suggestions --- .../BallerinaTextDocumentService.java | 10 ++- .../formatter/cli/FormatUtil.java | 7 +- .../modules/formatter-core/build.gradle | 2 +- .../formatter/core/FormatterUtils.java | 70 +++++++++++++------ .../core/options/BraceFormattingOptions.java | 20 ++++-- .../formatter/core/options/BraceStyle.java | 20 ++++++ .../core/options/ForceFormattingOptions.java | 2 +- .../formatter/core/options/FormatSection.java | 54 ++++++++++++++ .../core/options/FormattingOptions.java | 27 +++---- .../FunctionCallFormattingOptions.java | 34 ++++++--- .../FunctionDeclFormattingOptions.java | 33 ++++++--- .../options/IfStatementFormattingOptions.java | 13 ++-- .../core/options/ImportFormattingOptions.java | 23 +++--- .../core/options/IndentFormattingOptions.java | 18 +++-- .../core/options/QueryFormattingOptions.java | 13 ++-- .../options/SpacingFormattingOptions.java | 24 ++++--- .../options/WrappingFormattingOptions.java | 29 +++++--- .../core/options/WrappingMethod.java | 21 ++++++ .../src/main/resources/formatter.properties | 47 +++++++++++++ .../LocalConfigurationTest.java | 3 +- .../RemoteConfigurationTest.java | 2 +- .../configurations/local/assert/main.bal | 2 +- .../configurations/local/source/Format.toml | 2 +- .../configurations/local/source/main.bal | 4 +- .../remote/source/Ballerina.toml | 2 +- 25 files changed, 368 insertions(+), 114 deletions(-) create mode 100644 misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java create mode 100644 misc/formatter/modules/formatter-core/src/main/resources/formatter.properties diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index 4f1dac4fea3a..cfb13b2ceb20 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -116,6 +116,8 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static org.ballerinalang.formatter.core.FormatterUtils.loadFormatSection; + /** * Text document service implementation for ballerina. */ @@ -444,12 +446,14 @@ public CompletableFuture> formatting(DocumentFormatting return Collections.emptyList(); } String formattedSource; - if (context.currentModule().isPresent() && - !(context.currentModule().get().project().kind() == ProjectKind.SINGLE_FILE_PROJECT)) { + Optional currentModule = context.currentModule(); + if (currentModule.isPresent() && + currentModule.get().project().kind() != ProjectKind.SINGLE_FILE_PROJECT) { Path rootPath = context.workspace().projectRoot(context.filePath()); BuildProject project = BuildProject.load(rootPath, BuildOptions.builder().build()); FormattingOptions options = FormattingOptions.builder() - .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); + .build(project.sourceRoot(), + loadFormatSection(project.currentPackage().manifest())); formattedSource = Formatter.format(syntaxTree.get(), options).toSourceCode(); } else { formattedSource = Formatter.format(syntaxTree.get()).toSourceCode(); diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index 9e6d9f24a96b..bbe041804e71 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -27,6 +27,7 @@ import io.ballerina.projects.directory.SingleFileProject; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterUtils; import org.ballerinalang.formatter.core.options.FormattingOptions; import java.io.File; @@ -128,7 +129,8 @@ static void execute(List argList, boolean helpFlag, String moduleName, S try { project = BuildProject.load(projectPath, constructBuildOptions()); options = FormattingOptions.builder() - .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); + .build(project.sourceRoot(), + FormatterUtils.loadFormatSection(project.currentPackage().manifest())); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -196,7 +198,8 @@ static void execute(List argList, boolean helpFlag, String moduleName, S try { project = BuildProject.load(sourceRootPath, constructBuildOptions()); options = FormattingOptions.builder() - .build(project.sourceRoot(), project.currentPackage().manifest().getValue("format")); + .build(project.sourceRoot(), + FormatterUtils.loadFormatSection(project.currentPackage().manifest())); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } diff --git a/misc/formatter/modules/formatter-core/build.gradle b/misc/formatter/modules/formatter-core/build.gradle index a5e02e12782a..be9d9c82ecf0 100755 --- a/misc/formatter/modules/formatter-core/build.gradle +++ b/misc/formatter/modules/formatter-core/build.gradle @@ -28,7 +28,7 @@ dependencies { implementation project(':ballerina-parser') implementation project(':ballerina-lang') implementation "org.apache.commons:commons-lang3:${project.apacheCommonsLang3Version}" - implementation project(path: ':toml-parser') + implementation project(':toml-parser') testImplementation 'com.google.code.gson:gson' testImplementation 'org.testng:testng' diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 034d2f696be7..d80a539bdb25 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -24,11 +24,15 @@ import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.projects.PackageManifest; import io.ballerina.projects.TomlDocument; import io.ballerina.toml.semantic.ast.TomlTableNode; import io.ballerina.tools.text.LineRange; import org.apache.commons.lang3.builder.CompareToBuilder; +import org.ballerinalang.formatter.core.options.FormatSection; import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -43,7 +47,9 @@ import java.nio.file.Path; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.ResourceBundle; import java.util.stream.Collectors; /** @@ -51,28 +57,55 @@ */ public class FormatterUtils { + private static Logger logger = LoggerFactory.getLogger("Formatter"); + static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); + static final String FORMAT_FILE_FIELD = "configPath"; + static final String FORMAT_OPTION_FILE_EXT = ".toml"; + static final String DEFAULT_FORMAT_OPTION_FILE = "Format.toml"; + static final String TARGET_DIR = "target"; + static final String FORMAT = "format"; + public static final ResourceBundle DEFAULTS = ResourceBundle.getBundle("formatter", Locale.getDefault()); + private FormatterUtils() { + } + public static boolean getDefaultBoolean(FormatSection section, String key) { + return Boolean.parseBoolean(getDefaultString(section, key)); } - static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); + public static int getDefaultInt(FormatSection section, String key) { + return Integer.parseInt(getDefaultString(section, key)); + } + + public static String getDefaultString(FormatSection section, String key) { + return DEFAULTS.getString(section.getStringValue() + "." + key); + } + + public static Object loadFormatSection(PackageManifest manifest) { + return manifest.getValue(FORMAT); + } + + public static void warning(String message) { + logger.warn(message); + } - public static String getFormattingFilePath(Object data, String root) { - if (data instanceof Map) { - Object path = ((Map) data).get("configPath"); + public static String getFormattingFilePath(Object formatSection, String root) { + if (formatSection != null) { + Object path = ((Map) formatSection).get(FORMAT_FILE_FIELD); if (path != null) { String str = path.toString(); - if (str.endsWith(".toml")) { + if (str.endsWith(FORMAT_OPTION_FILE_EXT)) { return str; } - return Path.of(str, "Format.toml").toString(); + return Path.of(str, DEFAULT_FORMAT_OPTION_FILE).toString(); } } + File directory = new File(root); File[] files = directory.listFiles(); if (files != null) { for (File file : files) { - if (file.isFile() && file.getName().equals("Format.toml")) { + if (file.isFile() && file.getName().equals(DEFAULT_FORMAT_OPTION_FILE)) { return file.getAbsolutePath(); } } @@ -100,9 +133,7 @@ public static boolean isLocalFile(String path) { } static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { - StringBuilder fileContent = new StringBuilder(); - Path cachePath = root.resolve("target").resolve("format").resolve("Format.toml"); - + Path cachePath = root.resolve(TARGET_DIR).resolve(FORMAT).resolve(DEFAULT_FORMAT_OPTION_FILE); if (Files.exists(cachePath)) { try { return Files.readString(cachePath, StandardCharsets.UTF_8); @@ -111,6 +142,7 @@ static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterEx } } + StringBuilder fileContent = new StringBuilder(); try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -130,7 +162,7 @@ static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterEx } connection.disconnect(); } catch (IOException e) { - throw new FormatterException("Failed to retrieve remote formatting configuration file"); + throw new FormatterException("Failed to retrieve formatting configuration file"); } cacheRemoteConfigurationFile(root, fileContent.toString()); @@ -138,15 +170,15 @@ static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterEx } private static void cacheRemoteConfigurationFile(Path root, String content) throws FormatterException { - if (Files.exists(root.resolve("target"))) { - if (!Files.exists(root.resolve("target").resolve("format"))) { + if (Files.exists(root.resolve(TARGET_DIR))) { + if (!Files.exists(root.resolve(TARGET_DIR).resolve(FORMAT))) { try { - Files.createDirectories(root.resolve("target").resolve("format")); + Files.createDirectories(root.resolve(TARGET_DIR).resolve(FORMAT)); } catch (IOException e) { throw new FormatterException("Failed to create format configuration cache directory"); } } - String filePath = root.resolve("target").resolve("format").resolve("Format.toml") + String filePath = root.resolve(TARGET_DIR).resolve(FORMAT).resolve(DEFAULT_FORMAT_OPTION_FILE) .toString(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, StandardCharsets.UTF_8))) { writer.write(content); @@ -158,14 +190,10 @@ private static void cacheRemoteConfigurationFile(Path root, String content) thro public static Map parseConfigurationToml(TomlDocument document) { TomlTableNode tomlAstNode = document.toml().rootNode(); - Map formatConfigs = new HashMap<>(); if (!tomlAstNode.entries().isEmpty()) { - Map tomlMap = document.toml().toMap(); - for (Map.Entry entry : tomlMap.entrySet()) { - formatConfigs.put(entry.getKey(), entry.getValue()); - } + return document.toml().toMap(); } - return formatConfigs; + return new HashMap<>(); } static boolean isInlineRange(Node node, LineRange lineRange) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 34e54f06cae7..8ff3652b95a1 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,13 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of brace settings by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class BraceFormattingOptions { @@ -48,8 +51,12 @@ public static BraceFormattingOptions.BraceFormattingOptionsBuilder builder() { public static class BraceFormattingOptionsBuilder { - private BraceStyle classBraceStyle = BraceStyle.EndOfLine; - private BraceStyle methodBraceStyle = BraceStyle.EndOfLine; + private static final String CLASS_BRACE_STYLE = "classBraceStyle"; + private static final String METHOD_BRACE_STYLE = "methodBraceStyle"; + private BraceStyle classBraceStyle = + BraceStyle.valueOf(getDefaultString(FormatSection.BRACES, CLASS_BRACE_STYLE)); + private BraceStyle methodBraceStyle = + BraceStyle.valueOf(getDefaultString(FormatSection.BRACES, METHOD_BRACE_STYLE)); public BraceFormattingOptionsBuilder setClassBraceStyle(BraceStyle classBraceStyle) { this.classBraceStyle = classBraceStyle; @@ -70,13 +77,14 @@ public BraceFormattingOptions build(Map configs) throws Formatte String bracesKey = bracesEntry.getKey(); BraceStyle style = BraceStyle.fromString((String) bracesEntry.getValue()); switch (bracesKey) { - case "classBraceStyle": + case CLASS_BRACE_STYLE: setClassBraceStyle(style); break; - case "methodBraceStyle": + case METHOD_BRACE_STYLE: setMethodBraceStyle(style); break; default: + warning("Invalid Brace Option: " + bracesKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index 57c4827387cf..dc379f2ded0e 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -1,7 +1,27 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.ballerinalang.formatter.core.options; import org.ballerinalang.formatter.core.FormatterException; +/** + * Represents the brace styles. + * + * @since 2201.9.0 + */ public enum BraceStyle { NewLine, EndOfLine; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java index fc3e69367c16..343106bfea7c 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java new file mode 100644 index 000000000000..295113e84ab4 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.ballerinalang.formatter.core.options; + +import org.ballerinalang.formatter.core.FormatterException; + +/** + * Represents the sections in the format file. + * + * @since 2201.9.0 + */ +public enum FormatSection { + BRACES("braces"), + METHOD_CALL("methodCall"), + METHOD_DECLARATION("methodDeclaration"), + IF_STATEMENT("ifStatement"), + IMPORT("import"), + INDENT("indent"), + QUERY("query"), + SPACING("spacing"), + WRAPPING("wrapping"); + + private final String val; + + FormatSection(String val) { + this.val = val; + } + + public String getStringValue() { + return val; + } + + public static FormatSection fromString(String value) throws FormatterException { + for (FormatSection section : FormatSection.values()) { + if (section.val.equals(value)) { + return section; + } + } + throw new FormatterException("Invalid format section: " + value); + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 2b11144a382a..4396c8ccce71 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -22,6 +22,7 @@ import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingFilePath; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting options that could be passed onto the formatter. @@ -176,8 +177,8 @@ public FormattingOptions build() { spacingFormattingOptions, forceFormattingOptions, importFormattingOptions, queryFormattingOptions); } - public FormattingOptions build(Path root, Object data) throws FormatterException { - String path = getFormattingFilePath(data, root.toString()); + public FormattingOptions build(Path root, Object formatSection) throws FormatterException { + String path = getFormattingFilePath(formatSection, root.toString()); if (path == null) { return build(); } @@ -189,35 +190,37 @@ public FormattingOptions build(Path root, Object data) throws FormatterException continue; } Map configs = (Map) value; - switch (key) { - case "indent": + FormatSection section = FormatSection.fromString(key); + switch (section) { + case INDENT: indentFormattingOptions = IndentFormattingOptions.builder().build(configs); break; - case "wrapping": + case WRAPPING: wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); break; - case "braces": + case BRACES: braceFormattingOptions = BraceFormattingOptions.builder().build(configs); break; - case "methodDeclaration": + case METHOD_DECLARATION: functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); break; - case "methodCall": + case METHOD_CALL: functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); break; - case "ifStatement": + case IF_STATEMENT: ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); break; - case "query": + case QUERY: queryFormattingOptions = QueryFormattingOptions.builder().build(configs); break; - case "spacing": + case SPACING: spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); break; - case "import": + case IMPORT: importFormattingOptions = ImportFormattingOptions.builder().build(configs); break; default: + warning("Invalid formatting option section : " + section); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index a827a206b185..cdd9f72b80a6 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,16 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of if statement by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ + public class FunctionCallFormattingOptions { private final WrappingMethod parametersWrap; @@ -60,14 +65,20 @@ public static FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder } /** - * A builder for the {@code FunctionFormattingOptions}. + * A builder for the {@code FunctionCallFormattingOptions}. */ public static class FunctionCallFormattingOptionsBuilder { - private WrappingMethod parametersWrap = WrappingMethod.Wrap; - private boolean alignMultilineParameters = false; - private boolean newLineAfterLeftParen = false; - private boolean rightParenOnNewLine = false; + private static final String PARAMETERS_WRAP = "parametersWrap"; + private static final String ALIGN_MULTILINE_PARAMETERS = "alignMultilineParameters"; + private static final String NEWLINE_AFTER_LEFT_PAREN = "newLineAfterLeftParen"; + private static final String RIGHT_PAREN_ON_NEWLINE = "rightParenOnNewLine"; + private WrappingMethod parametersWrap = + WrappingMethod.valueOf(getDefaultString(FormatSection.METHOD_CALL, PARAMETERS_WRAP)); + private boolean alignMultilineParameters = + getDefaultBoolean(FormatSection.METHOD_CALL, ALIGN_MULTILINE_PARAMETERS); + private boolean newLineAfterLeftParen = getDefaultBoolean(FormatSection.METHOD_CALL, NEWLINE_AFTER_LEFT_PAREN); + private boolean rightParenOnNewLine = getDefaultBoolean(FormatSection.METHOD_CALL, RIGHT_PAREN_ON_NEWLINE); public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setParametersWrap( WrappingMethod parametersWrap) { @@ -102,19 +113,20 @@ public FunctionCallFormattingOptions build(Map configs) throws F for (Map.Entry methodCallEntry : configs.entrySet()) { String methodCallKey = methodCallEntry.getKey(); switch (methodCallKey) { - case "parametersWrap": + case PARAMETERS_WRAP: setParametersWrap(WrappingMethod.fromString((String) methodCallEntry.getValue())); break; - case "alignMultilineParameters": + case ALIGN_MULTILINE_PARAMETERS: setAlignMultilineParameters((Boolean) methodCallEntry.getValue()); break; - case "newLineAfterLeftParen": + case NEWLINE_AFTER_LEFT_PAREN: setNewLineAfterLeftParen((Boolean) methodCallEntry.getValue()); break; - case "rightParenOnNewLine": + case RIGHT_PAREN_ON_NEWLINE: setRightParenOnNewLine((Boolean) methodCallEntry.getValue()); break; default: + warning("Invalid function call formatting option: " + methodCallKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index 6b7990a7b553..db3dcf340354 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,14 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of function declarations by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class FunctionDeclFormattingOptions { @@ -61,10 +65,18 @@ public static FunctionDeclFormattingOptionsBuilder builder() { public static class FunctionDeclFormattingOptionsBuilder { - private WrappingMethod parametersWrap = WrappingMethod.Wrap; - private boolean alignMultilineParameters = false; - private boolean newLineAfterLeftParen = false; - private boolean rightParenOnNewLine = false; + private static final String PARAMETERS_WRAP = "parametersWrap"; + private static final String ALIGN_MULTILINE_PARAMETERS = "alignMultilineParameters"; + private static final String NEWLINE_AFTER_LEFT_PAREN = "newLineAfterLeftParen"; + private static final String RIGHT_PAREN_ON_NEWLINE = "rightParenOnNewLine"; + private WrappingMethod parametersWrap = + WrappingMethod.valueOf(getDefaultString(FormatSection.METHOD_DECLARATION, PARAMETERS_WRAP)); + private boolean alignMultilineParameters = + getDefaultBoolean(FormatSection.METHOD_DECLARATION, ALIGN_MULTILINE_PARAMETERS); + private boolean newLineAfterLeftParen = + getDefaultBoolean(FormatSection.METHOD_DECLARATION, NEWLINE_AFTER_LEFT_PAREN); + private boolean rightParenOnNewLine = + getDefaultBoolean(FormatSection.METHOD_DECLARATION, RIGHT_PAREN_ON_NEWLINE); public FunctionDeclFormattingOptionsBuilder setParametersWrap(WrappingMethod parametersWrap) { this.parametersWrap = parametersWrap; @@ -95,19 +107,20 @@ public FunctionDeclFormattingOptions build(Map configs) throws F for (Map.Entry methodDeclarationEntry : configs.entrySet()) { String methodDeclarationKey = methodDeclarationEntry.getKey(); switch (methodDeclarationKey) { - case "parametersWrap": + case PARAMETERS_WRAP: setParametersWrap(WrappingMethod.fromString((String) methodDeclarationEntry.getValue())); break; - case "alignMultilineParameters": + case ALIGN_MULTILINE_PARAMETERS: setAlignMultilineParameters((Boolean) methodDeclarationEntry.getValue()); break; - case "newLineAfterLeftParen": + case NEWLINE_AFTER_LEFT_PAREN: setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); break; - case "rightParenOnNewLine": + case RIGHT_PAREN_ON_NEWLINE: setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); break; default: + warning("Invalid function declaration formatting option: " + methodDeclarationKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index 5fa6ddcadb1b..ef3bc38fc8f4 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of indent settings by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class IfStatementFormattingOptions { @@ -40,7 +43,8 @@ public static IfStatementFormattingOptions.IfStatementFormattingOptionsBuilder b public static class IfStatementFormattingOptionsBuilder { - private boolean elseOnNewLine = false; + private static final String ELSE_ON_NEW_LINE = "elseOnNewLine"; + private boolean elseOnNewLine = getDefaultBoolean(FormatSection.IF_STATEMENT, ELSE_ON_NEW_LINE); public IfStatementFormattingOptionsBuilder setElseOnNewLine(boolean elseOnNewLine) { this.elseOnNewLine = elseOnNewLine; @@ -55,10 +59,11 @@ public IfStatementFormattingOptions build(Map configs) { for (Map.Entry ifStatementEntry : configs.entrySet()) { String ifStatementKey = ifStatementEntry.getKey(); switch (ifStatementKey) { - case "elseOnNewLine": + case ELSE_ON_NEW_LINE: setElseOnNewLine((Boolean) ifStatementEntry.getValue()); break; default: + warning("Invalid if statement formatting option: " + ifStatementKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index fea6d9055c17..c4c2ff958400 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,9 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting and optimizing imports by the API user, that could be passed onto the formatter. * @@ -55,9 +58,12 @@ public static ImportFormattingOptions.ImportFormattingOptionsBuilder builder() { */ public static class ImportFormattingOptionsBuilder { - private boolean groupImports = true; - private boolean sortImports = true; - private boolean removeUnusedImports = false; + private static final String GROUP_IMPORTS = "groupImports"; + private static final String SORT_IMPORTS = "sortImports"; + private static final String REMOVE_UNUSED_IMPORTS = "removeUnusedImports"; + private boolean groupImports = getDefaultBoolean(FormatSection.IMPORT, GROUP_IMPORTS); + private boolean sortImports = getDefaultBoolean(FormatSection.IMPORT, SORT_IMPORTS); + private boolean removeUnusedImports = getDefaultBoolean(FormatSection.IMPORT, REMOVE_UNUSED_IMPORTS); public ImportFormattingOptions.ImportFormattingOptionsBuilder setGroupImports(boolean groupImports) { this.groupImports = groupImports; @@ -81,15 +87,16 @@ public ImportFormattingOptions build() { public ImportFormattingOptions build(Map configs) { for (Map.Entry importEntry : configs.entrySet()) { - String ifStatementKey = importEntry.getKey(); - switch (ifStatementKey) { - case "sortImports": + String importKey = importEntry.getKey(); + switch (importKey) { + case SORT_IMPORTS: setSortImports((Boolean) importEntry.getValue()); break; - case "groupImports": + case GROUP_IMPORTS: setGroupImports((Boolean) importEntry.getValue()); break; default: + warning("Invalid import formatting option: " + importKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index 9ff949b08301..841827898b0d 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultInt; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of indent settings by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class IndentFormattingOptions { @@ -55,8 +58,10 @@ public static IndentFormattingOptions.IndentFormattingOptionsBuilder builder() { */ public static class IndentFormattingOptionsBuilder { - private int indentSize = 4; - private int continuationIndentSize = 2; + private static final String INDENT_SIZE = "indentSize"; + private static final String CONTINUATION_INDENT_SIZE = "continuationIndentSize"; + private int indentSize = getDefaultInt(FormatSection.INDENT, INDENT_SIZE); + private int continuationIndentSize = getDefaultInt(FormatSection.INDENT, CONTINUATION_INDENT_SIZE); private String wsCharacter = " "; public IndentFormattingOptionsBuilder setIndentSize(int indentSize) { @@ -77,13 +82,14 @@ public IndentFormattingOptions build(Map configs) { for (Map.Entry indentEntry : configs.entrySet()) { String indentKey = indentEntry.getKey(); switch (indentKey) { - case "indentSize": + case INDENT_SIZE: setIndentSize(((Number) indentEntry.getValue()).intValue()); break; - case "continuationIndentSize": + case CONTINUATION_INDENT_SIZE: setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); break; default: + warning("Invalid indent formatting option: " + indentKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index 4c4f7d99542b..9f9af291d284 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of the queries by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class QueryFormattingOptions { @@ -40,7 +43,8 @@ public static QueryFormattingOptions.QueryFormattingOptionsBuilder builder() { public static class QueryFormattingOptionsBuilder { - private boolean alignMultiLineQueries = false; + private static final String ALIGN_MULTILINE_QUERIES = "alignMultiLineQueries"; + private boolean alignMultiLineQueries = getDefaultBoolean(FormatSection.QUERY, ALIGN_MULTILINE_QUERIES); public QueryFormattingOptionsBuilder setAlignMultiLineQueries(boolean alignMultiLineQueries) { this.alignMultiLineQueries = alignMultiLineQueries; @@ -55,10 +59,11 @@ public QueryFormattingOptions build(Map configs) { for (Map.Entry queryStatementEntry : configs.entrySet()) { String queryStatementKey = queryStatementEntry.getKey(); switch (queryStatementKey) { - case "alignMultiLineQueries": + case ALIGN_MULTILINE_QUERIES: setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); break; default: + warning("Invalid query formatting option: " + queryStatementKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index d29ee4659042..20f09ffe2b8a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,13 @@ import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of spacing by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class SpacingFormattingOptions { @@ -53,9 +56,13 @@ public static SpacingFormattingOptions.SpacingFormattingOptionsBuilder builder() public static class SpacingFormattingOptionsBuilder { - private boolean afterTypeCast = false; - private boolean aroundRecordBraces = false; - private boolean alignConsecutiveDefinitions = false; + private static final String AFTER_TYPE_CAST = "afterTypeCast"; + private static final String AROUND_RECORD_BRACES = "aroundRecordBraces"; + private static final String ALIGN_CONSECUTIVE_DEFINITIONS = "alignConsecutiveDefinitions"; + private boolean afterTypeCast = getDefaultBoolean(FormatSection.SPACING, AFTER_TYPE_CAST); + private boolean aroundRecordBraces = getDefaultBoolean(FormatSection.SPACING, AROUND_RECORD_BRACES); + private boolean alignConsecutiveDefinitions = + getDefaultBoolean(FormatSection.SPACING, ALIGN_CONSECUTIVE_DEFINITIONS); public SpacingFormattingOptionsBuilder setAfterTypeCast(boolean afterTypeCast) { this.afterTypeCast = afterTypeCast; @@ -80,16 +87,17 @@ public SpacingFormattingOptions build(Map configs) { for (Map.Entry spacingEntry : configs.entrySet()) { String spacingKey = spacingEntry.getKey(); switch (spacingKey) { - case "afterTypeCast": + case AFTER_TYPE_CAST: setAfterTypeCast((Boolean) spacingEntry.getValue()); break; - case "aroundRecordBraces": + case AROUND_RECORD_BRACES: setAroundRecordBraces((Boolean) spacingEntry.getValue()); break; - case "alignConsecutiveDefinitions": + case ALIGN_CONSECUTIVE_DEFINITIONS: setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); break; default: + warning("Invalid spacing formatting option: " + spacingKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index bdb697528357..4930c75bd95d 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,16 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterUtils; + import java.util.Map; +import static org.ballerinalang.formatter.core.FormatterUtils.warning; + /** * A model for formatting of wrapping settings by the API user, that could be passed onto the formatter. * - * @since 2201.8.0 + * @since 2201.9.0 */ public class WrappingFormattingOptions { @@ -59,10 +63,16 @@ public static WrappingFormattingOptions.WrappingFormattingOptionsBuilder builder public static class WrappingFormattingOptionsBuilder { - private int maxLineLength = 120; - private boolean simpleBlocksInOneLine = false; - private boolean simpleMethodsInOneLine = false; - private boolean lineWrap = false; + private static final String MAX_LINE_LENGTH = "maxLineLength"; + private static final String SIMPLE_BLOCKS_IN_ONE_LINE = "simpleBlocksInOneLine"; + private static final String SIMPLE_METHODS_IN_ONE_LINE = "simpleMethodsInOneLine"; + private static final String LINE_WRAP = "lineWrap"; + private int maxLineLength = FormatterUtils.getDefaultInt(FormatSection.WRAPPING, MAX_LINE_LENGTH); + private boolean simpleBlocksInOneLine = + FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, SIMPLE_BLOCKS_IN_ONE_LINE); + private boolean simpleMethodsInOneLine = + FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, SIMPLE_METHODS_IN_ONE_LINE); + private boolean lineWrap = FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, LINE_WRAP); public WrappingFormattingOptionsBuilder setMaxLineLength(int maxLineLength) { this.maxLineLength = maxLineLength; @@ -93,17 +103,18 @@ public WrappingFormattingOptions build(Map configs) { for (Map.Entry wrappingEntry : configs.entrySet()) { String wrappingKey = wrappingEntry.getKey(); switch (wrappingKey) { - case "maxLineLength": + case MAX_LINE_LENGTH: setMaxLineLength(((Number) wrappingEntry.getValue()).intValue()); setLineWrap(true); break; - case "simpleBlocksInOneLine": + case SIMPLE_BLOCKS_IN_ONE_LINE: setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); break; - case "simpleMethodsInOneLine": + case SIMPLE_METHODS_IN_ONE_LINE: setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); break; default: + warning("Invalid wrapping formatting option: " + wrappingKey); break; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index c0003e5c80dd..f139b3c83102 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -1,7 +1,27 @@ +/* + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.ballerinalang.formatter.core.options; import org.ballerinalang.formatter.core.FormatterException; +/** + * Represents the wrapping methods. + * + * @since 2201.9.0 + */ public enum WrappingMethod { ChopDown, Wrap, @@ -14,4 +34,5 @@ public static WrappingMethod fromString(String value) throws FormatterException throw new FormatterException("Invalid wrapping method: " + value); } } + } diff --git a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties new file mode 100644 index 000000000000..592edc831faa --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties @@ -0,0 +1,47 @@ +# +# Copyright (c) 2023, WSO2 LLC. (http://wso2.com). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +braces.classBraceStyle=EndOfLine +braces.methodBraceStyle=EndOfLine + +methodCall.parametersWrap=Wrap +methodCall.alignMultilineParameters=false +methodCall.newLineAfterLeftParen=false +methodCall.rightParenOnNewLine=false + +methodDeclaration.parametersWrap=Wrap +methodDeclaration.alignMultilineParameters=false +methodDeclaration.newLineAfterLeftParen=false +methodDeclaration.rightParenOnNewLine=false + +ifStatement.elseOnNewLine=false + +import.groupImports=true +import.sortImports=true +import.removeUnusedImports=false + +indent.indentSize=4 +indent.continuationIndentSize=2 + +query.alignMultiLineQueries=false + +spacing.afterTypeCast=false +spacing.aroundRecordBraces=false +spacing.alignConsecutiveDefinitions=false + +wrapping.maxLineLength=120 +wrapping.lineWrap=false +wrapping.simpleBlocksInOneLine=false +wrapping.simpleMethodsInOneLine=false \ No newline at end of file diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java index df97e0274897..379ded3cd9ee 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java @@ -27,7 +27,7 @@ /** * Test formatting with a local configuration file. * - * @since 2.0.0 + * @since 2201.9.0 */ public class LocalConfigurationTest extends FormatterTest { @Test(dataProvider = "test-file-provider") @@ -57,4 +57,3 @@ public String getTestResourceDir() { return path.toString(); } } - diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java index 1ca343b34293..2bf099e56731 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java @@ -26,7 +26,7 @@ /** * Test the formatting of additive expressions. * - * @since 2.0.0 + * @since 2201.9.0 */ public class RemoteConfigurationTest extends FormatterTest { diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal index f5e25fde52f7..96fb8dd094d8 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/assert/main.bal @@ -19,7 +19,7 @@ public function main() { ]; Employee[] top3 = from var e in employees - order by e.salary descending + order by e.score descending limit 3 select e; diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml index b6e9a1b6bd3e..604529288f88 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Format.toml @@ -9,4 +9,4 @@ aroundRecordBraces = true alignConsecutiveDefinitions = true [query] -alignMultiLineQueries = true \ No newline at end of file +alignMultiLineQueries = true diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal index cc24aa2e6ca2..cab1e6ac447b 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/main.bal @@ -19,9 +19,9 @@ public function main() { ]; Employee[] top3 = from var e in employees - order by e.salary descending + order by e.score descending limit 3 select e; foreach var emp in top3 {io:println(emp);} -} \ No newline at end of file +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml index b5bd5e03c83e..d9cd5dd4962c 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml" \ No newline at end of file +configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml" From 917b16d0027df04c5a10a640e11c780b885a442c Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Thu, 4 Jan 2024 11:38:23 +0530 Subject: [PATCH 12/22] Address review comments and add validator --- .../functionCall/source/wrap/main.bal | 16 +- .../wrapping/source/project/Format.toml | 1 - .../src/main/java/module-info.java | 2 +- .../formatter/core/FormatterUtils.java | 107 +++++++------ .../core/FormattingTreeModifier.java | 29 ++-- .../core/options/BraceFormattingOptions.java | 12 +- .../core/options/FormattingOptions.java | 43 ++--- .../FunctionCallFormattingOptions.java | 27 ++-- .../FunctionDeclFormattingOptions.java | 23 +-- .../options/IfStatementFormattingOptions.java | 11 +- .../core/options/ImportFormattingOptions.java | 12 +- .../core/options/IndentFormattingOptions.java | 13 +- .../core/options/QueryFormattingOptions.java | 11 +- .../options/SpacingFormattingOptions.java | 17 +- .../options/WrappingFormattingOptions.java | 16 +- .../main/resources/format-toml-schema.json | 151 ++++++++++++++++++ .../src/main/resources/formatter.properties | 2 +- 17 files changed, 297 insertions(+), 196 deletions(-) create mode 100644 misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal index 95031e114bb8..6075d4041ccf 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal @@ -1,14 +1,22 @@ import ballerina/io; -function sendEmail(string sender, string recipient, string subject, string message) returns boolean { +function sendEmail(string sender, string recipient, string subject, + string message) returns boolean { return true; } public function main() { - boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + boolean isEmailSent = sendEmail( + "sender@example.com", "recipient@example.com", + "This is a test email from Ballerina.", "Hello from Ballerina" + ); if (isEmailSent) { - io:println("Email sent successfully!"); + io:println( + "Email sent successfully!" + ); } else { - io:println("Email sending failed."); + io:println( + "Email sending failed." + ); } } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml index 7635233381c7..10d58a05e0bc 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml @@ -1,5 +1,4 @@ [wrapping] maxLineLength = 80 -keepLineBreaks = true simpleBlocksInOneLine = true simpleMethodsInOneLine = true diff --git a/misc/formatter/modules/formatter-core/src/main/java/module-info.java b/misc/formatter/modules/formatter-core/src/main/java/module-info.java index e5138a285491..5df52a1830d6 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/module-info.java +++ b/misc/formatter/modules/formatter-core/src/main/java/module-info.java @@ -1,10 +1,10 @@ module io.ballerina.formatter.core { requires io.ballerina.lang; requires io.ballerina.parser; + requires io.ballerina.toml; requires io.ballerina.tools.api; requires org.apache.commons.lang3; requires org.slf4j; - requires io.ballerina.toml; exports org.ballerinalang.formatter.core; exports org.ballerinalang.formatter.core.options; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index d80a539bdb25..80359065c03a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -25,14 +25,18 @@ import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; import io.ballerina.projects.PackageManifest; +import io.ballerina.projects.ProjectException; import io.ballerina.projects.TomlDocument; -import io.ballerina.toml.semantic.ast.TomlTableNode; +import io.ballerina.projects.util.FileUtils; +import io.ballerina.toml.api.Toml; +import io.ballerina.toml.validator.TomlValidator; +import io.ballerina.toml.validator.schema.Schema; +import io.ballerina.tools.diagnostics.Diagnostic; +import io.ballerina.tools.diagnostics.DiagnosticSeverity; import io.ballerina.tools.text.LineRange; import org.apache.commons.lang3.builder.CompareToBuilder; import org.ballerinalang.formatter.core.options.FormatSection; import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -40,6 +44,7 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; +import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -56,14 +61,15 @@ * Class that contains the util functions used by the formatting tree modifier. */ public class FormatterUtils { - - private static Logger logger = LoggerFactory.getLogger("Formatter"); static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); static final String FORMAT_FILE_FIELD = "configPath"; static final String FORMAT_OPTION_FILE_EXT = ".toml"; static final String DEFAULT_FORMAT_OPTION_FILE = "Format.toml"; static final String TARGET_DIR = "target"; static final String FORMAT = "format"; + static final String FORMAT_TOML_SCHEMA = "format-toml-schema.json"; + private static final PrintStream errStream = System.err; + public static final ResourceBundle DEFAULTS = ResourceBundle.getBundle("formatter", Locale.getDefault()); private FormatterUtils() { @@ -86,7 +92,7 @@ public static Object loadFormatSection(PackageManifest manifest) { } public static void warning(String message) { - logger.warn(message); + errStream.println(message); } public static String getFormattingFilePath(Object formatSection, String root) { @@ -101,16 +107,8 @@ public static String getFormattingFilePath(Object formatSection, String root) { } } - File directory = new File(root); - File[] files = directory.listFiles(); - if (files != null) { - for (File file : files) { - if (file.isFile() && file.getName().equals(DEFAULT_FORMAT_OPTION_FILE)) { - return file.getAbsolutePath(); - } - } - } - return null; + Path defaultFile = Path.of(root, DEFAULT_FORMAT_OPTION_FILE); + return Files.exists(defaultFile) ? defaultFile.toString() : null; } public static Map getFormattingConfigurations(Path root, String path) throws FormatterException { @@ -146,20 +144,18 @@ static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterEx try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - int responseCode = connection.getResponseCode(); - - if (responseCode == HttpURLConnection.HTTP_OK) { - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - fileContent.append(line).append(NEWLINE_SYMBOL); - } - } - } else { + if (responseCode != HttpURLConnection.HTTP_OK) { + connection.disconnect(); throw new FormatterException("Failed to retrieve remote file. HTTP response code: " + responseCode); } + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + fileContent.append(line).append(NEWLINE_SYMBOL); + } + } connection.disconnect(); } catch (IOException e) { throw new FormatterException("Failed to retrieve formatting configuration file"); @@ -170,30 +166,51 @@ static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterEx } private static void cacheRemoteConfigurationFile(Path root, String content) throws FormatterException { - if (Files.exists(root.resolve(TARGET_DIR))) { - if (!Files.exists(root.resolve(TARGET_DIR).resolve(FORMAT))) { - try { - Files.createDirectories(root.resolve(TARGET_DIR).resolve(FORMAT)); - } catch (IOException e) { - throw new FormatterException("Failed to create format configuration cache directory"); - } - } - String filePath = root.resolve(TARGET_DIR).resolve(FORMAT).resolve(DEFAULT_FORMAT_OPTION_FILE) - .toString(); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, StandardCharsets.UTF_8))) { - writer.write(content); + Path targetDir = root.resolve(TARGET_DIR); + if (!Files.exists(targetDir)) { + return; + } + Path formatDir = targetDir.resolve(FORMAT); + if (!Files.exists(formatDir)) { + try { + Files.createDirectories(formatDir); } catch (IOException e) { - throw new FormatterException("Failed to write format configuration cache file"); + throw new FormatterException("Failed to create format configuration cache directory"); } } + String filePath = formatDir.resolve(DEFAULT_FORMAT_OPTION_FILE).toString(); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, StandardCharsets.UTF_8))) { + writer.write(content); + } catch (IOException e) { + throw new FormatterException("Failed to write format configuration cache file"); + } } - public static Map parseConfigurationToml(TomlDocument document) { - TomlTableNode tomlAstNode = document.toml().rootNode(); - if (!tomlAstNode.entries().isEmpty()) { - return document.toml().toMap(); + public static Map parseConfigurationToml(TomlDocument document) throws FormatterException { + Toml toml = document.toml(); + if (toml.rootNode().entries().isEmpty()) { + return new HashMap<>(); + } + TomlValidator formatTomlValidator; + try { + formatTomlValidator = new TomlValidator(Schema.from(FileUtils.readFileAsString(FORMAT_TOML_SCHEMA))); + } catch (IOException e) { + throw new ProjectException("Failed to read the Format.toml validator schema file."); + } + formatTomlValidator.validate(toml); + + List diagnostics = toml.diagnostics(); + boolean hasErrors = false; + for (Diagnostic d: diagnostics) { + if (d.diagnosticInfo().severity().equals(DiagnosticSeverity.ERROR)) { + errStream.println(d.message()); + hasErrors = true; + } + } + if (hasErrors) { + throw new FormatterException("Invalid Format.toml file"); } - return new HashMap<>(); + return toml.toMap(); } static boolean isInlineRange(Node node, LineRange lineRange) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index eb99ac73ac2e..02c5b59508f5 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -325,8 +325,7 @@ public FunctionDefinitionNode transform(FunctionDefinitionNode functionDefinitio NodeList relativeResourcePath = formatNodeList(functionDefinitionNode.relativeResourcePath(), 0, 0, 0, 0); int trailingNL = options.braceFormattingOptions().methodBraceStyle() == BraceStyle.NewLine ? 1 : 0; FunctionSignatureNode functionSignatureNode = - formatNode(functionDefinitionNode.functionSignature(), 1 - trailingNL, - trailingNL); + formatNode(functionDefinitionNode.functionSignature(), invert(trailingNL), trailingNL); FunctionBodyNode functionBodyNode = formatNode(functionDefinitionNode.functionBody(), env.trailingWS, env.trailingNL); @@ -461,10 +460,10 @@ public IncludedRecordParameterNode transform(IncludedRecordParameterNode include @Override public FunctionBodyBlockNode transform(FunctionBodyBlockNode functionBodyBlockNode) { int trailingNL = openBraceTrailingNLs(options.wrappingFormattingOptions(), functionBodyBlockNode); - Token openBrace = formatToken(functionBodyBlockNode.openBraceToken(), 1 - trailingNL, trailingNL); + Token openBrace = formatToken(functionBodyBlockNode.openBraceToken(), invert(trailingNL), trailingNL); indent(); // increase indentation for the statements to follow. NodeList statements = - formatNodeList(functionBodyBlockNode.statements(), 0, 1, 1 - trailingNL, trailingNL); + formatNodeList(functionBodyBlockNode.statements(), 0, 1, invert(trailingNL), trailingNL); NamedWorkerDeclarator namedWorkerDeclarator = formatNode(functionBodyBlockNode.namedWorkerDeclarator().orElse(null), 0, 1); @@ -579,7 +578,7 @@ public BlockStatementNode transform(BlockStatementNode blockStatementNode) { boolean preserveIndent = env.preserveIndentation; preserveIndentation(blockStatementNode.openBraceToken().isMissing() && preserveIndent); int trailingNL = openBraceTrailingNLs(options.wrappingFormattingOptions(), blockStatementNode); - int trailingWS = 1 - trailingNL; + int trailingWS = invert(trailingNL); Token openBrace = formatToken(blockStatementNode.openBraceToken(), trailingWS, trailingNL); preserveIndentation(preserveIndent); indent(); // start an indentation @@ -1096,13 +1095,8 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC NameReferenceNode functionName = formatNode(functionCallExpressionNode.functionName(), 0, 0); FunctionCallFormattingOptions callOptions = options.functionCallFormattingOptions(); int prevIndentation = env.currentIndentation; -// if (functionCallExpressionNode.arguments().size() > 0) { -// if (!isScopedFunctionArgument(functionCallExpressionNode.arguments().get(0))) { -// indented = true; - alignOrIndent(callOptions.alignMultilineParameters(), - options.indentFormattingOptions().continuationIndentSize()); -// } -// } + alignOrIndent(callOptions.alignMultilineParameters(), + options.indentFormattingOptions().continuationIndentSize()); Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, callOptions.newLineAfterLeftParen() ? 1 : 0); @@ -1114,9 +1108,6 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC setIndentation(prevIndentation); Token functionCallClosePara = formatToken(functionCallExpressionNode.closeParenToken(), env.trailingWS, env.trailingNL); -// if (indented) { - -// } return functionCallExpressionNode.modify() .withFunctionName(functionName) .withOpenParenToken(functionCallOpenPara) @@ -3536,8 +3527,7 @@ public ClassDefinitionNode transform(ClassDefinitionNode classDefinitionNode) { NodeList classTypeQualifiers = formatNodeList(classDefinitionNode.classTypeQualifiers(), 1, 0, 1, 0); Token classKeyword = formatToken(classDefinitionNode.classKeyword(), 1, 0); int trailingNL = options.braceFormattingOptions().classBraceStyle() == BraceStyle.NewLine ? 1 : 0; - Token className = formatToken(classDefinitionNode.className(), 1 - trailingNL, - trailingNL); + Token className = formatToken(classDefinitionNode.className(), invert(trailingNL), trailingNL); Token openBrace = formatToken(classDefinitionNode.openBrace(), 0, 1); indent(); @@ -4961,4 +4951,9 @@ private boolean hasLeadingComments(Node node) { } return false; } + + private int invert(int val) { + int inverted = 1 - val; + return inverted >= 0 ? inverted : 0; + } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 8ff3652b95a1..8282f7d62c13 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -77,15 +77,9 @@ public BraceFormattingOptions build(Map configs) throws Formatte String bracesKey = bracesEntry.getKey(); BraceStyle style = BraceStyle.fromString((String) bracesEntry.getValue()); switch (bracesKey) { - case CLASS_BRACE_STYLE: - setClassBraceStyle(style); - break; - case METHOD_BRACE_STYLE: - setMethodBraceStyle(style); - break; - default: - warning("Invalid Brace Option: " + bracesKey); - break; + case CLASS_BRACE_STYLE -> setClassBraceStyle(style); + case METHOD_BRACE_STYLE -> setMethodBraceStyle(style); + default -> warning("Invalid Brace Option: " + bracesKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 4396c8ccce71..d0c6220ca439 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -192,36 +192,19 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter Map configs = (Map) value; FormatSection section = FormatSection.fromString(key); switch (section) { - case INDENT: - indentFormattingOptions = IndentFormattingOptions.builder().build(configs); - break; - case WRAPPING: - wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); - break; - case BRACES: - braceFormattingOptions = BraceFormattingOptions.builder().build(configs); - break; - case METHOD_DECLARATION: - functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); - break; - case METHOD_CALL: - functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); - break; - case IF_STATEMENT: - ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); - break; - case QUERY: - queryFormattingOptions = QueryFormattingOptions.builder().build(configs); - break; - case SPACING: - spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); - break; - case IMPORT: - importFormattingOptions = ImportFormattingOptions.builder().build(configs); - break; - default: - warning("Invalid formatting option section : " + section); - break; + case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build(configs); + case WRAPPING -> wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); + case BRACES -> braceFormattingOptions = BraceFormattingOptions.builder().build(configs); + case METHOD_DECLARATION -> + functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); + case METHOD_CALL -> + functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); + case IF_STATEMENT -> + ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); + case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build(configs); + case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); + case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build(configs); + default -> warning("Invalid formatting option section : " + section); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index cdd9f72b80a6..e5dbfdc1aa8c 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -110,24 +110,15 @@ public FunctionCallFormattingOptions build() { } public FunctionCallFormattingOptions build(Map configs) throws FormatterException { - for (Map.Entry methodCallEntry : configs.entrySet()) { - String methodCallKey = methodCallEntry.getKey(); - switch (methodCallKey) { - case PARAMETERS_WRAP: - setParametersWrap(WrappingMethod.fromString((String) methodCallEntry.getValue())); - break; - case ALIGN_MULTILINE_PARAMETERS: - setAlignMultilineParameters((Boolean) methodCallEntry.getValue()); - break; - case NEWLINE_AFTER_LEFT_PAREN: - setNewLineAfterLeftParen((Boolean) methodCallEntry.getValue()); - break; - case RIGHT_PAREN_ON_NEWLINE: - setRightParenOnNewLine((Boolean) methodCallEntry.getValue()); - break; - default: - warning("Invalid function call formatting option: " + methodCallKey); - break; + for (Map.Entry funcCallEntry : configs.entrySet()) { + String funcCallKey = funcCallEntry.getKey(); + switch (funcCallKey) { + case PARAMETERS_WRAP -> + setParametersWrap(WrappingMethod.fromString((String) funcCallEntry.getValue())); + case ALIGN_MULTILINE_PARAMETERS -> setAlignMultilineParameters((Boolean) funcCallEntry.getValue()); + case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) funcCallEntry.getValue()); + case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) funcCallEntry.getValue()); + default -> warning("Invalid function call formatting option: " + funcCallKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index db3dcf340354..41cc708b76b8 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -107,21 +107,14 @@ public FunctionDeclFormattingOptions build(Map configs) throws F for (Map.Entry methodDeclarationEntry : configs.entrySet()) { String methodDeclarationKey = methodDeclarationEntry.getKey(); switch (methodDeclarationKey) { - case PARAMETERS_WRAP: - setParametersWrap(WrappingMethod.fromString((String) methodDeclarationEntry.getValue())); - break; - case ALIGN_MULTILINE_PARAMETERS: - setAlignMultilineParameters((Boolean) methodDeclarationEntry.getValue()); - break; - case NEWLINE_AFTER_LEFT_PAREN: - setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); - break; - case RIGHT_PAREN_ON_NEWLINE: - setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); - break; - default: - warning("Invalid function declaration formatting option: " + methodDeclarationKey); - break; + case PARAMETERS_WRAP -> + setParametersWrap(WrappingMethod.fromString((String) methodDeclarationEntry.getValue())); + case ALIGN_MULTILINE_PARAMETERS -> + setAlignMultilineParameters((Boolean) methodDeclarationEntry.getValue()); + case NEWLINE_AFTER_LEFT_PAREN -> + setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); + case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); + default -> warning("Invalid function declaration formatting option: " + methodDeclarationKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index ef3bc38fc8f4..1cb3a8e8bbf2 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -58,13 +58,10 @@ public IfStatementFormattingOptions build() { public IfStatementFormattingOptions build(Map configs) { for (Map.Entry ifStatementEntry : configs.entrySet()) { String ifStatementKey = ifStatementEntry.getKey(); - switch (ifStatementKey) { - case ELSE_ON_NEW_LINE: - setElseOnNewLine((Boolean) ifStatementEntry.getValue()); - break; - default: - warning("Invalid if statement formatting option: " + ifStatementKey); - break; + if (ifStatementKey.equals(ELSE_ON_NEW_LINE)) { + setElseOnNewLine((Boolean) ifStatementEntry.getValue()); + } else { + warning("Invalid if statement formatting option: " + ifStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index c4c2ff958400..f15ffe8a5a60 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -89,15 +89,9 @@ public ImportFormattingOptions build(Map configs) { for (Map.Entry importEntry : configs.entrySet()) { String importKey = importEntry.getKey(); switch (importKey) { - case SORT_IMPORTS: - setSortImports((Boolean) importEntry.getValue()); - break; - case GROUP_IMPORTS: - setGroupImports((Boolean) importEntry.getValue()); - break; - default: - warning("Invalid import formatting option: " + importKey); - break; + case SORT_IMPORTS -> setSortImports((Boolean) importEntry.getValue()); + case GROUP_IMPORTS -> setGroupImports((Boolean) importEntry.getValue()); + default -> warning("Invalid import formatting option: " + importKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index 841827898b0d..e1540257f983 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -82,15 +82,10 @@ public IndentFormattingOptions build(Map configs) { for (Map.Entry indentEntry : configs.entrySet()) { String indentKey = indentEntry.getKey(); switch (indentKey) { - case INDENT_SIZE: - setIndentSize(((Number) indentEntry.getValue()).intValue()); - break; - case CONTINUATION_INDENT_SIZE: - setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); - break; - default: - warning("Invalid indent formatting option: " + indentKey); - break; + case INDENT_SIZE -> setIndentSize(((Number) indentEntry.getValue()).intValue()); + case CONTINUATION_INDENT_SIZE -> + setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); + default -> warning("Invalid indent formatting option: " + indentKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index 9f9af291d284..d4467d73be93 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -58,13 +58,10 @@ public QueryFormattingOptions build() { public QueryFormattingOptions build(Map configs) { for (Map.Entry queryStatementEntry : configs.entrySet()) { String queryStatementKey = queryStatementEntry.getKey(); - switch (queryStatementKey) { - case ALIGN_MULTILINE_QUERIES: - setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); - break; - default: - warning("Invalid query formatting option: " + queryStatementKey); - break; + if (queryStatementKey.equals(ALIGN_MULTILINE_QUERIES)) { + setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); + } else { + warning("Invalid query formatting option: " + queryStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 20f09ffe2b8a..90829635a3c3 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -87,18 +87,11 @@ public SpacingFormattingOptions build(Map configs) { for (Map.Entry spacingEntry : configs.entrySet()) { String spacingKey = spacingEntry.getKey(); switch (spacingKey) { - case AFTER_TYPE_CAST: - setAfterTypeCast((Boolean) spacingEntry.getValue()); - break; - case AROUND_RECORD_BRACES: - setAroundRecordBraces((Boolean) spacingEntry.getValue()); - break; - case ALIGN_CONSECUTIVE_DEFINITIONS: - setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); - break; - default: - warning("Invalid spacing formatting option: " + spacingKey); - break; + case AFTER_TYPE_CAST -> setAfterTypeCast((Boolean) spacingEntry.getValue()); + case AROUND_RECORD_BRACES -> setAroundRecordBraces((Boolean) spacingEntry.getValue()); + case ALIGN_CONSECUTIVE_DEFINITIONS -> + setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); + default -> warning("Invalid spacing formatting option: " + spacingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index 4930c75bd95d..0407292855ab 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -103,19 +103,13 @@ public WrappingFormattingOptions build(Map configs) { for (Map.Entry wrappingEntry : configs.entrySet()) { String wrappingKey = wrappingEntry.getKey(); switch (wrappingKey) { - case MAX_LINE_LENGTH: + case MAX_LINE_LENGTH -> { setMaxLineLength(((Number) wrappingEntry.getValue()).intValue()); setLineWrap(true); - break; - case SIMPLE_BLOCKS_IN_ONE_LINE: - setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); - break; - case SIMPLE_METHODS_IN_ONE_LINE: - setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); - break; - default: - warning("Invalid wrapping formatting option: " + wrappingKey); - break; + } + case SIMPLE_BLOCKS_IN_ONE_LINE -> setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); + case SIMPLE_METHODS_IN_ONE_LINE -> setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); + default -> warning("Invalid wrapping formatting option: " + wrappingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json new file mode 100644 index 000000000000..cef3a8733c04 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json @@ -0,0 +1,151 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Format Toml Spec", + "description": "Schema for Format Toml", + "type": "object", + "additionalProperties": true, + "properties": { + "braces": { + "type": "object", + "additionalProperties": false, + "properties": { + "classBraceStyle": { + "type": "string", + "pattern": "\\b(?:NewLine|EndOfLine)\\b", + "message": { + "pattern": "Invalid value for 'classBraceStyle'. Only 'NewLine' or 'EndOfLine' are allowed." + } + }, + "methodBraceStyle": { + "type": "string", + "pattern": "\\b(?:NewLine|EndOfLine)\\b", + "message": { + "pattern": "Invalid value for 'methodBraceStyle'. Only 'NewLine' or 'EndOfLine' are allowed." + } + } + } + }, + "methodCall": { + "type": "object", + "additionalProperties": false, + "properties": { + "parametersWrap": { + "type": "string", + "pattern": "\\b(?:Wrap|NoWrap|ChopDown)\\b", + "message": { + "pattern": "Invalid wrapping style. Only, 'Wrap', 'NoWrap', or 'ChopDown' is allowed." + } + }, + "alignMultilineParameters": { + "type": "boolean" + }, + "newLineAfterLeftParen": { + "type": "boolean" + }, + "rightParenOnNewLine": { + "type": "boolean" + } + } + }, + "methodDeclaration": { + "type": "object", + "additionalProperties": false, + "properties": { + "parametersWrap": { + "type": "string", + "pattern": "\\b(?:Wrap|NoWrap|ChopDown)\\b", + "message": { + "pattern": "Invalid wrapping style. Only, 'Wrap', 'NoWrap', or 'ChopDown' is allowed." + } + }, + "alignMultilineParameters": { + "type": "boolean" + }, + "newLineAfterLeftParen": { + "type": "boolean" + }, + "rightParenOnNewLine": { + "type": "boolean" + } + } + }, + "ifStatement": { + "type": "object", + "additionalProperties": false, + "properties": { + "elseOnNewLine": { + "type": "boolean" + } + } + }, + "import": { + "type": "object", + "additionalProperties": false, + "properties": { + "groupImports": { + "type": "boolean" + }, + "sortImports": { + "type": "boolean" + }, + "removeUnusedImports": { + "type": "boolean" + } + } + }, + "indent": { + "type": "object", + "additionalProperties": false, + "properties": { + "indentSize": { + "type": "integer" + }, + "continuationIndentSize": { + "type": "integer" + } + } + }, + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "alignMultiLineQueries": { + "type": "boolean" + } + } + }, + "spacing": { + "type": "object", + "additionalProperties": false, + "properties": { + "afterTypeCast": { + "type": "boolean" + }, + "aroundRecordBraces": { + "type": "boolean" + }, + "alignConsecutiveDefinitions": { + "type": "boolean" + } + } + }, + "wrapping": { + "type": "object", + "additionalProperties": true, + "properties": { + "maxLineLength": { + "type": "integer" + }, + "lineWrap": { + "type": "boolean" + }, + "simpleBlocksInOneLine": { + "type": "boolean" + }, + "simpleMethodsInOneLine": { + "type": "boolean" + } + } + } + } +} diff --git a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties index 592edc831faa..efbde00fb3b7 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties +++ b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties @@ -44,4 +44,4 @@ spacing.alignConsecutiveDefinitions=false wrapping.maxLineLength=120 wrapping.lineWrap=false wrapping.simpleBlocksInOneLine=false -wrapping.simpleMethodsInOneLine=false \ No newline at end of file +wrapping.simpleMethodsInOneLine=false From 8ca229228d29a938432fcde9823c411b23f3ca6b Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Wed, 6 Mar 2024 15:31:50 +0530 Subject: [PATCH 13/22] Change defaults to asserts --- .../org/ballerinalang/formatter/core/FormatterUtils.java | 6 +----- .../formatter/core/options/BraceFormattingOptions.java | 5 +++-- .../ballerinalang/formatter/core/options/BraceStyle.java | 3 ++- .../ballerinalang/formatter/core/options/FormatSection.java | 3 ++- .../formatter/core/options/FormattingOptions.java | 6 ++++-- .../core/options/FunctionCallFormattingOptions.java | 6 ++++-- .../core/options/FunctionDeclFormattingOptions.java | 6 ++++-- .../core/options/IfStatementFormattingOptions.java | 3 +-- .../formatter/core/options/ImportFormattingOptions.java | 5 +++-- .../formatter/core/options/IndentFormattingOptions.java | 5 +++-- .../formatter/core/options/QueryFormattingOptions.java | 3 +-- .../formatter/core/options/SpacingFormattingOptions.java | 5 +++-- .../formatter/core/options/WrappingFormattingOptions.java | 6 +++--- .../formatter/core/options/WrappingMethod.java | 3 ++- 14 files changed, 36 insertions(+), 29 deletions(-) diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 80359065c03a..42a5acf9d7b1 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -91,10 +91,6 @@ public static Object loadFormatSection(PackageManifest manifest) { return manifest.getValue(FORMAT); } - public static void warning(String message) { - errStream.println(message); - } - public static String getFormattingFilePath(Object formatSection, String root) { if (formatSection != null) { Object path = ((Map) formatSection).get(FORMAT_FILE_FIELD); @@ -126,7 +122,7 @@ public static Map getFormattingConfigurations(Path root, String return parseConfigurationToml(TomlDocument.from(path, content)); } - public static boolean isLocalFile(String path) { + private static boolean isLocalFile(String path) { return new File(path).exists(); } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 8282f7d62c13..238dcc6399f4 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -20,7 +20,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of brace settings by the API user, that could be passed onto the formatter. @@ -79,7 +78,9 @@ public BraceFormattingOptions build(Map configs) throws Formatte switch (bracesKey) { case CLASS_BRACE_STYLE -> setClassBraceStyle(style); case METHOD_BRACE_STYLE -> setMethodBraceStyle(style); - default -> warning("Invalid Brace Option: " + bracesKey); + default -> { + assert false : "Include the brace formatting option " + bracesKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index dc379f2ded0e..b69fc3c309e4 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -30,7 +30,8 @@ public static BraceStyle fromString(String value) throws FormatterException { try { return BraceStyle.valueOf(value); } catch (IllegalArgumentException e) { - throw new FormatterException("Invalid Brace style: " + value); + assert false : "Include the brace style " + value + " in the validator"; + return EndOfLine; } } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java index 295113e84ab4..322f6d8fa303 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -49,6 +49,7 @@ public static FormatSection fromString(String value) throws FormatterException { return section; } } - throw new FormatterException("Invalid format section: " + value); + assert false : "Include the format section " + value + " in the validator"; + return null; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index d0c6220ca439..19fb8b308edb 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -22,7 +22,6 @@ import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingFilePath; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting options that could be passed onto the formatter. @@ -204,7 +203,10 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build(configs); case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build(configs); - default -> warning("Invalid formatting option section : " + section); + default -> { + assert false : + "Include the formatting section " + section + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index e5dbfdc1aa8c..8cec5554ba89 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -21,7 +21,6 @@ import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of if statement by the API user, that could be passed onto the formatter. @@ -118,7 +117,10 @@ public FunctionCallFormattingOptions build(Map configs) throws F case ALIGN_MULTILINE_PARAMETERS -> setAlignMultilineParameters((Boolean) funcCallEntry.getValue()); case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) funcCallEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) funcCallEntry.getValue()); - default -> warning("Invalid function call formatting option: " + funcCallKey); + default -> { + assert false : + "Include the function call formatting option " + funcCallKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index 41cc708b76b8..71cacb74c097 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -21,7 +21,6 @@ import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultString; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of function declarations by the API user, that could be passed onto the formatter. @@ -114,7 +113,10 @@ public FunctionDeclFormattingOptions build(Map configs) throws F case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); - default -> warning("Invalid function declaration formatting option: " + methodDeclarationKey); + default -> { + assert false : "Include the function declaration formatting option " + methodDeclarationKey + + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index 1cb3a8e8bbf2..8d5f1dba6ee6 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -18,7 +18,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of indent settings by the API user, that could be passed onto the formatter. @@ -61,7 +60,7 @@ public IfStatementFormattingOptions build(Map configs) { if (ifStatementKey.equals(ELSE_ON_NEW_LINE)) { setElseOnNewLine((Boolean) ifStatementEntry.getValue()); } else { - warning("Invalid if statement formatting option: " + ifStatementKey); + assert false : "Include the if statement formatting option " + ifStatementKey + " in the validator"; } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index f15ffe8a5a60..dea010b5e3ed 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -18,7 +18,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting and optimizing imports by the API user, that could be passed onto the formatter. @@ -91,7 +90,9 @@ public ImportFormattingOptions build(Map configs) { switch (importKey) { case SORT_IMPORTS -> setSortImports((Boolean) importEntry.getValue()); case GROUP_IMPORTS -> setGroupImports((Boolean) importEntry.getValue()); - default -> warning("Invalid import formatting option: " + importKey); + default -> { + assert false : "Include the import formatting option " + importKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index e1540257f983..7bab827cbc15 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -18,7 +18,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultInt; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of indent settings by the API user, that could be passed onto the formatter. @@ -85,7 +84,9 @@ public IndentFormattingOptions build(Map configs) { case INDENT_SIZE -> setIndentSize(((Number) indentEntry.getValue()).intValue()); case CONTINUATION_INDENT_SIZE -> setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); - default -> warning("Invalid indent formatting option: " + indentKey); + default -> { + assert false : "Include the import formatting option " + indentKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index d4467d73be93..460dcd2ac7a5 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -18,7 +18,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of the queries by the API user, that could be passed onto the formatter. @@ -61,7 +60,7 @@ public QueryFormattingOptions build(Map configs) { if (queryStatementKey.equals(ALIGN_MULTILINE_QUERIES)) { setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); } else { - warning("Invalid query formatting option: " + queryStatementKey); + assert false : "Include the query formatting option " + queryStatementKey + " in the validator"; } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 90829635a3c3..1166c8f1aa5a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -18,7 +18,6 @@ import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; /** * A model for formatting of spacing by the API user, that could be passed onto the formatter. @@ -91,7 +90,9 @@ public SpacingFormattingOptions build(Map configs) { case AROUND_RECORD_BRACES -> setAroundRecordBraces((Boolean) spacingEntry.getValue()); case ALIGN_CONSECUTIVE_DEFINITIONS -> setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); - default -> warning("Invalid spacing formatting option: " + spacingKey); + default -> { + assert false : "Include the spacing formatting option " + spacingKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index 0407292855ab..828d603b55a7 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -19,8 +19,6 @@ import java.util.Map; -import static org.ballerinalang.formatter.core.FormatterUtils.warning; - /** * A model for formatting of wrapping settings by the API user, that could be passed onto the formatter. * @@ -109,7 +107,9 @@ public WrappingFormattingOptions build(Map configs) { } case SIMPLE_BLOCKS_IN_ONE_LINE -> setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); case SIMPLE_METHODS_IN_ONE_LINE -> setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); - default -> warning("Invalid wrapping formatting option: " + wrappingKey); + default -> { + assert false : "Include the wrapping formatting option " + wrappingKey + " in the validator"; + } } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index f139b3c83102..a70bb160d6ba 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -31,7 +31,8 @@ public static WrappingMethod fromString(String value) throws FormatterException try { return WrappingMethod.valueOf(value); } catch (IllegalArgumentException e) { - throw new FormatterException("Invalid wrapping method: " + value); + assert false : "Include the wrapping method " + value + " in the validator"; + return NoWrap; } } From e9e4661c911f595ea02c762cb174cecec6821488 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Sun, 10 Mar 2024 17:33:28 +0530 Subject: [PATCH 14/22] Add validator and resolution test --- .../formatter/cli/FormatCmdTest.java | 74 +++++++-- .../brace/source/project/Ballerina.toml | 2 - .../functionCall/assert/wrap/main.bal | 22 --- .../source/chopDown/Ballerina.toml | 2 - .../functionCall/source/noWrap/Ballerina.toml | 2 - .../functionCall/source/wrap/Ballerina.toml | 2 - .../source/chopDown/Ballerina.toml | 2 - .../source/wrap/Ballerina.toml | 2 - .../ifStatement/source/ifelse/Ballerina.toml | 2 - .../imports/source/project/Ballerina.toml | 2 - .../configurations/module/assert/main.bal | 7 + .../module/assert/modules/core/core.bal | 15 ++ .../source/project}/Ballerina.toml | 0 .../module/source/project/Format.toml | 14 ++ .../module/source/project/main.bal | 7 + .../source/project/modules/core/core.bal | 13 ++ .../module/source/projectTemp/main.bal | 7 + .../source/projectTemp/modules/core/core.bal | 13 ++ .../brace/assert/project/main.bal | 0 .../brace/source/project/Ballerina.toml | 2 + .../brace/source/project/Format.toml | 0 .../brace/source/project/main.bal | 0 .../brace/source/projectTemp/main.bal | 0 .../functionCall/assert/chopDown/main.bal | 0 .../functionCall/assert/noWrap/main.bal | 0 .../functionCall/assert}/wrap/main.bal | 0 .../source/chopDown/Ballerina.toml | 2 + .../functionCall/source/chopDown/Format.toml | 0 .../functionCall/source/chopDown/main.bal | 0 .../functionCall/source/chopDownTemp/main.bal | 0 .../functionCall/source/noWrap/Ballerina.toml | 2 + .../functionCall/source/noWrap/Format.toml | 0 .../functionCall/source/noWrap/main.bal | 0 .../functionCall/source/noWrapTemp/main.bal | 0 .../functionCall/source/wrap/Ballerina.toml | 2 + .../functionCall/source/wrap/Format.toml | 0 .../functionCall/source/wrap}/main.bal | 0 .../functionCall/source/wrapTemp/main.bal | 14 ++ .../assert/chopDown/main.bal | 0 .../assert/noWrap/main.bal | 0 .../functionDeclaration/assert/wrap/main.bal | 0 .../source/chopDown/Ballerina.toml | 2 + .../source/chopDown/Format.toml | 0 .../source/chopDown/main.bal | 0 .../source/chopDownTemp/main.bal | 0 .../source/noWrap}/Ballerina.toml | 0 .../source/noWrap/Format.toml | 0 .../source/noWrap/main.bal | 0 .../source/noWrapTemp/main.bal | 0 .../source/wrap/Ballerina.toml | 2 + .../source/wrap/Format.toml | 0 .../functionDeclaration/source/wrap/main.bal | 0 .../source/wrapTemp/main.bal | 0 .../ifStatement/assert/ifelse/main.bal | 0 .../ifStatement/source/ifelse/Ballerina.toml | 2 + .../ifStatement/source/ifelse/Format.toml | 0 .../ifStatement/source/ifelse/main.bal | 0 .../ifStatement/source/ifelseTemp/main.bal | 0 .../imports/assert/project/main.bal | 0 .../imports/source/project/Ballerina.toml | 2 + .../imports/source/project/Format.toml | 0 .../imports/source/project/main.bal | 0 .../imports/source/projectTemp/main.bal | 0 .../indent/assert/project/main.bal | 0 .../indent}/source/project/Ballerina.toml | 0 .../indent/source/project/Format.toml | 0 .../indent/source/project/main.bal | 0 .../indent/source/projectTemp/main.bal | 0 .../query/assert/project/main.bal | 0 .../query/source/project/Ballerina.toml | 2 + .../query/source/project/Format.toml | 0 .../query/source/project/main.bal | 0 .../query/source/projectTemp/main.bal | 0 .../spacing/assert/project/main.bal | 0 .../spacing/source/project/Ballerina.toml | 2 + .../spacing/source/project/Format.toml | 0 .../spacing/source/project/main.bal | 0 .../spacing/source/projectTemp/main.bal | 0 .../wrapping/assert/project/main.bal | 0 .../wrapping/source/project/Ballerina.toml | 0 .../wrapping/source/project/Format.toml | 0 .../wrapping/source/project/main.bal | 0 .../wrapping/source/projectTemp/main.bal | 0 .../projectWithModule/assert/main.bal | 3 + .../assert/modules/mod/mod.bal | 15 ++ .../source/project/Ballerina.toml | 0 .../source/project/Format.toml | 13 ++ .../projectWithModule/source/project/main.bal | 3 + .../source/project/modules/mod/mod.bal | 13 ++ .../source/projectTemp/main.bal | 3 + .../source/projectTemp/modules/mod/mod.bal | 13 ++ .../query/source/project/Ballerina.toml | 2 - .../spacing/source/project/Ballerina.toml | 2 - .../FormatFileResolutionTest.java | 155 ++++++++++++++++++ .../FormatFileValidatorTest.java | 48 ++++++ .../resolution/validLocal/Format.toml | 0 .../validator/invalid/Format.toml | 25 +++ .../validator/valid/Format.toml | 31 ++++ 98 files changed, 493 insertions(+), 55 deletions(-) delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/modules/core/core.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functionDeclaration/source/noWrap => module/source/project}/Ballerina.toml (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/modules/core/core.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/modules/core/core.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/brace/assert/project/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/brace/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/brace/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/brace/source/projectTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/assert/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/assert/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functionCall/source => options/functionCall/assert}/wrap/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/chopDown/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/chopDownTemp/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/noWrap/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/noWrapTemp/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionCall/source/wrap/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{functionCall/source/wrapTemp => options/functionCall/source/wrap}/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrapTemp/main.bal rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/assert/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/assert/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/assert/wrap/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/chopDown/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/chopDownTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{indent/source/project => options/functionDeclaration/source/noWrap}/Ballerina.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/noWrap/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/noWrapTemp/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/wrap/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/wrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/functionDeclaration/source/wrapTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/ifStatement/assert/ifelse/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/ifStatement/source/ifelse/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/ifStatement/source/ifelse/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/ifStatement/source/ifelseTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/imports/assert/project/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/imports/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/imports/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/imports/source/projectTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/indent/assert/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{wrapping => options/indent}/source/project/Ballerina.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/indent/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/indent/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/indent/source/projectTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/query/assert/project/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/query/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/query/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/query/source/projectTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/spacing/assert/project/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/spacing/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/spacing/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/spacing/source/projectTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/wrapping/assert/project/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/wrapping/source/project/Format.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/wrapping/source/project/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/{ => options}/wrapping/source/projectTemp/main.bal (100%) create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/modules/mod/mod.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/modules/mod/mod.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/main.bal create mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/modules/mod/mod.bal delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml delete mode 100644 misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java create mode 100644 misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validLocal/Format.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index d1165e0929ac..0a16271e30f6 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -106,35 +106,37 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< private Object[][] provideConfigurationProjects() { return new Object[][]{ {"brace", List.of( - RES_DIR.resolve("configurations/brace/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "brace", "source", "project")) )}, {"functionCall", List.of( - RES_DIR.resolve("configurations/functionCall/source/chopDown"), - RES_DIR.resolve("configurations/functionCall/source/noWrap"), - RES_DIR.resolve("configurations/functionCall/source/wrap") + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "chopDown")), + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "noWrap")), + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "wrap")) )}, {"functionDeclaration", List.of( - RES_DIR.resolve("configurations/functionDeclaration/source/chopDown"), - RES_DIR.resolve("configurations/functionDeclaration/source/noWrap"), - RES_DIR.resolve("configurations/functionDeclaration/source/wrap") + RES_DIR.resolve( + Path.of("configurations", "options", "functionDeclaration", "source", "chopDown")), + RES_DIR.resolve( + Path.of("configurations", "options", "functionDeclaration", "source", "noWrap")), + RES_DIR.resolve(Path.of("configurations", "options", "functionDeclaration", "source", "wrap")) )}, {"ifStatement", List.of( - RES_DIR.resolve("configurations/ifStatement/source/ifelse") + RES_DIR.resolve(Path.of("configurations", "options", "ifStatement", "source", "ifelse")) )}, {"imports", List.of( - RES_DIR.resolve("configurations/imports/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "imports", "source", "project")) )}, {"indent", List.of( - RES_DIR.resolve("configurations/indent/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "indent", "source", "project")) )}, {"query", List.of( - RES_DIR.resolve("configurations/query/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "query", "source", "project")) )}, {"spacing", List.of( - RES_DIR.resolve("configurations/spacing/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "spacing", "source", "project")) )}, {"wrapping", List.of( - RES_DIR.resolve("configurations/wrapping/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "wrapping", "source", "project")) )} }; } @@ -339,4 +341,50 @@ public void formatCLISingleFileInProjectTest() { } } } + + @Test(description = "Test formatting of a module in a ballerina project with configurations") + public void formatCLIOnBallerinaProjectWithModulesWithConfigurations() { + List argList = new ArrayList<>(); + String module = "core"; + Path sourceDir = RES_DIR.resolve(Path.of("configurations", "module", "source")); + Path projectDir = sourceDir.resolve(Path.of("project")); + Path assertDir = Paths.get(sourceDir.toString().replace("/source", "/assert")); + Path moduleRelativePath = Path.of("modules", module, "core.bal"); + try { + FormatUtil.execute(argList, false, module, null, false, projectDir); + + Assert.assertEquals(Files.readString(projectDir.resolve("main.bal")), + Files.readString(assertDir.resolve("main.bal"))); + Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), + Files.readString(assertDir.resolve(moduleRelativePath))); + FileUtils.copyDirectory(sourceDir.resolve(Path.of("projectTemp")).toFile(), projectDir.toFile()); + } catch (IOException e) { + String exception = e.getMessage(); + Assert.assertTrue(exception.contains("error: "), "actual exception didn't match the expected."); + } + } + + @Test(description = "Test formatting of a module with specified ballerina project with configurations") + public void formatCLIOnBallernaProjectWithModulesWithConfigurations() { + List argList = new ArrayList<>(); + argList.add("project"); + String module = "mod"; + Path sourceDir = RES_DIR.resolve(Path.of("configurations", "projectWithModule", "source")); + Path projectDir = sourceDir.resolve(Path.of("project")); + Path assertDir = Paths.get(sourceDir.toString().replace("/source", "/assert")); + Path moduleRelativePath = Path.of("modules", module, "mod.bal"); + try { + FormatUtil.execute(argList, false, module, null, false, sourceDir); + + Assert.assertEquals(Files.readString(projectDir.resolve("main.bal")), + Files.readString(assertDir.resolve("main.bal"))); + Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), + Files.readString(assertDir.resolve(moduleRelativePath))); + FileUtils.copyDirectory(sourceDir.resolve(Path.of("projectTemp")).toFile(), projectDir.toFile()); + } catch (IOException e) { + String exception = e.getMessage(); + Assert.assertTrue(exception.contains("error: "), "actual exception didn't match the expected."); + } + } + } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml deleted file mode 100644 index a11d3d8fd440..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/brace/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal deleted file mode 100644 index ba25691b3c98..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/wrap/main.bal +++ /dev/null @@ -1,22 +0,0 @@ -import ballerina/io; - -function sendEmail(string sender, string recipient, string subject, - string message) returns boolean { - return true; -} - -public function main() { - boolean isEmailSent = sendEmail( - "sender@example.com", "recipient@example.com", - "This is a test email from Ballerina.", "Hello from Ballerina" - ); - if (isEmailSent) { - io:println( - "Email sent successfully!" - ); - } else { - io:println( - "Email sending failed." - ); - } -} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml deleted file mode 100644 index 8e54d8ed91c5..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionCall/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml deleted file mode 100644 index 2d40e31f1346..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionCall/source/noWrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml deleted file mode 100644 index 4d851c42c785..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionCall/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml deleted file mode 100644 index 95eb41f51983..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionDeclaration/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml deleted file mode 100644 index 94de643f225c..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/functionDeclaration/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml deleted file mode 100644 index c56508296bfb..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/ifStatement/source/ifelse" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml deleted file mode 100644 index 3be67308dc2b..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/imports/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/main.bal new file mode 100644 index 000000000000..dea76d4e518a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/main.bal @@ -0,0 +1,7 @@ +function foo(int a, int b) returns boolean { + if a + b > 10 { + return false; + } else { + return true; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/modules/core/core.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/modules/core/core.bal new file mode 100644 index 000000000000..4a3452672d36 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/assert/modules/core/core.bal @@ -0,0 +1,15 @@ +public const OFFSET = 10; +public const MULTIPLIER = 2; +public const TRUE = true; +public const FALSE = false; + +function bar(string|int x) +{ + string|int y = x; + if y is string { + y += "a"; + } + else { + y += 2; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml new file mode 100644 index 000000000000..524d91dc8b7a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml @@ -0,0 +1,14 @@ +[indent] +indentSize = 2 + +[wrapping] +maxLineLength = 120 + +[braces] +methodBraceStyle = "NewLine" + +[ifStatement] +elseOnNewLine = true + +[spacing] +alignConsecutiveDefinitions = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/main.bal new file mode 100644 index 000000000000..dea76d4e518a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/main.bal @@ -0,0 +1,7 @@ +function foo(int a, int b) returns boolean { + if a + b > 10 { + return false; + } else { + return true; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/modules/core/core.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/modules/core/core.bal new file mode 100644 index 000000000000..ec4bf776b459 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/modules/core/core.bal @@ -0,0 +1,13 @@ +public const OFFSET = 10; +public const MULTIPLIER = 2; +public const TRUE = true; +public const FALSE = false; + +function bar(string|int x) { + string|int y = x; + if y is string { + y += "a"; + } else { + y += 2; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/main.bal new file mode 100644 index 000000000000..dea76d4e518a --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/main.bal @@ -0,0 +1,7 @@ +function foo(int a, int b) returns boolean { + if a + b > 10 { + return false; + } else { + return true; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/modules/core/core.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/modules/core/core.bal new file mode 100644 index 000000000000..ec4bf776b459 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/projectTemp/modules/core/core.bal @@ -0,0 +1,13 @@ +public const OFFSET = 10; +public const MULTIPLIER = 2; +public const TRUE = true; +public const FALSE = false; + +function bar(string|int x) { + string|int y = x; + if y is string { + y += "a"; + } else { + y += 2; + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml new file mode 100644 index 000000000000..1c486e4beb55 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/brace/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/brace/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/assert/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/assert/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml new file mode 100644 index 000000000000..8f9e5a667008 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/functionCall/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDownTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/chopDownTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDownTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml new file mode 100644 index 000000000000..52384fd0c202 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/functionCall/source/noWrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/noWrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml new file mode 100644 index 000000000000..bd2aabcac133 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/functionCall/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionCall/source/wrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrapTemp/main.bal new file mode 100644 index 000000000000..95031e114bb8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrapTemp/main.bal @@ -0,0 +1,14 @@ +import ballerina/io; + +function sendEmail(string sender, string recipient, string subject, string message) returns boolean { + return true; +} + +public function main() { + boolean isEmailSent = sendEmail("sender@example.com", "recipient@example.com", "This is a test email from Ballerina.", "Hello from Ballerina"); + if (isEmailSent) { + io:println("Email sent successfully!"); + } else { + io:println("Email sending failed."); + } +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/assert/wrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml new file mode 100644 index 000000000000..9902ce62e027 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/functionDeclaration/source/chopDown" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDownTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDownTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/chopDownTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDownTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/noWrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml new file mode 100644 index 000000000000..6707bf60cba0 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/functionDeclaration/source/wrap" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/functionDeclaration/source/wrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/assert/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/assert/ifelse/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/assert/ifelse/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/assert/ifelse/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml new file mode 100644 index 000000000000..c22adfbec452 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/ifStatement/source/ifelse" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelse/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelseTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelseTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/ifStatement/source/ifelseTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelseTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml new file mode 100644 index 000000000000..c63d64b9f275 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/imports/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/imports/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/indent/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml new file mode 100644 index 000000000000..85a87577d7c6 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/query/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml new file mode 100644 index 000000000000..fada09cccda8 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "src/test/resources/configurations/options/spacing/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/assert/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/assert/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/assert/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/assert/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Format.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/project/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/projectTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/wrapping/source/projectTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/projectTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/main.bal new file mode 100644 index 000000000000..e2227aa2f026 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/main.bal @@ -0,0 +1,3 @@ +function foz(int a, string b, boolean c, int|string|boolean|float k) returns string { + return "hello"; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/modules/mod/mod.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/modules/mod/mod.bal new file mode 100644 index 000000000000..1c000f3f44b4 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/assert/modules/mod/mod.bal @@ -0,0 +1,15 @@ +class Calculator { + int a; + int b; + + function intAdd( + any x, any y) returns int { + return x + y; + } +} + +function bar( + int|string x, int k, string longName, string ultraLongName, int r, + string|int|boolean j) returns string|int { + return x; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Ballerina.toml new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml new file mode 100644 index 000000000000..f36c895a705f --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml @@ -0,0 +1,13 @@ +[indent] +continuationIndentSize = 4 + +[wrapping] +maxLineLength = 80 + + +[methodDeclaration] +alignMultilineParameters = true +newLineAfterLeftParen = true + +[spacing] +afterTypeCast = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/main.bal new file mode 100644 index 000000000000..e2227aa2f026 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/main.bal @@ -0,0 +1,3 @@ +function foz(int a, string b, boolean c, int|string|boolean|float k) returns string { + return "hello"; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/modules/mod/mod.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/modules/mod/mod.bal new file mode 100644 index 000000000000..a3bf4bace9b7 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/modules/mod/mod.bal @@ -0,0 +1,13 @@ +class Calculator { + int a; + int b; + + function intAdd(any x, any y) returns int { + return x + y; + } +} + +function bar(int|string x, int k, string longName, string ultraLongName, int r, +string|int|boolean j) returns string|int { + return x; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/main.bal new file mode 100644 index 000000000000..e2227aa2f026 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/main.bal @@ -0,0 +1,3 @@ +function foz(int a, string b, boolean c, int|string|boolean|float k) returns string { + return "hello"; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/modules/mod/mod.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/modules/mod/mod.bal new file mode 100644 index 000000000000..a3bf4bace9b7 --- /dev/null +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/projectTemp/modules/mod/mod.bal @@ -0,0 +1,13 @@ +class Calculator { + int a; + int b; + + function intAdd(any x, any y) returns int { + return x + y; + } +} + +function bar(int|string x, int k, string longName, string ultraLongName, int r, +string|int|boolean j) returns string|int { + return x; +} diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml deleted file mode 100644 index 26d2a66bc526..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/query/source/project/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/query/source/project" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml deleted file mode 100644 index cea39276de7f..000000000000 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/spacing/source/project/Ballerina.toml +++ /dev/null @@ -1,2 +0,0 @@ -[format] -configPath = "src/test/resources/configurations/spacing/source/project" diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java new file mode 100644 index 000000000000..da7698b8d75f --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.ballerinalang.formatter.core.configurations; + +import io.ballerina.projects.util.ProjectUtils; +import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Test resolution of formatting configuration file. + * + * @since 2201.9.0 + */ +public class FormatFileResolutionTest { + + private final Path resDir = Path.of("src", "test", "resources", "configurations", "resolution"); + private final String validRemoteUrl = + "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw" + + "/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml"; + private final Path validRemote = resDir.resolve("validRemote"); + private final Path withTarget = resDir.resolve("withTarget"); + private final Path invalidLocal = resDir.resolve("invalidLocal"); + private final Path invalidCached = resDir.resolve(Path.of("invalidCached")); + private final Path invalidCacheTarget = resDir.resolve("invalidCacheTarget"); + private final Path invalidCacheWrite = resDir.resolve("invalidCacheWrite"); + + // In the case of tests failing to run, check whether these temp files exists and delete them if so. + private File tempInvalidPermissionFile; + private File tempInvalidCachedPermissionFile; + private File tempInvalidTargetDir; + private File tempInvalidFormatDir; + + @BeforeClass + public void setup() { + try { + tempInvalidPermissionFile = createTempUnreadableFile(invalidLocal.resolve("Format.toml")); + tempInvalidCachedPermissionFile = + createTempUnreadableFile(invalidCached.resolve(Path.of("target", "format", "Format.toml"))); + tempInvalidTargetDir = createTempUnwritableDir(invalidCacheTarget.resolve("target")); + tempInvalidFormatDir = createTempUnwritableDir(invalidCacheWrite.resolve("target").resolve("format")); + + } catch (IOException e) { + throw new RuntimeException("Error while setting up the formatter resolution test."); + } + } + + @Test(description = "Test for local formatting configuration file") + public void resolutionOfLocalFormatFileTest() throws FormatterException { + Path validLocal = resDir.resolve("validLocal"); + FormatterUtils.getFormattingConfigurations(validLocal, validLocal.resolve("Format.toml").toString()); + } + + @Test(description = "Test for remote formatting configuration file") + public void resolutionOfRemoteFormatFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(validRemote, validRemoteUrl); + } + + @Test(description = "Test caching of configuration file with target directory present") + public void cacheWithTargetDirectoryPresent() throws FormatterException { + FormatterUtils.getFormattingConfigurations(withTarget, validRemoteUrl); + } + + @Test(description = "Test invalid local formatting configuration files", + expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to retrieve local formatting configuration file") + public void invalidLocalFormatFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("directory.toml").toString()); + FormatterUtils.getFormattingConfigurations(invalidLocal, tempInvalidPermissionFile.toString()); + } + + @Test(description = "Test invalid remote cached formatting configuration files", + expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to read cached formatting configuration file") + public void invalidRemoteCachedFormatFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(invalidCached, validRemoteUrl); + } + + @Test(description = "Test invalid remote formatting configuration file url", + expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to retrieve remote file. HTTP response code:.*") + public void invalidRemoteFormatFileURLTest() throws FormatterException { + Path invalidUrl = resDir.resolve("invalidUrl"); + FormatterUtils.getFormattingConfigurations(invalidUrl, + "https://gist.github.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/Format.toml"); + } + + @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to retrieve formatting configuration file") + public void getInvalidFormatFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("t.toml").toString()); + } + + @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to create format configuration cache directory") + public void failureToCreateFormatCacheFolderTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(invalidCacheTarget, validRemoteUrl); + } + + @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Failed to write format configuration cache file") + public void failureToWriteCacheFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(invalidCacheWrite, validRemoteUrl); + } + + private File createTempUnreadableFile(Path path) throws IOException { + Files.deleteIfExists(path); + File file = new File(path.toString()); + file.createNewFile(); + file.setReadable(false); + return file; + } + + private File createTempUnwritableDir(Path path) throws IOException { + Files.deleteIfExists(path); + File dir = new File(path.toString()); + dir.mkdir(); + dir.setWritable(false); + return dir; + } + + @AfterClass + public void tearDown() { + ProjectUtils.deleteDirectory(validRemote.resolve("target")); + ProjectUtils.deleteDirectory(withTarget.resolve("target").resolve("format")); + tempInvalidPermissionFile.delete(); + tempInvalidCachedPermissionFile.delete(); + tempInvalidTargetDir.delete(); + tempInvalidFormatDir.delete(); + } + +} diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java new file mode 100644 index 000000000000..0cac424f0860 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.ballerinalang.formatter.core.configurations; + +import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterUtils; +import org.testng.annotations.Test; + +import java.nio.file.Path; + +/** + * Test validation of formatting configuration file. + * + * @since 2201.9.0 + */ +public class FormatFileValidatorTest { + + private final Path resDir = Path.of("src", "test", "resources", "configurations", "validator"); + + @Test(description = "Test validator on valid formatting configuration file") + public void testValidatorOnValidFile() throws FormatterException { + Path valid = resDir.resolve("valid"); + FormatterUtils.getFormattingConfigurations(valid, valid.resolve("Format.toml").toString()); + } + + @Test(description = "Test validtor on invalid formatting configuration files", + expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid Format.toml file") + public void testValidatorOnInvalidFile() throws FormatterException { + Path invalid = resDir.resolve("invalid"); + FormatterUtils.getFormattingConfigurations(invalid, invalid.resolve("Format.toml").toString()); + } +} diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validLocal/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validLocal/Format.toml new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml new file mode 100644 index 000000000000..3d403de184cb --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml @@ -0,0 +1,25 @@ +[indent] +indentSize = "4" +continuationIndentSize = true + +[wrapping] +maxLineLength = 120 +simpleBlocksInOneLine = "true" +simpleMethodsInOneLine = "true" + +[braces] +classBraceStyle = "NEWLINE" +methodBraceStyle = "NEWLINE" + +[methodDeclaration] +parametersWrap = "CHOPDOWN" +paramterExtend = true + +[methodCall] +parametersWrap = "WRAP" + +[elseStatement] +elseOnNewLine = false + +[Spacing] +afterTypeCast = true diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml new file mode 100644 index 000000000000..dc4e253c5d1f --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml @@ -0,0 +1,31 @@ +[indent] +indentSize = 4 +continuationIndentSize = 8 + +[wrapping] +maxLineLength = 120 +simpleBlocksInOneLine = true +simpleMethodsInOneLine = true + +[braces] +classBraceStyle = "NewLine" +methodBraceStyle = "NewLine" + +[methodDeclaration] +parametersWrap = "ChopDown" +alignMultilineParameters = true +newLineAfterLeftParen = false +rightParenOnNewLine = false + +[methodCall] +parametersWrap = "Wrap" +alignMultilineParameters = false +newLineAfterLeftParen = false +rightParenOnNewLine = false + +[ifStatement] +elseOnNewLine = false + +[spacing] +afterTypeCast = true +aroundRecordBraces = true From 47395a38627c1147f48de949d988264823906a19 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Sun, 10 Mar 2024 19:46:07 +0530 Subject: [PATCH 15/22] Add options negative tests --- .../formatter/cli/FormatCmdTest.java | 28 ++- .../core/options/BraceFormattingOptions.java | 4 +- .../formatter/core/options/BraceStyle.java | 3 +- .../formatter/core/options/FormatSection.java | 3 +- .../core/options/FormattingOptions.java | 5 +- .../FunctionCallFormattingOptions.java | 5 +- .../FunctionDeclFormattingOptions.java | 6 +- .../options/IfStatementFormattingOptions.java | 6 +- .../core/options/ImportFormattingOptions.java | 8 +- .../core/options/IndentFormattingOptions.java | 8 +- .../core/options/QueryFormattingOptions.java | 6 +- .../options/SpacingFormattingOptions.java | 8 +- .../options/WrappingFormattingOptions.java | 7 +- .../core/options/WrappingMethod.java | 3 +- .../FormatOptionNegativeTest.java | 162 ++++++++++++++++++ 15 files changed, 206 insertions(+), 56 deletions(-) create mode 100644 misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index 0a16271e30f6..a5120e86fdbd 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -106,37 +106,35 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< private Object[][] provideConfigurationProjects() { return new Object[][]{ {"brace", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "brace", "source", "project")) + RES_DIR.resolve("configurations/options/brace/source/project") )}, {"functionCall", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "chopDown")), - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "noWrap")), - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "wrap")) + RES_DIR.resolve("configurations/options/functionCall/source/chopDown"), + RES_DIR.resolve("configurations/options/functionCall/source/noWrap"), + RES_DIR.resolve("configurations/options/functionCall/source/wrap") )}, {"functionDeclaration", List.of( - RES_DIR.resolve( - Path.of("configurations", "options", "functionDeclaration", "source", "chopDown")), - RES_DIR.resolve( - Path.of("configurations", "options", "functionDeclaration", "source", "noWrap")), - RES_DIR.resolve(Path.of("configurations", "options", "functionDeclaration", "source", "wrap")) + RES_DIR.resolve("configurations/options/functionDeclaration/source/chopDown"), + RES_DIR.resolve("configurations/options/functionDeclaration/source/noWrap"), + RES_DIR.resolve("configurations/options/functionDeclaration/source/wrap") )}, {"ifStatement", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "ifStatement", "source", "ifelse")) + RES_DIR.resolve("configurations/options/ifStatement/source/ifelse") )}, {"imports", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "imports", "source", "project")) + RES_DIR.resolve("configurations/options/imports/source/project") )}, {"indent", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "indent", "source", "project")) + RES_DIR.resolve("configurations/options/indent/source/project") )}, {"query", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "query", "source", "project")) + RES_DIR.resolve("configurations/options/query/source/project") )}, {"spacing", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "spacing", "source", "project")) + RES_DIR.resolve("configurations/options/spacing/source/project") )}, {"wrapping", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "wrapping", "source", "project")) + RES_DIR.resolve("configurations/options/wrapping/source/project") )} }; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 238dcc6399f4..9c578604cb22 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -78,9 +78,7 @@ public BraceFormattingOptions build(Map configs) throws Formatte switch (bracesKey) { case CLASS_BRACE_STYLE -> setClassBraceStyle(style); case METHOD_BRACE_STYLE -> setMethodBraceStyle(style); - default -> { - assert false : "Include the brace formatting option " + bracesKey + " in the validator"; - } + default -> throw new FormatterException("Invalid Brace Option: " + bracesKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index b69fc3c309e4..dc379f2ded0e 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -30,8 +30,7 @@ public static BraceStyle fromString(String value) throws FormatterException { try { return BraceStyle.valueOf(value); } catch (IllegalArgumentException e) { - assert false : "Include the brace style " + value + " in the validator"; - return EndOfLine; + throw new FormatterException("Invalid Brace style: " + value); } } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java index 322f6d8fa303..295113e84ab4 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -49,7 +49,6 @@ public static FormatSection fromString(String value) throws FormatterException { return section; } } - assert false : "Include the format section " + value + " in the validator"; - return null; + throw new FormatterException("Invalid format section: " + value); } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 19fb8b308edb..dd7b2095acbb 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -203,10 +203,7 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build(configs); case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build(configs); - default -> { - assert false : - "Include the formatting section " + section + " in the validator"; - } + default -> throw new FormatterException("Invalid formatting option section : " + section); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index 8cec5554ba89..4846e37cd705 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -117,10 +117,7 @@ public FunctionCallFormattingOptions build(Map configs) throws F case ALIGN_MULTILINE_PARAMETERS -> setAlignMultilineParameters((Boolean) funcCallEntry.getValue()); case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) funcCallEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) funcCallEntry.getValue()); - default -> { - assert false : - "Include the function call formatting option " + funcCallKey + " in the validator"; - } + default -> throw new FormatterException("Invalid function call formatting option: " + funcCallKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index 71cacb74c097..7226e666d773 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -113,10 +113,8 @@ public FunctionDeclFormattingOptions build(Map configs) throws F case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); - default -> { - assert false : "Include the function declaration formatting option " + methodDeclarationKey + - " in the validator"; - } + default -> throw new FormatterException( + "Invalid function declaration formatting option: " + methodDeclarationKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index 8d5f1dba6ee6..dfb3a80bf89f 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; + import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; @@ -54,13 +56,13 @@ public IfStatementFormattingOptions build() { return new IfStatementFormattingOptions(elseOnNewLine); } - public IfStatementFormattingOptions build(Map configs) { + public IfStatementFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry ifStatementEntry : configs.entrySet()) { String ifStatementKey = ifStatementEntry.getKey(); if (ifStatementKey.equals(ELSE_ON_NEW_LINE)) { setElseOnNewLine((Boolean) ifStatementEntry.getValue()); } else { - assert false : "Include the if statement formatting option " + ifStatementKey + " in the validator"; + throw new FormatterException("Invalid if statement formatting option: " + ifStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index dea010b5e3ed..43fb81a03c36 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; + import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; @@ -84,15 +86,13 @@ public ImportFormattingOptions build() { return new ImportFormattingOptions(groupImports, sortImports, removeUnusedImports); } - public ImportFormattingOptions build(Map configs) { + public ImportFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry importEntry : configs.entrySet()) { String importKey = importEntry.getKey(); switch (importKey) { case SORT_IMPORTS -> setSortImports((Boolean) importEntry.getValue()); case GROUP_IMPORTS -> setGroupImports((Boolean) importEntry.getValue()); - default -> { - assert false : "Include the import formatting option " + importKey + " in the validator"; - } + default -> throw new FormatterException("Invalid import formatting option: " + importKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index 7bab827cbc15..ddf619868f4a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; + import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultInt; @@ -77,16 +79,14 @@ public IndentFormattingOptions build() { return new IndentFormattingOptions(indentSize, continuationIndentSize, wsCharacter); } - public IndentFormattingOptions build(Map configs) { + public IndentFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry indentEntry : configs.entrySet()) { String indentKey = indentEntry.getKey(); switch (indentKey) { case INDENT_SIZE -> setIndentSize(((Number) indentEntry.getValue()).intValue()); case CONTINUATION_INDENT_SIZE -> setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); - default -> { - assert false : "Include the import formatting option " + indentKey + " in the validator"; - } + default -> throw new FormatterException("Invalid indent formatting option: " + indentKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index 460dcd2ac7a5..58c570f72737 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; + import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; @@ -54,13 +56,13 @@ public QueryFormattingOptions build() { return new QueryFormattingOptions(alignMultiLineQueries); } - public QueryFormattingOptions build(Map configs) { + public QueryFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry queryStatementEntry : configs.entrySet()) { String queryStatementKey = queryStatementEntry.getKey(); if (queryStatementKey.equals(ALIGN_MULTILINE_QUERIES)) { setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); } else { - assert false : "Include the query formatting option " + queryStatementKey + " in the validator"; + throw new FormatterException("Invalid query formatting option: " + queryStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 1166c8f1aa5a..058bbd44ba2b 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -15,6 +15,8 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; + import java.util.Map; import static org.ballerinalang.formatter.core.FormatterUtils.getDefaultBoolean; @@ -82,7 +84,7 @@ public SpacingFormattingOptions build() { return new SpacingFormattingOptions(afterTypeCast, aroundRecordBraces, alignConsecutiveDefinitions); } - public SpacingFormattingOptions build(Map configs) { + public SpacingFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry spacingEntry : configs.entrySet()) { String spacingKey = spacingEntry.getKey(); switch (spacingKey) { @@ -90,9 +92,7 @@ public SpacingFormattingOptions build(Map configs) { case AROUND_RECORD_BRACES -> setAroundRecordBraces((Boolean) spacingEntry.getValue()); case ALIGN_CONSECUTIVE_DEFINITIONS -> setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); - default -> { - assert false : "Include the spacing formatting option " + spacingKey + " in the validator"; - } + default -> throw new FormatterException("Invalid spacing formatting option: " + spacingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index 828d603b55a7..3aafdf814474 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -15,6 +15,7 @@ */ package org.ballerinalang.formatter.core.options; +import org.ballerinalang.formatter.core.FormatterException; import org.ballerinalang.formatter.core.FormatterUtils; import java.util.Map; @@ -97,7 +98,7 @@ public WrappingFormattingOptions build() { simpleMethodsInOneLine); } - public WrappingFormattingOptions build(Map configs) { + public WrappingFormattingOptions build(Map configs) throws FormatterException { for (Map.Entry wrappingEntry : configs.entrySet()) { String wrappingKey = wrappingEntry.getKey(); switch (wrappingKey) { @@ -107,9 +108,7 @@ public WrappingFormattingOptions build(Map configs) { } case SIMPLE_BLOCKS_IN_ONE_LINE -> setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); case SIMPLE_METHODS_IN_ONE_LINE -> setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); - default -> { - assert false : "Include the wrapping formatting option " + wrappingKey + " in the validator"; - } + default -> throw new FormatterException("Invalid wrapping formatting option: " + wrappingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index a70bb160d6ba..f139b3c83102 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -31,8 +31,7 @@ public static WrappingMethod fromString(String value) throws FormatterException try { return WrappingMethod.valueOf(value); } catch (IllegalArgumentException e) { - assert false : "Include the wrapping method " + value + " in the validator"; - return NoWrap; + throw new FormatterException("Invalid wrapping method: " + value); } } diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java new file mode 100644 index 000000000000..47a4697bbd7c --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.ballerinalang.formatter.core.configurations; + +import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.options.BraceFormattingOptions; +import org.ballerinalang.formatter.core.options.BraceStyle; +import org.ballerinalang.formatter.core.options.FormatSection; +import org.ballerinalang.formatter.core.options.FunctionCallFormattingOptions; +import org.ballerinalang.formatter.core.options.FunctionDeclFormattingOptions; +import org.ballerinalang.formatter.core.options.IfStatementFormattingOptions; +import org.ballerinalang.formatter.core.options.ImportFormattingOptions; +import org.ballerinalang.formatter.core.options.IndentFormattingOptions; +import org.ballerinalang.formatter.core.options.QueryFormattingOptions; +import org.ballerinalang.formatter.core.options.SpacingFormattingOptions; +import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; +import org.ballerinalang.formatter.core.options.WrappingMethod; +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.Map; + +/** + * Test formatting options invalid configurations. + * + * @since 2201.9.0 + */ +public class FormatOptionNegativeTest { + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid Brace Option: serviceBraceStyle") + public void testInvalidBracesOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("classBraceStyle", "NewLine"); + put("methodBraceStyle", "EndOfLine"); + put("serviceBraceStyle", "NewLine"); + }}; + BraceFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid function call formatting option: parametersInLine") + public void testInvalidFunctionCallOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("parametersWrap", "Wrap"); + put("newLineAfterLeftParen", true); + put("alignMultilineParameters", false); + put("rightParenOnNewLine", true); + put("parametersInLine", true); + }}; + FunctionCallFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid function declaration formatting option: parametersInLine") + public void testInvalidFunctionDeclarationOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("parametersWrap", "Wrap"); + put("newLineAfterLeftParen", true); + put("alignMultilineParameters", false); + put("rightParenOnNewLine", true); + put("parametersInLine", true); + }}; + FunctionDeclFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid if statement formatting option: conditionOnSameLine") + public void testInvalidIfStatementOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("elseOnNewLine", true); + put("conditionOnSameLine", true); + }}; + IfStatementFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid import formatting option: randomizeImports") + public void testInvalidImportOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("groupImports", true); + put("sortImports", true); + put("randomizeImports", true); + }}; + ImportFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid indent formatting option: indentFunctions") + public void testInvalidIndentOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("indentSize", -2); + put("continuationIndentSize", 4); + put("indentFunctions", false); + }}; + IndentFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid query formatting option: queryOnSameLine") + public void testInvalidQueryOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("alignMultiLineQueries", true); + put("queryOnSameLine", false); + }}; + QueryFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid spacing formatting option: spaceAroundTuple") + public void testInvalidSpacingOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("spaceAfterTypeCast", true); + put("spaceAroundRecordBraces", true); + put("spaceAroundTuple", true); + }}; + SpacingFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Invalid wrapping formatting option: wrapSimpleObjects") + public void testInvalidWrappingOptions() throws FormatterException { + Map configs = new HashMap<>() {{ + put("maxLineLength", 120); + put("simpleBlocksInOneLine", true); + put("simpleMethodsInOneLine", true); + put("wrapSimpleObjects", true); + }}; + WrappingFormattingOptions.builder().build(configs); + } + + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid Brace style:.*") + public void testInvalidBraceStyle() throws FormatterException { + BraceStyle.fromString("NEWLINE"); + } + + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid wrapping method:.*") + public void testInvalidWrappingMethod() throws FormatterException { + WrappingMethod.fromString("WRAP"); + } + + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid format section:.*") + public void testInvalidFormatSection() throws FormatterException { + FormatSection.fromString("service"); + } +} From 6f4b38a4aa0fed0eea1a3231d575ab157c5af7ad Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 11 Mar 2024 06:25:46 +0530 Subject: [PATCH 16/22] Update tests --- .../formatter/cli/FormatCmdTest.java | 49 +++++++-------- .../core/options/FormattingOptions.java | 1 - .../FormatFileResolutionTest.java | 59 +++---------------- .../configurations/resolution/.gitignore | 1 + .../cached/target/format/Format.toml | 5 ++ .../resolution/invalidCacheCreate/.gitkeep | 0 .../invalidCacheCreate/target/.gitkeep | 0 .../resolution/invalidCacheTarget/.gitkeep | 0 .../resolution/invalidCacheTarget/target | 0 .../resolution/invalidCacheWrite/.gitkeep | 0 .../invalidCacheWrite/target/.gitkeep | 0 .../invalidCacheWrite/target/format | 0 .../resolution/invalidCached/.gitkeep | 0 .../resolution/invalidCached/target/.gitkeep | 0 .../invalidCached/target/format/.gitkeep | 0 .../target/format/Format.toml/.gitkeep | 0 .../resolution/invalidLocal/.gitkeep | 0 .../invalidLocal/directory.toml/.gitkeep | 0 .../resolution/invalidUrl/.gitkeep | 0 .../resolution/validRemote/.gitkeep | 0 .../resolution/withTarget/.gitkeep | 0 .../resolution/withTarget/target/.gitkeep | 0 22 files changed, 40 insertions(+), 75 deletions(-) create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/.gitignore create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/cached/target/format/Format.toml create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/target/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/target create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/format create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/Format.toml/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/directory.toml/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidUrl/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validRemote/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/.gitkeep create mode 100644 misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/target/.gitkeep diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index a5120e86fdbd..5cea249a7a3f 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -106,35 +106,38 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< private Object[][] provideConfigurationProjects() { return new Object[][]{ {"brace", List.of( - RES_DIR.resolve("configurations/options/brace/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "brace", "source", "project")) )}, {"functionCall", List.of( - RES_DIR.resolve("configurations/options/functionCall/source/chopDown"), - RES_DIR.resolve("configurations/options/functionCall/source/noWrap"), - RES_DIR.resolve("configurations/options/functionCall/source/wrap") + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "chopDown")), + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "noWrap")), + RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "wrap")) )}, {"functionDeclaration", List.of( - RES_DIR.resolve("configurations/options/functionDeclaration/source/chopDown"), - RES_DIR.resolve("configurations/options/functionDeclaration/source/noWrap"), - RES_DIR.resolve("configurations/options/functionDeclaration/source/wrap") + RES_DIR.resolve( + Path.of("configurations", "options", "functionDeclaration", "source", "chopDown")), + RES_DIR.resolve( + Path.of("configurations", "options", "functionDeclaration", "source", "noWrap")), + RES_DIR.resolve(Path.of("configurations", "options", "functionDeclaration", "source", "wrap")) )}, {"ifStatement", List.of( - RES_DIR.resolve("configurations/options/ifStatement/source/ifelse") + RES_DIR.resolve(Path.of("configurations", "options", "ifStatement", "source", "ifelse")) )}, {"imports", List.of( - RES_DIR.resolve("configurations/options/imports/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "imports", "source", "project")) )}, {"indent", List.of( - RES_DIR.resolve("configurations/options/indent/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "indent", "source", "project")) )}, {"query", List.of( - RES_DIR.resolve("configurations/options/query/source/project") - )}, + RES_DIR.resolve(Path.of("configurations", "options", "query", "source", "project")) + )} + , {"spacing", List.of( - RES_DIR.resolve("configurations/options/spacing/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "spacing", "source", "project")) )}, {"wrapping", List.of( - RES_DIR.resolve("configurations/options/wrapping/source/project") + RES_DIR.resolve(Path.of("configurations", "options", "wrapping", "source", "project")) )} }; } @@ -344,9 +347,9 @@ public void formatCLISingleFileInProjectTest() { public void formatCLIOnBallerinaProjectWithModulesWithConfigurations() { List argList = new ArrayList<>(); String module = "core"; - Path sourceDir = RES_DIR.resolve(Path.of("configurations", "module", "source")); - Path projectDir = sourceDir.resolve(Path.of("project")); - Path assertDir = Paths.get(sourceDir.toString().replace("/source", "/assert")); + Path sourceDir = RES_DIR.resolve(Path.of("configurations", "module")); + Path projectDir = sourceDir.resolve(Path.of("source", "project")); + Path assertDir = sourceDir.resolve("assert"); Path moduleRelativePath = Path.of("modules", module, "core.bal"); try { FormatUtil.execute(argList, false, module, null, false, projectDir); @@ -355,7 +358,7 @@ public void formatCLIOnBallerinaProjectWithModulesWithConfigurations() { Files.readString(assertDir.resolve("main.bal"))); Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), Files.readString(assertDir.resolve(moduleRelativePath))); - FileUtils.copyDirectory(sourceDir.resolve(Path.of("projectTemp")).toFile(), projectDir.toFile()); + FileUtils.copyDirectory(sourceDir.resolve(Path.of("source", "projectTemp")).toFile(), projectDir.toFile()); } catch (IOException e) { String exception = e.getMessage(); Assert.assertTrue(exception.contains("error: "), "actual exception didn't match the expected."); @@ -367,18 +370,18 @@ public void formatCLIOnBallernaProjectWithModulesWithConfigurations() { List argList = new ArrayList<>(); argList.add("project"); String module = "mod"; - Path sourceDir = RES_DIR.resolve(Path.of("configurations", "projectWithModule", "source")); - Path projectDir = sourceDir.resolve(Path.of("project")); - Path assertDir = Paths.get(sourceDir.toString().replace("/source", "/assert")); + Path sourceDir = RES_DIR.resolve(Path.of("configurations", "projectWithModule")); + Path projectDir = sourceDir.resolve(Path.of("source", "project")); + Path assertDir = sourceDir.resolve("assert"); Path moduleRelativePath = Path.of("modules", module, "mod.bal"); try { - FormatUtil.execute(argList, false, module, null, false, sourceDir); + FormatUtil.execute(argList, false, module, null, false, sourceDir.resolve("source")); Assert.assertEquals(Files.readString(projectDir.resolve("main.bal")), Files.readString(assertDir.resolve("main.bal"))); Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), Files.readString(assertDir.resolve(moduleRelativePath))); - FileUtils.copyDirectory(sourceDir.resolve(Path.of("projectTemp")).toFile(), projectDir.toFile()); + FileUtils.copyDirectory(sourceDir.resolve(Path.of("source", "projectTemp")).toFile(), projectDir.toFile()); } catch (IOException e) { String exception = e.getMessage(); Assert.assertTrue(exception.contains("error: "), "actual exception didn't match the expected."); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index dd7b2095acbb..18034ddabe91 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -203,7 +203,6 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter case QUERY -> queryFormattingOptions = QueryFormattingOptions.builder().build(configs); case SPACING -> spacingFormattingOptions = SpacingFormattingOptions.builder().build(configs); case IMPORT -> importFormattingOptions = ImportFormattingOptions.builder().build(configs); - default -> throw new FormatterException("Invalid formatting option section : " + section); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java index da7698b8d75f..15d6beb76198 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java @@ -22,12 +22,8 @@ import org.ballerinalang.formatter.core.FormatterException; import org.ballerinalang.formatter.core.FormatterUtils; import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; /** @@ -44,29 +40,6 @@ public class FormatFileResolutionTest { private final Path validRemote = resDir.resolve("validRemote"); private final Path withTarget = resDir.resolve("withTarget"); private final Path invalidLocal = resDir.resolve("invalidLocal"); - private final Path invalidCached = resDir.resolve(Path.of("invalidCached")); - private final Path invalidCacheTarget = resDir.resolve("invalidCacheTarget"); - private final Path invalidCacheWrite = resDir.resolve("invalidCacheWrite"); - - // In the case of tests failing to run, check whether these temp files exists and delete them if so. - private File tempInvalidPermissionFile; - private File tempInvalidCachedPermissionFile; - private File tempInvalidTargetDir; - private File tempInvalidFormatDir; - - @BeforeClass - public void setup() { - try { - tempInvalidPermissionFile = createTempUnreadableFile(invalidLocal.resolve("Format.toml")); - tempInvalidCachedPermissionFile = - createTempUnreadableFile(invalidCached.resolve(Path.of("target", "format", "Format.toml"))); - tempInvalidTargetDir = createTempUnwritableDir(invalidCacheTarget.resolve("target")); - tempInvalidFormatDir = createTempUnwritableDir(invalidCacheWrite.resolve("target").resolve("format")); - - } catch (IOException e) { - throw new RuntimeException("Error while setting up the formatter resolution test."); - } - } @Test(description = "Test for local formatting configuration file") public void resolutionOfLocalFormatFileTest() throws FormatterException { @@ -79,6 +52,11 @@ public void resolutionOfRemoteFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(validRemote, validRemoteUrl); } + @Test(description = "Test for cached remote formatting configuration file") + public void resolutionOfCachedRemoteFormatFileTest() throws FormatterException { + FormatterUtils.getFormattingConfigurations(resDir.resolve("cached"), validRemoteUrl); + } + @Test(description = "Test caching of configuration file with target directory present") public void cacheWithTargetDirectoryPresent() throws FormatterException { FormatterUtils.getFormattingConfigurations(withTarget, validRemoteUrl); @@ -89,14 +67,13 @@ public void cacheWithTargetDirectoryPresent() throws FormatterException { expectedExceptionsMessageRegExp = "Failed to retrieve local formatting configuration file") public void invalidLocalFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("directory.toml").toString()); - FormatterUtils.getFormattingConfigurations(invalidLocal, tempInvalidPermissionFile.toString()); } @Test(description = "Test invalid remote cached formatting configuration files", expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Failed to read cached formatting configuration file") public void invalidRemoteCachedFormatFileTest() throws FormatterException { - FormatterUtils.getFormattingConfigurations(invalidCached, validRemoteUrl); + FormatterUtils.getFormattingConfigurations(resDir.resolve(Path.of("invalidCached")), validRemoteUrl); } @Test(description = "Test invalid remote formatting configuration file url", @@ -117,39 +94,19 @@ public void getInvalidFormatFileTest() throws FormatterException { @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Failed to create format configuration cache directory") public void failureToCreateFormatCacheFolderTest() throws FormatterException { - FormatterUtils.getFormattingConfigurations(invalidCacheTarget, validRemoteUrl); + FormatterUtils.getFormattingConfigurations(resDir.resolve("invalidCacheTarget"), validRemoteUrl); } @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Failed to write format configuration cache file") public void failureToWriteCacheFileTest() throws FormatterException { - FormatterUtils.getFormattingConfigurations(invalidCacheWrite, validRemoteUrl); - } - - private File createTempUnreadableFile(Path path) throws IOException { - Files.deleteIfExists(path); - File file = new File(path.toString()); - file.createNewFile(); - file.setReadable(false); - return file; - } - - private File createTempUnwritableDir(Path path) throws IOException { - Files.deleteIfExists(path); - File dir = new File(path.toString()); - dir.mkdir(); - dir.setWritable(false); - return dir; + FormatterUtils.getFormattingConfigurations(resDir.resolve("invalidCacheWrite"), validRemoteUrl); } @AfterClass public void tearDown() { ProjectUtils.deleteDirectory(validRemote.resolve("target")); ProjectUtils.deleteDirectory(withTarget.resolve("target").resolve("format")); - tempInvalidPermissionFile.delete(); - tempInvalidCachedPermissionFile.delete(); - tempInvalidTargetDir.delete(); - tempInvalidFormatDir.delete(); } } diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/.gitignore b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/.gitignore new file mode 100644 index 000000000000..0d70cc697f53 --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/.gitignore @@ -0,0 +1 @@ +!target diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/cached/target/format/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/cached/target/format/Format.toml new file mode 100644 index 000000000000..fb384424874e --- /dev/null +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/cached/target/format/Format.toml @@ -0,0 +1,5 @@ +[indent] +continuationIndentSize=4 + +[spacing] +afterTypeCast=true diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/target/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheCreate/target/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/target b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheTarget/target new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/format b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCacheWrite/target/format new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/Format.toml/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidCached/target/format/Format.toml/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/directory.toml/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidLocal/directory.toml/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidUrl/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/invalidUrl/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validRemote/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/validRemote/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/target/.gitkeep b/misc/formatter/modules/formatter-core/src/test/resources/configurations/resolution/withTarget/target/.gitkeep new file mode 100644 index 000000000000..e69de29bb2d1 From 8e291aa517a33f6fa1994cde8e6e774dda4cd5ad Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 18 Mar 2024 11:15:44 +0530 Subject: [PATCH 17/22] Update relative path resolution --- .../options/brace/source/project/Ballerina.toml | 2 +- .../functionCall/source/chopDown/Ballerina.toml | 2 +- .../functionCall/source/noWrap/Ballerina.toml | 2 +- .../functionCall/source/wrap/Ballerina.toml | 2 +- .../source/chopDown/Ballerina.toml | 2 +- .../source/wrap/Ballerina.toml | 2 +- .../ifStatement/source/ifelse/Ballerina.toml | 2 +- .../imports/source/project/Ballerina.toml | 2 +- .../options/query/source/project/Ballerina.toml | 2 +- .../spacing/source/project/Ballerina.toml | 2 +- .../wrapping/source/project/Ballerina.toml | 2 ++ .../source/project/{ => dir}/Format.toml | 0 .../formatter/core/FormatterUtils.java | 16 +++++++++------- .../configurations/local/source/Ballerina.toml | 2 +- 14 files changed, 22 insertions(+), 18 deletions(-) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/{ => dir}/Format.toml (100%) diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml index 1c486e4beb55..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/brace/source/project" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml index 8f9e5a667008..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/functionCall/source/chopDown" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml index 52384fd0c202..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/functionCall/source/noWrap" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml index bd2aabcac133..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/functionCall/source/wrap" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml index 9902ce62e027..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/functionDeclaration/source/chopDown" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml index 6707bf60cba0..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/functionDeclaration/source/wrap" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml index c22adfbec452..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/ifStatement/source/ifelse/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/ifStatement/source/ifelse" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml index c63d64b9f275..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/imports/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/imports/source/project" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml index 85a87577d7c6..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/query/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/query/source/project" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml index fada09cccda8..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/spacing/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/options/spacing/source/project" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml index e69de29bb2d1..4da7c944567f 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml @@ -0,0 +1,2 @@ +[format] +configPath = "dir/Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 42a5acf9d7b1..907924065eac 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -107,23 +107,25 @@ public static String getFormattingFilePath(Object formatSection, String root) { return Files.exists(defaultFile) ? defaultFile.toString() : null; } - public static Map getFormattingConfigurations(Path root, String path) throws FormatterException { + public static Map getFormattingConfigurations(Path root, String sPath) throws FormatterException { String content; - if (isLocalFile(path)) { + Path path = Path.of(sPath); + Path absPath = path.isAbsolute() || !root.isAbsolute() ? path : root.resolve(sPath); + if (isLocalFile(absPath)) { try { - content = Files.readString(Path.of(path), StandardCharsets.UTF_8); + content = Files.readString(absPath, StandardCharsets.UTF_8); } catch (IOException e) { throw new FormatterException("Failed to retrieve local formatting configuration file"); } } else { - content = readRemoteFormatFile(root, path); + content = readRemoteFormatFile(root, sPath); } - return parseConfigurationToml(TomlDocument.from(path, content)); + return parseConfigurationToml(TomlDocument.from(sPath, content)); } - private static boolean isLocalFile(String path) { - return new File(path).exists(); + private static boolean isLocalFile(Path path) { + return new File(path.toString()).exists(); } static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml index e65074998a5f..b53603fd5286 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/local/source/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/configurations/local/source" +configPath = "Format.toml" From 3ddf7f0b9f9aca607c4eab1b7d9649ac23e629a9 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Mon, 18 Mar 2024 15:29:33 +0530 Subject: [PATCH 18/22] Refactor code to add functions --- .../BallerinaTextDocumentService.java | 12 +-- .../formatting/project/Ballerina.toml | 2 +- .../formatter/cli/FormatUtil.java | 8 +- .../formatter/core/FormatterUtils.java | 102 +++++++++++++++--- .../core/FormattingTreeModifier.java | 17 ++- .../core/options/ForceFormattingOptions.java | 22 ++-- .../core/options/FormattingOptions.java | 31 +++--- 7 files changed, 133 insertions(+), 61 deletions(-) diff --git a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java index cfb13b2ceb20..7b6fcc24e9a5 100755 --- a/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java +++ b/language-server/modules/langserver-core/src/main/java/org/ballerinalang/langserver/BallerinaTextDocumentService.java @@ -18,12 +18,12 @@ import io.ballerina.compiler.syntax.tree.SyntaxTree; import io.ballerina.projects.BuildOptions; import io.ballerina.projects.Module; -import io.ballerina.projects.ProjectKind; import io.ballerina.projects.directory.BuildProject; import io.ballerina.tools.text.LinePosition; import io.ballerina.tools.text.LineRange; import org.ballerinalang.formatter.core.Formatter; import org.ballerinalang.formatter.core.FormatterException; +import org.ballerinalang.formatter.core.FormatterUtils; import org.ballerinalang.formatter.core.options.FormattingOptions; import org.ballerinalang.langserver.codelenses.CodeLensUtil; import org.ballerinalang.langserver.codelenses.LSCodeLensesProviderHolder; @@ -116,7 +116,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static org.ballerinalang.formatter.core.FormatterUtils.loadFormatSection; +import static org.ballerinalang.formatter.core.FormatterUtils.buildFormattingOptions; /** * Text document service implementation for ballerina. @@ -446,14 +446,10 @@ public CompletableFuture> formatting(DocumentFormatting return Collections.emptyList(); } String formattedSource; - Optional currentModule = context.currentModule(); - if (currentModule.isPresent() && - currentModule.get().project().kind() != ProjectKind.SINGLE_FILE_PROJECT) { + if (FormatterUtils.isBuildProject(context.currentModule())) { Path rootPath = context.workspace().projectRoot(context.filePath()); BuildProject project = BuildProject.load(rootPath, BuildOptions.builder().build()); - FormattingOptions options = FormattingOptions.builder() - .build(project.sourceRoot(), - loadFormatSection(project.currentPackage().manifest())); + FormattingOptions options = buildFormattingOptions(project); formattedSource = Formatter.format(syntaxTree.get(), options).toSourceCode(); } else { formattedSource = Formatter.format(syntaxTree.get()).toSourceCode(); diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml index 9646948d7e80..b53603fd5286 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "src/test/resources/formatting/project" +configPath = "Format.toml" diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index bbe041804e71..72128bcdbc48 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -128,9 +128,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S try { project = BuildProject.load(projectPath, constructBuildOptions()); - options = FormattingOptions.builder() - .build(project.sourceRoot(), - FormatterUtils.loadFormatSection(project.currentPackage().manifest())); + options = FormatterUtils.buildFormattingOptions(project); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } @@ -197,9 +195,7 @@ static void execute(List argList, boolean helpFlag, String moduleName, S FormattingOptions options; try { project = BuildProject.load(sourceRootPath, constructBuildOptions()); - options = FormattingOptions.builder() - .build(project.sourceRoot(), - FormatterUtils.loadFormatSection(project.currentPackage().manifest())); + options = FormatterUtils.buildFormattingOptions(project); } catch (ProjectException e) { throw LauncherUtils.createLauncherException(e.getMessage()); } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 907924065eac..684aeb82fea0 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -24,9 +24,12 @@ import io.ballerina.compiler.syntax.tree.NodeFactory; import io.ballerina.compiler.syntax.tree.SyntaxKind; import io.ballerina.compiler.syntax.tree.Token; +import io.ballerina.projects.Module; import io.ballerina.projects.PackageManifest; import io.ballerina.projects.ProjectException; +import io.ballerina.projects.ProjectKind; import io.ballerina.projects.TomlDocument; +import io.ballerina.projects.directory.BuildProject; import io.ballerina.projects.util.FileUtils; import io.ballerina.toml.api.Toml; import io.ballerina.toml.validator.TomlValidator; @@ -36,6 +39,7 @@ import io.ballerina.tools.text.LineRange; import org.apache.commons.lang3.builder.CompareToBuilder; import org.ballerinalang.formatter.core.options.FormatSection; +import org.ballerinalang.formatter.core.options.FormattingOptions; import org.ballerinalang.formatter.core.options.WrappingFormattingOptions; import java.io.BufferedReader; @@ -54,6 +58,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.ResourceBundle; import java.util.stream.Collectors; @@ -75,42 +80,106 @@ public class FormatterUtils { private FormatterUtils() { } + /** + * Build the formatting options given the build project. + * + * @param project the build project + * @return the FormattingOptions + */ + public static FormattingOptions buildFormattingOptions(BuildProject project) throws FormatterException { + return FormattingOptions.builder() + .build(project.sourceRoot(), loadFormatSection(project.currentPackage().manifest())); + } + + /** + * Checks whether the module is a build project. + * + * @param module Current module + * @return whether module is a build project + */ + public static boolean isBuildProject(Optional module) { + return module.isPresent() && module.get().project().kind() != ProjectKind.SINGLE_FILE_PROJECT; + } + + /** + * Retrieves the default boolean value for the format option in the given format section. + * + * @param section the format section + * @param key the format option + * @return the default boolean value + */ public static boolean getDefaultBoolean(FormatSection section, String key) { return Boolean.parseBoolean(getDefaultString(section, key)); } + /** + * Retrieves the default integer value for the format option in the given format section. + * + * @param section the format section + * @param key the format option + * @return the default integer value + */ public static int getDefaultInt(FormatSection section, String key) { return Integer.parseInt(getDefaultString(section, key)); } + /** + * Retrieves the default string value for the format option in the given format section. + * + * @param section the format section + * @param key the format option + * @return the default string value + */ public static String getDefaultString(FormatSection section, String key) { return DEFAULTS.getString(section.getStringValue() + "." + key); } + /** + * Loads the format section in the Ballerina.toml . + * + * @param manifest the package manifest + * @return the format section + */ public static Object loadFormatSection(PackageManifest manifest) { return manifest.getValue(FORMAT); } - public static String getFormattingFilePath(Object formatSection, String root) { + /** + * Retrieves the formatting file path. + * + * @param formatSection the format section loaded from Ballerina.toml + * @param root the root path of the project + * @return the formatting file path + */ + public static Optional getFormattingFilePath(Object formatSection, String root) { if (formatSection != null) { Object path = ((Map) formatSection).get(FORMAT_FILE_FIELD); if (path != null) { String str = path.toString(); if (str.endsWith(FORMAT_OPTION_FILE_EXT)) { - return str; + return Optional.of(str); } - return Path.of(str, DEFAULT_FORMAT_OPTION_FILE).toString(); + return Optional.of(Path.of(str, DEFAULT_FORMAT_OPTION_FILE).toString()); } } Path defaultFile = Path.of(root, DEFAULT_FORMAT_OPTION_FILE); - return Files.exists(defaultFile) ? defaultFile.toString() : null; + return Files.exists(defaultFile) ? Optional.of(defaultFile.toString()) : Optional.empty(); } - public static Map getFormattingConfigurations(Path root, String sPath) throws FormatterException { + /** + * Retrieves the formatting configurations. + * + * @param root the root path of the project + * @param configurationFilePath the path of configuration file + * @return the formatting configurations + * @throws FormatterException if the file resolution fails + */ + public static Map getFormattingConfigurations(Path root, String configurationFilePath) + throws FormatterException { String content; - Path path = Path.of(sPath); - Path absPath = path.isAbsolute() || !root.isAbsolute() ? path : root.resolve(sPath); + Path path = Path.of(configurationFilePath); + Path absPath = path.isAbsolute() || !root.isAbsolute() ? path : root.resolve(configurationFilePath); if (isLocalFile(absPath)) { try { content = Files.readString(absPath, StandardCharsets.UTF_8); @@ -118,17 +187,17 @@ public static Map getFormattingConfigurations(Path root, String throw new FormatterException("Failed to retrieve local formatting configuration file"); } } else { - content = readRemoteFormatFile(root, sPath); + content = readRemoteFormatFile(root, configurationFilePath); } - return parseConfigurationToml(TomlDocument.from(sPath, content)); + return parseConfigurationToml(TomlDocument.from(configurationFilePath, content)); } private static boolean isLocalFile(Path path) { return new File(path.toString()).exists(); } - static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { + private static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { Path cachePath = root.resolve(TARGET_DIR).resolve(FORMAT).resolve(DEFAULT_FORMAT_OPTION_FILE); if (Files.exists(cachePath)) { try { @@ -184,6 +253,13 @@ private static void cacheRemoteConfigurationFile(Path root, String content) thro } } + /** + * Retrieves the formatting configurations. + * + * @param document formatting configuration toml file + * @return the formatting options + * @throws FormatterException if the configuration file validation fails + */ public static Map parseConfigurationToml(TomlDocument document) throws FormatterException { Toml toml = document.toml(); if (toml.rootNode().entries().isEmpty()) { @@ -199,9 +275,9 @@ public static Map parseConfigurationToml(TomlDocument document) List diagnostics = toml.diagnostics(); boolean hasErrors = false; - for (Diagnostic d: diagnostics) { - if (d.diagnosticInfo().severity().equals(DiagnosticSeverity.ERROR)) { - errStream.println(d.message()); + for (Diagnostic diagnostic: diagnostics) { + if (diagnostic.diagnosticInfo().severity().equals(DiagnosticSeverity.ERROR)) { + errStream.println(diagnostic.message()); hasErrors = true; } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 02c5b59508f5..cb000fc86859 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -387,11 +387,11 @@ public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNo } Token openPara = formatToken(functionSignatureNode.openParenToken(), 0, parenTrailingNL); - boolean oneArgPerLine = funcOptions.parametersWrap() == WrappingMethod.ChopDown; int closeParenLeadingNL = funcOptions.rightParenOnNewLine() ? 1 : 0; + int separatorTrailingWS = funcOptions.parametersWrap() == WrappingMethod.ChopDown ? 0 : 1; SeparatedNodeList parameters = - formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, oneArgPerLine ? 0 : 1, - oneArgPerLine ? 1 : 0, 0, closeParenLeadingNL, true); + formatSeparatedNodeList(functionSignatureNode.parameters(), 0, 0, separatorTrailingWS, + invert(separatorTrailingWS), 0, closeParenLeadingNL, true); unalignOrUnindent(paranAlign, options.indentFormattingOptions().continuationIndentSize()); Token closePara; @@ -545,9 +545,8 @@ public IfElseStatementNode transform(IfElseStatementNode ifElseStatementNode) { BlockStatementNode ifBody; Node elseBody = null; if (ifElseStatementNode.elseBody().isPresent()) { - boolean needNL = options.ifStatementFormattingOptions().elseOnNewLine(); - ifBody = formatNode(ifElseStatementNode.ifBody(), needNL ? 0 : 1, - needNL ? 1 : 0); + int trailingWS = options.ifStatementFormattingOptions().elseOnNewLine() ? 0 : 1; + ifBody = formatNode(ifElseStatementNode.ifBody(), trailingWS, invert(trailingWS)); preserveIndentation(!hasTrailingNL(ifElseStatementNode.ifBody().closeBraceToken())); elseBody = formatNode(ifElseStatementNode.elseBody().orElse(null), env.trailingWS, env.trailingNL); preserveIndentation(prevPreservedNewLine); @@ -1100,11 +1099,11 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, callOptions.newLineAfterLeftParen() ? 1 : 0); - boolean oneArgPerLine = callOptions.parametersWrap() == WrappingMethod.ChopDown; int closeParenLeadingNL = callOptions.rightParenOnNewLine() ? 1 : 0; + int separatorTrailingWS = callOptions.parametersWrap() == WrappingMethod.ChopDown ? 0 : 1; SeparatedNodeList arguments = - formatSeparatedNodeList(functionCallExpressionNode.arguments(), 0, 0, oneArgPerLine ? 0 : 1, - oneArgPerLine ? 1 : 0, 0, closeParenLeadingNL, true); + formatSeparatedNodeList(functionCallExpressionNode.arguments(), 0, 0, separatorTrailingWS, + invert(separatorTrailingWS), 0, closeParenLeadingNL, true); setIndentation(prevIndentation); Token functionCallClosePara = formatToken(functionCallExpressionNode.closeParenToken(), env.trailingWS, env.trailingNL); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java index 343106bfea7c..aae38840a216 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java @@ -1,17 +1,19 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.ballerinalang.formatter.core.options; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 18034ddabe91..dec50e8d7e24 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -1,17 +1,19 @@ /* - * Copyright (c) 2020, WSO2 Inc. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.ballerinalang.formatter.core.options; @@ -19,6 +21,7 @@ import java.nio.file.Path; import java.util.Map; +import java.util.Optional; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingConfigurations; import static org.ballerinalang.formatter.core.FormatterUtils.getFormattingFilePath; @@ -177,18 +180,18 @@ public FormattingOptions build() { } public FormattingOptions build(Path root, Object formatSection) throws FormatterException { - String path = getFormattingFilePath(formatSection, root.toString()); - if (path == null) { + Optional path = getFormattingFilePath(formatSection, root.toString()); + if (path.isEmpty()) { return build(); } - Map configurations = getFormattingConfigurations(root, path); + Map configurations = getFormattingConfigurations(root, path.get()); for (Map.Entry entry : configurations.entrySet()) { - String key = entry.getKey(); Object value = entry.getValue(); if (!(value instanceof Map)) { continue; } Map configs = (Map) value; + String key = entry.getKey(); FormatSection section = FormatSection.fromString(key); switch (section) { case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build(configs); From ff261099f895b367c3b4adcfa2a6b2617fd238f7 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Wed, 20 Mar 2024 13:30:54 +0530 Subject: [PATCH 19/22] Handle invalid path exception in windows --- .../formatter/core/FormatterUtils.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index 684aeb82fea0..af48399a06bd 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -53,7 +53,9 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.InvalidPathException; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -178,11 +180,12 @@ public static Optional getFormattingFilePath(Object formatSection, Strin public static Map getFormattingConfigurations(Path root, String configurationFilePath) throws FormatterException { String content; - Path path = Path.of(configurationFilePath); - Path absPath = path.isAbsolute() || !root.isAbsolute() ? path : root.resolve(configurationFilePath); + Optional path = convertConfigurationPath(configurationFilePath); + Optional absPath = path.isEmpty() || path.get().isAbsolute() || !root.isAbsolute() ? path : + Optional.of(root.resolve(configurationFilePath)); if (isLocalFile(absPath)) { try { - content = Files.readString(absPath, StandardCharsets.UTF_8); + content = Files.readString(absPath.get(), StandardCharsets.UTF_8); } catch (IOException e) { throw new FormatterException("Failed to retrieve local formatting configuration file"); } @@ -193,8 +196,16 @@ public static Map getFormattingConfigurations(Path root, String return parseConfigurationToml(TomlDocument.from(configurationFilePath, content)); } - private static boolean isLocalFile(Path path) { - return new File(path.toString()).exists(); + private static Optional convertConfigurationPath(String path) { + try { + return Optional.of(Paths.get(path)); + } catch (InvalidPathException ex) { + return Optional.empty(); + } + } + + private static boolean isLocalFile(Optional path) throws InvalidPathException { + return !path.isEmpty() && new File(path.get().toString()).exists(); } private static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { From d25bf3e391a71af4eac099f4351888b0027868b5 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Fri, 22 Mar 2024 10:03:37 +0530 Subject: [PATCH 20/22] Address review comments --- .../formatter/cli/FormatCmdTest.java | 3 -- .../wrapping/source/project/Ballerina.toml | 2 +- .../formatter/core/FormatterUtils.java | 38 +++++++++++-------- .../core/options/BraceFormattingOptions.java | 2 +- .../formatter/core/options/BraceStyle.java | 2 +- .../core/options/ForceFormattingOptions.java | 2 +- .../formatter/core/options/FormatSection.java | 2 +- .../core/options/FormattingOptions.java | 2 +- .../FunctionCallFormattingOptions.java | 2 +- .../FunctionDeclFormattingOptions.java | 2 +- .../options/IfStatementFormattingOptions.java | 2 +- .../core/options/ImportFormattingOptions.java | 2 +- .../core/options/IndentFormattingOptions.java | 2 +- .../core/options/QueryFormattingOptions.java | 2 +- .../options/SpacingFormattingOptions.java | 2 +- .../options/WrappingFormattingOptions.java | 2 +- .../core/options/WrappingMethod.java | 2 +- .../src/main/resources/formatter.properties | 2 +- .../FormatFileResolutionTest.java | 11 +++++- .../LocalConfigurationTest.java | 2 +- .../RemoteConfigurationTest.java | 2 +- 21 files changed, 49 insertions(+), 39 deletions(-) diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index 5cea249a7a3f..f8a35b8ae876 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -91,7 +91,6 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< for (Path dir : dirs) { Path tempDir = dir.resolveSibling(dir.getFileName() + "Temp"); Path assertDir = Paths.get(dir.toString().replace("/source/", "/assert/")); - FormatUtil.execute(argList, false, null, null, false, dir); Assert.assertEquals(Files.readString(dir.resolve("main.bal")), Files.readString(assertDir.resolve("main.bal"))); @@ -353,7 +352,6 @@ public void formatCLIOnBallerinaProjectWithModulesWithConfigurations() { Path moduleRelativePath = Path.of("modules", module, "core.bal"); try { FormatUtil.execute(argList, false, module, null, false, projectDir); - Assert.assertEquals(Files.readString(projectDir.resolve("main.bal")), Files.readString(assertDir.resolve("main.bal"))); Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), @@ -376,7 +374,6 @@ public void formatCLIOnBallernaProjectWithModulesWithConfigurations() { Path moduleRelativePath = Path.of("modules", module, "mod.bal"); try { FormatUtil.execute(argList, false, module, null, false, sourceDir.resolve("source")); - Assert.assertEquals(Files.readString(projectDir.resolve("main.bal")), Files.readString(assertDir.resolve("main.bal"))); Assert.assertEquals(Files.readString(projectDir.resolve(moduleRelativePath)), diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml index 4da7c944567f..c14ec321d486 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "dir/Format.toml" +configPath = "dir" diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index af48399a06bd..dff628ef04ed 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -51,6 +51,7 @@ import java.io.PrintStream; import java.net.HttpURLConnection; import java.net.URL; +import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.InvalidPathException; @@ -69,14 +70,13 @@ */ public class FormatterUtils { static final String NEWLINE_SYMBOL = System.getProperty("line.separator"); - static final String FORMAT_FILE_FIELD = "configPath"; - static final String FORMAT_OPTION_FILE_EXT = ".toml"; - static final String DEFAULT_FORMAT_OPTION_FILE = "Format.toml"; - static final String TARGET_DIR = "target"; - static final String FORMAT = "format"; - static final String FORMAT_TOML_SCHEMA = "format-toml-schema.json"; + private static final String FORMAT_FILE_FIELD = "configPath"; + private static final String FORMAT_OPTION_FILE_EXT = ".toml"; + private static final String DEFAULT_FORMAT_OPTION_FILE = "Format.toml"; + private static final String TARGET_DIR = "target"; + private static final String FORMAT = "format"; + private static final String FORMAT_TOML_SCHEMA = "format-toml-schema.json"; private static final PrintStream errStream = System.err; - public static final ResourceBundle DEFAULTS = ResourceBundle.getBundle("formatter", Locale.getDefault()); private FormatterUtils() { @@ -187,7 +187,8 @@ public static Map getFormattingConfigurations(Path root, String try { content = Files.readString(absPath.get(), StandardCharsets.UTF_8); } catch (IOException e) { - throw new FormatterException("Failed to retrieve local formatting configuration file"); + throw new FormatterException( + "Failed to retrieve local formatting configuration file: " + configurationFilePath); } } else { content = readRemoteFormatFile(root, configurationFilePath); @@ -205,7 +206,7 @@ private static Optional convertConfigurationPath(String path) { } private static boolean isLocalFile(Optional path) throws InvalidPathException { - return !path.isEmpty() && new File(path.get().toString()).exists(); + return path.isPresent() && new File(path.get().toString()).exists(); } private static String readRemoteFormatFile(Path root, String fileUrl) throws FormatterException { @@ -221,22 +222,26 @@ private static String readRemoteFormatFile(Path root, String fileUrl) throws For StringBuilder fileContent = new StringBuilder(); try { URL url = new URL(fileUrl); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - int responseCode = connection.getResponseCode(); + URLConnection connection = url.openConnection(); + if (!(connection instanceof HttpURLConnection)) { + throw new FormatterException("Configuration file remote url is not an HTTP url: " + fileUrl); + } + HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); + int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { - connection.disconnect(); + httpURLConnection.disconnect(); throw new FormatterException("Failed to retrieve remote file. HTTP response code: " + responseCode); } try (BufferedReader reader = new BufferedReader( - new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { + new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { fileContent.append(line).append(NEWLINE_SYMBOL); } } - connection.disconnect(); + httpURLConnection.disconnect(); } catch (IOException e) { - throw new FormatterException("Failed to retrieve formatting configuration file"); + throw new FormatterException("Failed to retrieve formatting configuration file: " + fileUrl); } cacheRemoteConfigurationFile(root, fileContent.toString()); @@ -422,7 +427,8 @@ private static boolean hasEmptyLineAtEnd(MinutiaeList minutiaeList) { } static int openBraceTrailingNLs(WrappingFormattingOptions options, Node node) { - if (node.lineRange().startLine().line() != node.lineRange().endLine().line()) { + LineRange lineRange = node.lineRange(); + if (lineRange.startLine().line() != lineRange.endLine().line()) { return 1; } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index 9c578604cb22..c6c43e107786 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index dc379f2ded0e..4847c33c670a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java index aae38840a216..5fbdf285bd17 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ForceFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java index 295113e84ab4..ae2e27ea9847 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index dec50e8d7e24..9a9af86f3190 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index 4846e37cd705..8246e6233678 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index 7226e666d773..ac47cfead4f8 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index dfb3a80bf89f..5af5fb1cb379 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index 43fb81a03c36..04e5bb1eb3ee 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index ddf619868f4a..a10aecf3d333 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index 58c570f72737..a8a30f6d72db 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 058bbd44ba2b..18cb5380d67b 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index 3aafdf814474..ab41f548a10e 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index f139b3c83102..9ec2f703f207 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). + * Copyright (c) 2024, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties index efbde00fb3b7..021fc71018b6 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties +++ b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties @@ -1,5 +1,5 @@ # -# Copyright (c) 2023, WSO2 LLC. (http://wso2.com). +# Copyright (c) 2024, WSO2 LLC. (http://wso2.com). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java index 15d6beb76198..a1b29b48c47f 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java @@ -64,7 +64,7 @@ public void cacheWithTargetDirectoryPresent() throws FormatterException { @Test(description = "Test invalid local formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to retrieve local formatting configuration file") + expectedExceptionsMessageRegExp = "Failed to retrieve local formatting configuration file.*") public void invalidLocalFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("directory.toml").toString()); } @@ -76,6 +76,13 @@ public void invalidRemoteCachedFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(resDir.resolve(Path.of("invalidCached")), validRemoteUrl); } + @Test(description = "Test invalid remote file protocol", expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "Configuration file remote url is not an HTTP url:.*") + public void invalidRemoteFileProtocol() throws FormatterException { + Path invalidUrl = resDir.resolve("invalidUrl"); + FormatterUtils.getFormattingConfigurations(invalidUrl, "ftp://example.com/Format.toml"); + } + @Test(description = "Test invalid remote formatting configuration file url", expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Failed to retrieve remote file. HTTP response code:.*") @@ -86,7 +93,7 @@ public void invalidRemoteFormatFileURLTest() throws FormatterException { } @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to retrieve formatting configuration file") + expectedExceptionsMessageRegExp = "Failed to retrieve formatting configuration file.*") public void getInvalidFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("t.toml").toString()); } diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java index 379ded3cd9ee..b0ef751df782 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/LocalConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java index 2bf099e56731..5becea390c12 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/RemoteConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved. + * Copyright (c) 2023, WSO2 LLC. (http://wso2.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From ad4ddd5c3dea2acbb403becd7e9388bc49f3521e Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Fri, 29 Mar 2024 08:58:46 +0530 Subject: [PATCH 21/22] Update option names --- .../resources/formatting/project/Format.toml | 4 +- .../formatter/cli/FormatUtil.java | 4 +- .../ballerinalang/formatter/cli/Messages.java | 2 +- .../module/source/project/Format.toml | 2 +- .../options/brace/source/project/Format.toml | 2 +- .../functionCall/source/chopDown/Format.toml | 6 +- .../functionCall/source/noWrap/Format.toml | 4 +- .../functionCall/source/wrap/Format.toml | 6 +- .../source/chopDown/Format.toml | 2 +- .../source/noWrap/Format.toml | 2 +- .../source/wrap/Format.toml | 2 +- .../options/indent/source/project/Format.toml | 2 +- .../wrapping/source/project/dir/Format.toml | 2 +- .../source/project/Format.toml | 2 +- .../formatter/core/FormatterUtils.java | 41 ++++++++----- .../core/FormattingTreeModifier.java | 20 +++---- .../core/options/BraceFormattingOptions.java | 26 ++++---- .../formatter/core/options/BraceStyle.java | 2 +- .../formatter/core/options/FormatSection.java | 6 +- .../core/options/FormattingOptions.java | 4 +- .../FunctionCallFormattingOptions.java | 59 ++++++++++--------- .../FunctionDeclFormattingOptions.java | 25 ++++---- .../options/IfStatementFormattingOptions.java | 2 +- .../core/options/ImportFormattingOptions.java | 2 +- .../core/options/IndentFormattingOptions.java | 2 +- .../core/options/QueryFormattingOptions.java | 2 +- .../options/SpacingFormattingOptions.java | 2 +- .../options/WrappingFormattingOptions.java | 24 ++++---- .../core/options/WrappingMethod.java | 2 +- .../main/resources/format-toml-schema.json | 14 ++--- .../src/main/resources/formatter.properties | 22 +++---- .../FormatFileResolutionTest.java | 14 ++--- .../FormatFileValidatorTest.java | 3 +- .../FormatOptionNegativeTest.java | 32 +++++----- .../remote/source/Ballerina.toml | 2 +- .../validator/invalid/Format.toml | 10 ++-- .../validator/valid/Format.toml | 12 ++-- 37 files changed, 192 insertions(+), 178 deletions(-) diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml index f310175dab69..d68d4dc5017a 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml @@ -4,9 +4,9 @@ indentSize = 2 [wrapping] maxLineLength = 80 simpleBlocksInOneLine = true -simpleMethodsInOneLine = true +simpleFunctionsInOneLine = true -[methodDeclaration] +[functionDeclaration] alignMultilineParameters = true [ifStatement] diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java index 72128bcdbc48..978d39e56b9c 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/FormatUtil.java @@ -257,8 +257,10 @@ static void execute(List argList, boolean helpFlag, String moduleName, S generateChangeReport(formattedFiles, dryRun); } } - } catch (IOException | NullPointerException | FormatterException e) { + } catch (IOException | NullPointerException e) { throw LauncherUtils.createLauncherException(Messages.getException() + e); + } catch (FormatterException e) { + throw LauncherUtils.createLauncherException(Messages.getException() + e.getMessage()); } } diff --git a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java index 44540cd363aa..f51ea4c00247 100644 --- a/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java +++ b/misc/formatter/modules/formatter-cli/src/main/java/org/ballerinalang/formatter/cli/Messages.java @@ -36,7 +36,7 @@ public class Messages { private static final String NO_MODULE_FOUND = "couldn't find an existing module by the name: "; - private static final String EXCEPTION = "something went wrong when formatting." + System.lineSeparator(); + private static final String EXCEPTION = "formatting failed - "; private static final String NO_BALLERINA_FILE = "couldn't find an existing ballerina file by the name: "; diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml index 524d91dc8b7a..9e075acadd91 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/module/source/project/Format.toml @@ -5,7 +5,7 @@ indentSize = 2 maxLineLength = 120 [braces] -methodBraceStyle = "NewLine" +functionBraceStyle = "NewLine" [ifStatement] elseOnNewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml index 18845f1041a4..0e2a76dffe5b 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/brace/source/project/Format.toml @@ -1,3 +1,3 @@ [braces] classBraceStyle = "NewLine" -methodBraceStyle = "NewLine" +functionBraceStyle = "NewLine" diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml index 5c000c872f6e..1e2e59918395 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/chopDown/Format.toml @@ -1,6 +1,6 @@ -[methodCall] -parametersWrap = "ChopDown" -alignMultilineParameters = true +[functionCall] +argumentsWrap = "ChopDown" +alignMultilineArguments = true newLineAfterLeftParen = true [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml index d2a006fec672..5cbff90548e9 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/noWrap/Format.toml @@ -1,5 +1,5 @@ -[methodCall] -parametersWrap = "NoWrap" +[functionCall] +argumentsWrap = "NoWrap" newLineAfterLeftParen = true [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml index 365a236c13aa..235f5ffbface 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionCall/source/wrap/Format.toml @@ -1,6 +1,6 @@ -[methodCall] -parametersWrap = "Wrap" -alignMultilineParameters = true +[functionCall] +argumentsWrap = "Wrap" +alignMultilineArguments = true newLineAfterLeftParen = true rightParenOnNewLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml index 475a4cee5ca0..75c3ddbfddb7 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml @@ -1,4 +1,4 @@ -[methodDeclaration] +[functionDeclaration] parametersWrap = "ChopDown" alignMultilineParameters = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml index 0c5c088616de..f0fce7dc7d10 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml @@ -1,4 +1,4 @@ -[methodDeclaration] +[functionDeclaration] parametersWrap = "NoWrap" [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml index 5fc3a18b60f4..94978d78125f 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml @@ -1,4 +1,4 @@ -[methodDeclaration] +[functionDeclaration] parametersWrap = "Wrap" alignMultilineParameters = true newLineAfterLeftParen = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml index a9ff5e340462..01166316a5b1 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/indent/source/project/Format.toml @@ -1,3 +1,3 @@ [indent] indentSize = 2 -continuationIndentSize = 2 +continuationIndentSize = 4 diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml index 10d58a05e0bc..d66aa1b3dad6 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/wrapping/source/project/dir/Format.toml @@ -1,4 +1,4 @@ [wrapping] maxLineLength = 80 simpleBlocksInOneLine = true -simpleMethodsInOneLine = true +simpleFunctionsInOneLine = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml index f36c895a705f..f53a8a07cb6b 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml @@ -5,7 +5,7 @@ continuationIndentSize = 4 maxLineLength = 80 -[methodDeclaration] +[functionDeclaration] alignMultilineParameters = true newLineAfterLeftParen = true diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java index dff628ef04ed..47d1a02ed3ea 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormatterUtils.java @@ -57,6 +57,7 @@ import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -188,7 +189,7 @@ public static Map getFormattingConfigurations(Path root, String content = Files.readString(absPath.get(), StandardCharsets.UTF_8); } catch (IOException e) { throw new FormatterException( - "Failed to retrieve local formatting configuration file: " + configurationFilePath); + "failed to retrieve local formatting configuration file: " + configurationFilePath); } } else { content = readRemoteFormatFile(root, configurationFilePath); @@ -215,7 +216,7 @@ private static String readRemoteFormatFile(Path root, String fileUrl) throws For try { return Files.readString(cachePath, StandardCharsets.UTF_8); } catch (IOException e) { - throw new FormatterException("Failed to read cached formatting configuration file"); + throw new FormatterException("failed to read cached formatting configuration file"); } } @@ -224,13 +225,13 @@ private static String readRemoteFormatFile(Path root, String fileUrl) throws For URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); if (!(connection instanceof HttpURLConnection)) { - throw new FormatterException("Configuration file remote url is not an HTTP url: " + fileUrl); + throw new FormatterException("configuration file remote url is not an HTTP url: " + fileUrl); } HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { httpURLConnection.disconnect(); - throw new FormatterException("Failed to retrieve remote file. HTTP response code: " + responseCode); + throw new FormatterException("failed to retrieve remote file. HTTP response code: " + responseCode); } try (BufferedReader reader = new BufferedReader( new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) { @@ -241,7 +242,7 @@ private static String readRemoteFormatFile(Path root, String fileUrl) throws For } httpURLConnection.disconnect(); } catch (IOException e) { - throw new FormatterException("Failed to retrieve formatting configuration file: " + fileUrl); + throw new FormatterException("failed to retrieve formatting configuration file: " + fileUrl); } cacheRemoteConfigurationFile(root, fileContent.toString()); @@ -258,14 +259,14 @@ private static void cacheRemoteConfigurationFile(Path root, String content) thro try { Files.createDirectories(formatDir); } catch (IOException e) { - throw new FormatterException("Failed to create format configuration cache directory"); + throw new FormatterException("failed to create format configuration cache directory"); } } String filePath = formatDir.resolve(DEFAULT_FORMAT_OPTION_FILE).toString(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, StandardCharsets.UTF_8))) { writer.write(content); } catch (IOException e) { - throw new FormatterException("Failed to write format configuration cache file"); + throw new FormatterException("failed to write format configuration cache file"); } } @@ -274,7 +275,7 @@ private static void cacheRemoteConfigurationFile(Path root, String content) thro * * @param document formatting configuration toml file * @return the formatting options - * @throws FormatterException if the configuration file validation fails + * @throws FormatterException if the configuration file X`n fails */ public static Map parseConfigurationToml(TomlDocument document) throws FormatterException { Toml toml = document.toml(); @@ -290,15 +291,15 @@ public static Map parseConfigurationToml(TomlDocument document) formatTomlValidator.validate(toml); List diagnostics = toml.diagnostics(); - boolean hasErrors = false; + ArrayList errMessages = new ArrayList<>(); for (Diagnostic diagnostic: diagnostics) { if (diagnostic.diagnosticInfo().severity().equals(DiagnosticSeverity.ERROR)) { - errStream.println(diagnostic.message()); - hasErrors = true; + errMessages.add(diagnostic.message()); } } - if (hasErrors) { - throw new FormatterException("Invalid Format.toml file"); + if (errMessages.size() > 0) { + throw new FormatterException("invalid formatting configuration file" + System.lineSeparator() + + String.join(System.lineSeparator(), errMessages)); } return toml.toMap(); } @@ -432,11 +433,19 @@ static int openBraceTrailingNLs(WrappingFormattingOptions options, Node node) { return 1; } - SyntaxKind parentKind = node.parent().kind(); - if (options.isSimpleBlocksInOneLine() && parentKind != SyntaxKind.METHOD_DECLARATION) { + boolean isParentAFunction = isFunctionNode(node.parent()); + if (options.isSimpleBlocksInOneLine() && !isParentAFunction) { return 0; } - return (options.isSimpleMethodsInOneLine() && parentKind == SyntaxKind.METHOD_DECLARATION) ? 0 : 1; + return (options.isSimpleFunctionsInOneLine() && isParentAFunction) ? 0 : 1; + } + + private static boolean isFunctionNode(Node node) { + return switch (node.kind()) { + case FUNCTION_DEFINITION, METHOD_DECLARATION, OBJECT_METHOD_DEFINITION, RESOURCE_ACCESSOR_DEFINITION -> + true; + default -> false; + }; } static int getConstDefWidth(ConstantDeclarationNode node) { diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index cb000fc86859..65cbae3545c9 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -323,7 +323,7 @@ public FunctionDefinitionNode transform(FunctionDefinitionNode functionDefinitio functionName = formatToken(functionDefinitionNode.functionName(), 1, 0); } NodeList relativeResourcePath = formatNodeList(functionDefinitionNode.relativeResourcePath(), 0, 0, 0, 0); - int trailingNL = options.braceFormattingOptions().methodBraceStyle() == BraceStyle.NewLine ? 1 : 0; + int trailingNL = options.braceFormattingOptions().functionBraceStyle() == BraceStyle.NewLine ? 1 : 0; FunctionSignatureNode functionSignatureNode = formatNode(functionDefinitionNode.functionSignature(), invert(trailingNL), trailingNL); FunctionBodyNode functionBodyNode = @@ -1094,13 +1094,13 @@ public FunctionCallExpressionNode transform(FunctionCallExpressionNode functionC NameReferenceNode functionName = formatNode(functionCallExpressionNode.functionName(), 0, 0); FunctionCallFormattingOptions callOptions = options.functionCallFormattingOptions(); int prevIndentation = env.currentIndentation; - alignOrIndent(callOptions.alignMultilineParameters(), + alignOrIndent(callOptions.alignMultilineArguments(), options.indentFormattingOptions().continuationIndentSize()); Token functionCallOpenPara = formatToken(functionCallExpressionNode.openParenToken(), 0, callOptions.newLineAfterLeftParen() ? 1 : 0); int closeParenLeadingNL = callOptions.rightParenOnNewLine() ? 1 : 0; - int separatorTrailingWS = callOptions.parametersWrap() == WrappingMethod.ChopDown ? 0 : 1; + int separatorTrailingWS = callOptions.argumentsWrap() == WrappingMethod.ChopDown ? 0 : 1; SeparatedNodeList arguments = formatSeparatedNodeList(functionCallExpressionNode.arguments(), 0, 0, separatorTrailingWS, invert(separatorTrailingWS), 0, closeParenLeadingNL, true); @@ -4278,7 +4278,7 @@ private boolean shouldWrapLine(Node node, Node parent) { case POSITIONAL_ARG: case NAMED_ARG: case REST_ARG: - if (options.functionCallFormattingOptions().parametersWrap() == WrappingMethod.NoWrap) { + if (options.functionCallFormattingOptions().argumentsWrap() == WrappingMethod.NoWrap) { return false; } return true; @@ -4550,16 +4550,16 @@ private List removeTrailingWS(List trailingMinutiae) { * Indent the code by the number of white-spaces defined by tab-size. */ private void indent() { - indent(1); + indent(options.indentFormattingOptions().indentSize()); } /** * Indent the code by the number of white-spaces defined by tab-size. * - * @param step Number of tabs. + * @param step Number of spaces. */ private void indent(int step) { - env.currentIndentation += (options.indentFormattingOptions().indentSize() * step); + env.currentIndentation += step; } /** @@ -4574,7 +4574,7 @@ private void align() { * Undo the indentation of the code by the number of white-spaces defined by tab-size. */ private void unindent() { - unindent(1); + unindent(options.indentFormattingOptions().indentSize()); } /** @@ -4583,12 +4583,12 @@ private void unindent() { * @param step Number of tabs. */ private void unindent(int step) { - if (env.currentIndentation < (options.indentFormattingOptions().indentSize() * step)) { + if (env.currentIndentation < step) { env.currentIndentation = 0; return; } - env.currentIndentation -= (options.indentFormattingOptions().indentSize() * step); + env.currentIndentation -= step; } /** diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java index c6c43e107786..867a78319579 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceFormattingOptions.java @@ -29,19 +29,19 @@ public class BraceFormattingOptions { private final BraceStyle classBraceStyle; - private final BraceStyle methodBraceStyle; + private final BraceStyle functionBraceStyle; - private BraceFormattingOptions(BraceStyle classBraceStyle, BraceStyle methodBraceStyle) { + private BraceFormattingOptions(BraceStyle classBraceStyle, BraceStyle functionBraceStyle) { this.classBraceStyle = classBraceStyle; - this.methodBraceStyle = methodBraceStyle; + this.functionBraceStyle = functionBraceStyle; } public BraceStyle classBraceStyle() { return classBraceStyle; } - public BraceStyle methodBraceStyle() { - return methodBraceStyle; + public BraceStyle functionBraceStyle() { + return functionBraceStyle; } public static BraceFormattingOptions.BraceFormattingOptionsBuilder builder() { @@ -51,24 +51,24 @@ public static BraceFormattingOptions.BraceFormattingOptionsBuilder builder() { public static class BraceFormattingOptionsBuilder { private static final String CLASS_BRACE_STYLE = "classBraceStyle"; - private static final String METHOD_BRACE_STYLE = "methodBraceStyle"; + private static final String FUNCTION_BRACE_STYLE = "functionBraceStyle"; private BraceStyle classBraceStyle = BraceStyle.valueOf(getDefaultString(FormatSection.BRACES, CLASS_BRACE_STYLE)); - private BraceStyle methodBraceStyle = - BraceStyle.valueOf(getDefaultString(FormatSection.BRACES, METHOD_BRACE_STYLE)); + private BraceStyle functionBraceStyle = + BraceStyle.valueOf(getDefaultString(FormatSection.BRACES, FUNCTION_BRACE_STYLE)); public BraceFormattingOptionsBuilder setClassBraceStyle(BraceStyle classBraceStyle) { this.classBraceStyle = classBraceStyle; return this; } - public BraceFormattingOptionsBuilder setMethodBraceStyle(BraceStyle methodBraceStyle) { - this.methodBraceStyle = methodBraceStyle; + public BraceFormattingOptionsBuilder setFunctionBraceStyle(BraceStyle functionBraceStyle) { + this.functionBraceStyle = functionBraceStyle; return this; } public BraceFormattingOptions build() { - return new BraceFormattingOptions(classBraceStyle, methodBraceStyle); + return new BraceFormattingOptions(classBraceStyle, functionBraceStyle); } public BraceFormattingOptions build(Map configs) throws FormatterException { @@ -77,8 +77,8 @@ public BraceFormattingOptions build(Map configs) throws Formatte BraceStyle style = BraceStyle.fromString((String) bracesEntry.getValue()); switch (bracesKey) { case CLASS_BRACE_STYLE -> setClassBraceStyle(style); - case METHOD_BRACE_STYLE -> setMethodBraceStyle(style); - default -> throw new FormatterException("Invalid Brace Option: " + bracesKey); + case FUNCTION_BRACE_STYLE -> setFunctionBraceStyle(style); + default -> throw new FormatterException("invalid Brace Option: " + bracesKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java index 4847c33c670a..984cebd7e6fd 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/BraceStyle.java @@ -30,7 +30,7 @@ public static BraceStyle fromString(String value) throws FormatterException { try { return BraceStyle.valueOf(value); } catch (IllegalArgumentException e) { - throw new FormatterException("Invalid Brace style: " + value); + throw new FormatterException("invalid Brace style: " + value); } } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java index ae2e27ea9847..0a812485641f 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -24,8 +24,8 @@ */ public enum FormatSection { BRACES("braces"), - METHOD_CALL("methodCall"), - METHOD_DECLARATION("methodDeclaration"), + FUNCTION_CALL("functionCall"), + FUNCTION_DECLARATION("functionDeclaration"), IF_STATEMENT("ifStatement"), IMPORT("import"), INDENT("indent"), @@ -49,6 +49,6 @@ public static FormatSection fromString(String value) throws FormatterException { return section; } } - throw new FormatterException("Invalid format section: " + value); + throw new FormatterException("invalid format section: " + value); } } diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 9a9af86f3190..5626f20fc18f 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -197,9 +197,9 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build(configs); case WRAPPING -> wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); case BRACES -> braceFormattingOptions = BraceFormattingOptions.builder().build(configs); - case METHOD_DECLARATION -> + case FUNCTION_DECLARATION -> functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); - case METHOD_CALL -> + case FUNCTION_CALL -> functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); case IF_STATEMENT -> ifStatementFormattingOptions = IfStatementFormattingOptions.builder().build(configs); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java index 8246e6233678..9b57b2fa0d01 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionCallFormattingOptions.java @@ -30,25 +30,25 @@ public class FunctionCallFormattingOptions { - private final WrappingMethod parametersWrap; - private final boolean alignMultilineParameters; + private final WrappingMethod argumentsWrap; + private final boolean alignMultilineArguments; private final boolean newLineAfterLeftParen; private final boolean rightParenOnNewLine; - private FunctionCallFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + private FunctionCallFormattingOptions(WrappingMethod argumentsWrap, boolean alignMultilineArguments, boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { - this.parametersWrap = parametersWrap; - this.alignMultilineParameters = alignMultilineParameters; + this.argumentsWrap = argumentsWrap; + this.alignMultilineArguments = alignMultilineArguments; this.newLineAfterLeftParen = newLineAfterLeftParen; this.rightParenOnNewLine = rightParenOnNewLine; } - public WrappingMethod parametersWrap() { - return parametersWrap; + public WrappingMethod argumentsWrap() { + return argumentsWrap; } - public boolean alignMultilineParameters() { - return alignMultilineParameters; + public boolean alignMultilineArguments() { + return alignMultilineArguments; } public boolean newLineAfterLeftParen() { @@ -68,26 +68,27 @@ public static FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder */ public static class FunctionCallFormattingOptionsBuilder { - private static final String PARAMETERS_WRAP = "parametersWrap"; - private static final String ALIGN_MULTILINE_PARAMETERS = "alignMultilineParameters"; + private static final String ARGUMENTS_WRAP = "argumentsWrap"; + private static final String ALIGN_MULTILINE_ARGUMENTS = "alignMultilineArguments"; private static final String NEWLINE_AFTER_LEFT_PAREN = "newLineAfterLeftParen"; private static final String RIGHT_PAREN_ON_NEWLINE = "rightParenOnNewLine"; - private WrappingMethod parametersWrap = - WrappingMethod.valueOf(getDefaultString(FormatSection.METHOD_CALL, PARAMETERS_WRAP)); - private boolean alignMultilineParameters = - getDefaultBoolean(FormatSection.METHOD_CALL, ALIGN_MULTILINE_PARAMETERS); - private boolean newLineAfterLeftParen = getDefaultBoolean(FormatSection.METHOD_CALL, NEWLINE_AFTER_LEFT_PAREN); - private boolean rightParenOnNewLine = getDefaultBoolean(FormatSection.METHOD_CALL, RIGHT_PAREN_ON_NEWLINE); - - public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setParametersWrap( - WrappingMethod parametersWrap) { - this.parametersWrap = parametersWrap; + private WrappingMethod argumentsWrap = + WrappingMethod.valueOf(getDefaultString(FormatSection.FUNCTION_CALL, ARGUMENTS_WRAP)); + private boolean alignMultilineArguments = + getDefaultBoolean(FormatSection.FUNCTION_CALL, ALIGN_MULTILINE_ARGUMENTS); + private boolean newLineAfterLeftParen = + getDefaultBoolean(FormatSection.FUNCTION_CALL, NEWLINE_AFTER_LEFT_PAREN); + private boolean rightParenOnNewLine = getDefaultBoolean(FormatSection.FUNCTION_CALL, RIGHT_PAREN_ON_NEWLINE); + + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setArgumentsWrap( + WrappingMethod argumentsWrap) { + this.argumentsWrap = argumentsWrap; return this; } - public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setAlignMultilineParameters( - boolean alignMultilineParameters) { - this.alignMultilineParameters = alignMultilineParameters; + public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setAlignMultilineArguments( + boolean alignMultilineArguments) { + this.alignMultilineArguments = alignMultilineArguments; return this; } @@ -104,7 +105,7 @@ public FunctionCallFormattingOptions.FunctionCallFormattingOptionsBuilder setRig } public FunctionCallFormattingOptions build() { - return new FunctionCallFormattingOptions(parametersWrap, alignMultilineParameters, newLineAfterLeftParen, + return new FunctionCallFormattingOptions(argumentsWrap, alignMultilineArguments, newLineAfterLeftParen, rightParenOnNewLine); } @@ -112,12 +113,12 @@ public FunctionCallFormattingOptions build(Map configs) throws F for (Map.Entry funcCallEntry : configs.entrySet()) { String funcCallKey = funcCallEntry.getKey(); switch (funcCallKey) { - case PARAMETERS_WRAP -> - setParametersWrap(WrappingMethod.fromString((String) funcCallEntry.getValue())); - case ALIGN_MULTILINE_PARAMETERS -> setAlignMultilineParameters((Boolean) funcCallEntry.getValue()); + case ARGUMENTS_WRAP -> + setArgumentsWrap(WrappingMethod.fromString((String) funcCallEntry.getValue())); + case ALIGN_MULTILINE_ARGUMENTS -> setAlignMultilineArguments((Boolean) funcCallEntry.getValue()); case NEWLINE_AFTER_LEFT_PAREN -> setNewLineAfterLeftParen((Boolean) funcCallEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) funcCallEntry.getValue()); - default -> throw new FormatterException("Invalid function call formatting option: " + funcCallKey); + default -> throw new FormatterException("invalid function call formatting option: " + funcCallKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java index ac47cfead4f8..29aaaca0fffe 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java @@ -69,13 +69,13 @@ public static class FunctionDeclFormattingOptionsBuilder { private static final String NEWLINE_AFTER_LEFT_PAREN = "newLineAfterLeftParen"; private static final String RIGHT_PAREN_ON_NEWLINE = "rightParenOnNewLine"; private WrappingMethod parametersWrap = - WrappingMethod.valueOf(getDefaultString(FormatSection.METHOD_DECLARATION, PARAMETERS_WRAP)); + WrappingMethod.valueOf(getDefaultString(FormatSection.FUNCTION_DECLARATION, PARAMETERS_WRAP)); private boolean alignMultilineParameters = - getDefaultBoolean(FormatSection.METHOD_DECLARATION, ALIGN_MULTILINE_PARAMETERS); + getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, ALIGN_MULTILINE_PARAMETERS); private boolean newLineAfterLeftParen = - getDefaultBoolean(FormatSection.METHOD_DECLARATION, NEWLINE_AFTER_LEFT_PAREN); + getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, NEWLINE_AFTER_LEFT_PAREN); private boolean rightParenOnNewLine = - getDefaultBoolean(FormatSection.METHOD_DECLARATION, RIGHT_PAREN_ON_NEWLINE); + getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, RIGHT_PAREN_ON_NEWLINE); public FunctionDeclFormattingOptionsBuilder setParametersWrap(WrappingMethod parametersWrap) { this.parametersWrap = parametersWrap; @@ -103,18 +103,19 @@ public FunctionDeclFormattingOptions build() { } public FunctionDeclFormattingOptions build(Map configs) throws FormatterException { - for (Map.Entry methodDeclarationEntry : configs.entrySet()) { - String methodDeclarationKey = methodDeclarationEntry.getKey(); - switch (methodDeclarationKey) { + for (Map.Entry functionDeclarationEntry : configs.entrySet()) { + String functionDeclarationKey = functionDeclarationEntry.getKey(); + switch (functionDeclarationKey) { case PARAMETERS_WRAP -> - setParametersWrap(WrappingMethod.fromString((String) methodDeclarationEntry.getValue())); + setParametersWrap(WrappingMethod.fromString((String) functionDeclarationEntry.getValue())); case ALIGN_MULTILINE_PARAMETERS -> - setAlignMultilineParameters((Boolean) methodDeclarationEntry.getValue()); + setAlignMultilineParameters((Boolean) functionDeclarationEntry.getValue()); case NEWLINE_AFTER_LEFT_PAREN -> - setNewLineAfterLeftParen((Boolean) methodDeclarationEntry.getValue()); - case RIGHT_PAREN_ON_NEWLINE -> setRightParenOnNewLine((Boolean) methodDeclarationEntry.getValue()); + setNewLineAfterLeftParen((Boolean) functionDeclarationEntry.getValue()); + case RIGHT_PAREN_ON_NEWLINE -> + setRightParenOnNewLine((Boolean) functionDeclarationEntry.getValue()); default -> throw new FormatterException( - "Invalid function declaration formatting option: " + methodDeclarationKey); + "invalid function declaration formatting option: " + functionDeclarationKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java index 5af5fb1cb379..b040d6b99d12 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IfStatementFormattingOptions.java @@ -62,7 +62,7 @@ public IfStatementFormattingOptions build(Map configs) throws Fo if (ifStatementKey.equals(ELSE_ON_NEW_LINE)) { setElseOnNewLine((Boolean) ifStatementEntry.getValue()); } else { - throw new FormatterException("Invalid if statement formatting option: " + ifStatementKey); + throw new FormatterException("invalid if statement formatting option: " + ifStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java index 04e5bb1eb3ee..bf7f52900ad5 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/ImportFormattingOptions.java @@ -92,7 +92,7 @@ public ImportFormattingOptions build(Map configs) throws Formatt switch (importKey) { case SORT_IMPORTS -> setSortImports((Boolean) importEntry.getValue()); case GROUP_IMPORTS -> setGroupImports((Boolean) importEntry.getValue()); - default -> throw new FormatterException("Invalid import formatting option: " + importKey); + default -> throw new FormatterException("invalid import formatting option: " + importKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java index a10aecf3d333..f09017aaa04f 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/IndentFormattingOptions.java @@ -86,7 +86,7 @@ public IndentFormattingOptions build(Map configs) throws Formatt case INDENT_SIZE -> setIndentSize(((Number) indentEntry.getValue()).intValue()); case CONTINUATION_INDENT_SIZE -> setContinuationIndentSize(((Number) indentEntry.getValue()).intValue()); - default -> throw new FormatterException("Invalid indent formatting option: " + indentKey); + default -> throw new FormatterException("invalid indent formatting option: " + indentKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java index a8a30f6d72db..6070710cb544 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/QueryFormattingOptions.java @@ -62,7 +62,7 @@ public QueryFormattingOptions build(Map configs) throws Formatte if (queryStatementKey.equals(ALIGN_MULTILINE_QUERIES)) { setAlignMultiLineQueries((Boolean) queryStatementEntry.getValue()); } else { - throw new FormatterException("Invalid query formatting option: " + queryStatementKey); + throw new FormatterException("invalid query formatting option: " + queryStatementKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java index 18cb5380d67b..fd7410b66557 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/SpacingFormattingOptions.java @@ -92,7 +92,7 @@ public SpacingFormattingOptions build(Map configs) throws Format case AROUND_RECORD_BRACES -> setAroundRecordBraces((Boolean) spacingEntry.getValue()); case ALIGN_CONSECUTIVE_DEFINITIONS -> setAlignConsecutiveDefinitions((Boolean) spacingEntry.getValue()); - default -> throw new FormatterException("Invalid spacing formatting option: " + spacingKey); + default -> throw new FormatterException("invalid spacing formatting option: " + spacingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java index ab41f548a10e..551b20b9102f 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingFormattingOptions.java @@ -30,14 +30,14 @@ public class WrappingFormattingOptions { private final int maxLineLength; private final boolean lineWrap; private final boolean simpleBlocksInOneLine; - private final boolean simpleMethodsInOneLine; + private final boolean simpleFunctionsInOneLine; private WrappingFormattingOptions(int maxLineLength, boolean lineWrap, boolean simpleBlocksInOneLine, - boolean simpleMethodsInOneLine) { + boolean simpleFunctionsInOneLine) { this.maxLineLength = maxLineLength; this.lineWrap = lineWrap; this.simpleBlocksInOneLine = simpleBlocksInOneLine; - this.simpleMethodsInOneLine = simpleMethodsInOneLine; + this.simpleFunctionsInOneLine = simpleFunctionsInOneLine; } public int maxLineLength() { @@ -48,8 +48,8 @@ public boolean isSimpleBlocksInOneLine() { return simpleBlocksInOneLine; } - public boolean isSimpleMethodsInOneLine() { - return simpleMethodsInOneLine; + public boolean isSimpleFunctionsInOneLine() { + return simpleFunctionsInOneLine; } public boolean lineWrap() { @@ -64,12 +64,12 @@ public static class WrappingFormattingOptionsBuilder { private static final String MAX_LINE_LENGTH = "maxLineLength"; private static final String SIMPLE_BLOCKS_IN_ONE_LINE = "simpleBlocksInOneLine"; - private static final String SIMPLE_METHODS_IN_ONE_LINE = "simpleMethodsInOneLine"; + private static final String SIMPLE_METHODS_IN_ONE_LINE = "simpleFunctionsInOneLine"; private static final String LINE_WRAP = "lineWrap"; private int maxLineLength = FormatterUtils.getDefaultInt(FormatSection.WRAPPING, MAX_LINE_LENGTH); private boolean simpleBlocksInOneLine = FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, SIMPLE_BLOCKS_IN_ONE_LINE); - private boolean simpleMethodsInOneLine = + private boolean simpleFunctionsInOneLine = FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, SIMPLE_METHODS_IN_ONE_LINE); private boolean lineWrap = FormatterUtils.getDefaultBoolean(FormatSection.WRAPPING, LINE_WRAP); @@ -88,14 +88,14 @@ public WrappingFormattingOptionsBuilder setLineWrap(boolean lineWrap) { return this; } - public WrappingFormattingOptionsBuilder setSimpleMethodsInOneLine(boolean simpleMethodsInOneLine) { - this.simpleMethodsInOneLine = simpleMethodsInOneLine; + public WrappingFormattingOptionsBuilder setSimpleFunctionsInOneLine(boolean simpleFunctionsInOneLine) { + this.simpleFunctionsInOneLine = simpleFunctionsInOneLine; return this; } public WrappingFormattingOptions build() { return new WrappingFormattingOptions(maxLineLength, lineWrap, simpleBlocksInOneLine, - simpleMethodsInOneLine); + simpleFunctionsInOneLine); } public WrappingFormattingOptions build(Map configs) throws FormatterException { @@ -107,8 +107,8 @@ public WrappingFormattingOptions build(Map configs) throws Forma setLineWrap(true); } case SIMPLE_BLOCKS_IN_ONE_LINE -> setSimpleBlocksInOneLine((Boolean) wrappingEntry.getValue()); - case SIMPLE_METHODS_IN_ONE_LINE -> setSimpleMethodsInOneLine((Boolean) wrappingEntry.getValue()); - default -> throw new FormatterException("Invalid wrapping formatting option: " + wrappingKey); + case SIMPLE_METHODS_IN_ONE_LINE -> setSimpleFunctionsInOneLine((Boolean) wrappingEntry.getValue()); + default -> throw new FormatterException("invalid wrapping formatting option: " + wrappingKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java index 9ec2f703f207..cebb27ce0531 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/WrappingMethod.java @@ -31,7 +31,7 @@ public static WrappingMethod fromString(String value) throws FormatterException try { return WrappingMethod.valueOf(value); } catch (IllegalArgumentException e) { - throw new FormatterException("Invalid wrapping method: " + value); + throw new FormatterException("invalid wrapping method: " + value); } } diff --git a/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json index cef3a8733c04..7542b6e61911 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json +++ b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json @@ -16,27 +16,27 @@ "pattern": "Invalid value for 'classBraceStyle'. Only 'NewLine' or 'EndOfLine' are allowed." } }, - "methodBraceStyle": { + "functionBraceStyle": { "type": "string", "pattern": "\\b(?:NewLine|EndOfLine)\\b", "message": { - "pattern": "Invalid value for 'methodBraceStyle'. Only 'NewLine' or 'EndOfLine' are allowed." + "pattern": "Invalid value for 'functionBraceStyle'. Only 'NewLine' or 'EndOfLine' are allowed." } } } }, - "methodCall": { + "functionCall": { "type": "object", "additionalProperties": false, "properties": { - "parametersWrap": { + "argumentsWrap": { "type": "string", "pattern": "\\b(?:Wrap|NoWrap|ChopDown)\\b", "message": { "pattern": "Invalid wrapping style. Only, 'Wrap', 'NoWrap', or 'ChopDown' is allowed." } }, - "alignMultilineParameters": { + "alignMultilineArguments": { "type": "boolean" }, "newLineAfterLeftParen": { @@ -47,7 +47,7 @@ } } }, - "methodDeclaration": { + "functionDeclaration": { "type": "object", "additionalProperties": false, "properties": { @@ -142,7 +142,7 @@ "simpleBlocksInOneLine": { "type": "boolean" }, - "simpleMethodsInOneLine": { + "simpleFunctionsInOneLine": { "type": "boolean" } } diff --git a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties index 021fc71018b6..7445b4293dac 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties +++ b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties @@ -14,17 +14,17 @@ # limitations under the License. # braces.classBraceStyle=EndOfLine -braces.methodBraceStyle=EndOfLine +braces.functionBraceStyle=EndOfLine -methodCall.parametersWrap=Wrap -methodCall.alignMultilineParameters=false -methodCall.newLineAfterLeftParen=false -methodCall.rightParenOnNewLine=false +functionCall.argumentsWrap=Wrap +functionCall.alignMultilineArguments=false +functionCall.newLineAfterLeftParen=false +functionCall.rightParenOnNewLine=false -methodDeclaration.parametersWrap=Wrap -methodDeclaration.alignMultilineParameters=false -methodDeclaration.newLineAfterLeftParen=false -methodDeclaration.rightParenOnNewLine=false +functionDeclaration.parametersWrap=Wrap +functionDeclaration.alignMultilineParameters=false +functionDeclaration.newLineAfterLeftParen=false +functionDeclaration.rightParenOnNewLine=false ifStatement.elseOnNewLine=false @@ -33,7 +33,7 @@ import.sortImports=true import.removeUnusedImports=false indent.indentSize=4 -indent.continuationIndentSize=2 +indent.continuationIndentSize=8 query.alignMultiLineQueries=false @@ -44,4 +44,4 @@ spacing.alignConsecutiveDefinitions=false wrapping.maxLineLength=120 wrapping.lineWrap=false wrapping.simpleBlocksInOneLine=false -wrapping.simpleMethodsInOneLine=false +wrapping.simpleFunctionsInOneLine=false diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java index a1b29b48c47f..03a625ba6c0c 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java @@ -64,20 +64,20 @@ public void cacheWithTargetDirectoryPresent() throws FormatterException { @Test(description = "Test invalid local formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to retrieve local formatting configuration file.*") + expectedExceptionsMessageRegExp = "failed to retrieve local formatting configuration file.*") public void invalidLocalFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("directory.toml").toString()); } @Test(description = "Test invalid remote cached formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to read cached formatting configuration file") + expectedExceptionsMessageRegExp = "failed to read cached formatting configuration file") public void invalidRemoteCachedFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(resDir.resolve(Path.of("invalidCached")), validRemoteUrl); } @Test(description = "Test invalid remote file protocol", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Configuration file remote url is not an HTTP url:.*") + expectedExceptionsMessageRegExp = "configuration file remote url is not an HTTP url:.*") public void invalidRemoteFileProtocol() throws FormatterException { Path invalidUrl = resDir.resolve("invalidUrl"); FormatterUtils.getFormattingConfigurations(invalidUrl, "ftp://example.com/Format.toml"); @@ -85,7 +85,7 @@ public void invalidRemoteFileProtocol() throws FormatterException { @Test(description = "Test invalid remote formatting configuration file url", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to retrieve remote file. HTTP response code:.*") + expectedExceptionsMessageRegExp = "failed to retrieve remote file. HTTP response code:.*") public void invalidRemoteFormatFileURLTest() throws FormatterException { Path invalidUrl = resDir.resolve("invalidUrl"); FormatterUtils.getFormattingConfigurations(invalidUrl, @@ -93,19 +93,19 @@ public void invalidRemoteFormatFileURLTest() throws FormatterException { } @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to retrieve formatting configuration file.*") + expectedExceptionsMessageRegExp = "failed to retrieve formatting configuration file.*") public void getInvalidFormatFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(invalidLocal, invalidLocal.resolve("t.toml").toString()); } @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to create format configuration cache directory") + expectedExceptionsMessageRegExp = "failed to create format configuration cache directory") public void failureToCreateFormatCacheFolderTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(resDir.resolve("invalidCacheTarget"), validRemoteUrl); } @Test(description = "Test invalid formatting configuration files", expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Failed to write format configuration cache file") + expectedExceptionsMessageRegExp = "failed to write format configuration cache file") public void failureToWriteCacheFileTest() throws FormatterException { FormatterUtils.getFormattingConfigurations(resDir.resolve("invalidCacheWrite"), validRemoteUrl); } diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java index 0cac424f0860..d8fdb9c0543d 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileValidatorTest.java @@ -40,7 +40,8 @@ public void testValidatorOnValidFile() throws FormatterException { } @Test(description = "Test validtor on invalid formatting configuration files", - expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid Format.toml file") + expectedExceptions = FormatterException.class, + expectedExceptionsMessageRegExp = "invalid formatting configuration file.*") public void testValidatorOnInvalidFile() throws FormatterException { Path invalid = resDir.resolve("invalid"); FormatterUtils.getFormattingConfigurations(invalid, invalid.resolve("Format.toml").toString()); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java index 47a4697bbd7c..933bdaef05ae 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java @@ -44,23 +44,23 @@ public class FormatOptionNegativeTest { @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid Brace Option: serviceBraceStyle") + expectedExceptionsMessageRegExp = "invalid Brace Option: serviceBraceStyle") public void testInvalidBracesOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("classBraceStyle", "NewLine"); - put("methodBraceStyle", "EndOfLine"); + put("functionBraceStyle", "EndOfLine"); put("serviceBraceStyle", "NewLine"); }}; BraceFormattingOptions.builder().build(configs); } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid function call formatting option: parametersInLine") + expectedExceptionsMessageRegExp = "invalid function call formatting option: parametersInLine") public void testInvalidFunctionCallOptions() throws FormatterException { Map configs = new HashMap<>() {{ - put("parametersWrap", "Wrap"); + put("argumentsWrap", "Wrap"); put("newLineAfterLeftParen", true); - put("alignMultilineParameters", false); + put("alignMultilineArguments", false); put("rightParenOnNewLine", true); put("parametersInLine", true); }}; @@ -68,7 +68,7 @@ public void testInvalidFunctionCallOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid function declaration formatting option: parametersInLine") + expectedExceptionsMessageRegExp = "invalid function declaration formatting option: parametersInLine") public void testInvalidFunctionDeclarationOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("parametersWrap", "Wrap"); @@ -81,7 +81,7 @@ public void testInvalidFunctionDeclarationOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid if statement formatting option: conditionOnSameLine") + expectedExceptionsMessageRegExp = "invalid if statement formatting option: conditionOnSameLine") public void testInvalidIfStatementOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("elseOnNewLine", true); @@ -91,7 +91,7 @@ public void testInvalidIfStatementOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid import formatting option: randomizeImports") + expectedExceptionsMessageRegExp = "invalid import formatting option: randomizeImports") public void testInvalidImportOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("groupImports", true); @@ -102,7 +102,7 @@ public void testInvalidImportOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid indent formatting option: indentFunctions") + expectedExceptionsMessageRegExp = "invalid indent formatting option: indentFunctions") public void testInvalidIndentOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("indentSize", -2); @@ -113,7 +113,7 @@ public void testInvalidIndentOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid query formatting option: queryOnSameLine") + expectedExceptionsMessageRegExp = "invalid query formatting option: queryOnSameLine") public void testInvalidQueryOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("alignMultiLineQueries", true); @@ -123,7 +123,7 @@ public void testInvalidQueryOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid spacing formatting option: spaceAroundTuple") + expectedExceptionsMessageRegExp = "invalid spacing formatting option: spaceAroundTuple") public void testInvalidSpacingOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("spaceAfterTypeCast", true); @@ -134,28 +134,28 @@ public void testInvalidSpacingOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "Invalid wrapping formatting option: wrapSimpleObjects") + expectedExceptionsMessageRegExp = "invalid wrapping formatting option: wrapSimpleObjects") public void testInvalidWrappingOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("maxLineLength", 120); put("simpleBlocksInOneLine", true); - put("simpleMethodsInOneLine", true); + put("simpleFunctionsInOneLine", true); put("wrapSimpleObjects", true); }}; WrappingFormattingOptions.builder().build(configs); } - @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid Brace style:.*") + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "invalid Brace style:.*") public void testInvalidBraceStyle() throws FormatterException { BraceStyle.fromString("NEWLINE"); } - @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid wrapping method:.*") + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "invalid wrapping method:.*") public void testInvalidWrappingMethod() throws FormatterException { WrappingMethod.fromString("WRAP"); } - @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "Invalid format section:.*") + @Test(expectedExceptions = FormatterException.class, expectedExceptionsMessageRegExp = "invalid format section:.*") public void testInvalidFormatSection() throws FormatterException { FormatSection.fromString("service"); } diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml index d9cd5dd4962c..4fa2b95cd975 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml" +configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/cca92fd7156172057a4957edd47f1e1bd349b2ae/format.toml" diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml index 3d403de184cb..78d3c109de72 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml @@ -5,18 +5,18 @@ continuationIndentSize = true [wrapping] maxLineLength = 120 simpleBlocksInOneLine = "true" -simpleMethodsInOneLine = "true" +simpleFunctionsInOneLine = "true" [braces] classBraceStyle = "NEWLINE" -methodBraceStyle = "NEWLINE" +functionBraceStyle = "NEWLINE" -[methodDeclaration] +[functionDeclaration] parametersWrap = "CHOPDOWN" paramterExtend = true -[methodCall] -parametersWrap = "WRAP" +[functionCall] +argumentsWrap = "WRAP" [elseStatement] elseOnNewLine = false diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml index dc4e253c5d1f..b60765cbdc29 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml @@ -5,21 +5,21 @@ continuationIndentSize = 8 [wrapping] maxLineLength = 120 simpleBlocksInOneLine = true -simpleMethodsInOneLine = true +simpleFunctionsInOneLine = true [braces] classBraceStyle = "NewLine" -methodBraceStyle = "NewLine" +functionBraceStyle = "NewLine" -[methodDeclaration] +[functionDeclaration] parametersWrap = "ChopDown" alignMultilineParameters = true newLineAfterLeftParen = false rightParenOnNewLine = false -[methodCall] -parametersWrap = "Wrap" -alignMultilineParameters = false +[functionCall] +argumentsWrap = "Wrap" +alignMultilineArguments = false newLineAfterLeftParen = false rightParenOnNewLine = false From 9e6172d4871797ea4e1b3bf102443f882cc9cd78 Mon Sep 17 00:00:00 2001 From: poorna2152 Date: Wed, 3 Apr 2024 12:00:32 +0530 Subject: [PATCH 22/22] Update functionDefinition option name --- .../resources/formatting/project/Format.toml | 2 +- .../formatter/cli/FormatCmdTest.java | 31 ++++++------ .../assert/chopDown/main.bal | 0 .../assert/noWrap/main.bal | 0 .../assert/wrap/main.bal | 0 .../source/chopDown/Ballerina.toml | 0 .../source/chopDown/Format.toml | 2 +- .../source/chopDown/main.bal | 0 .../source/chopDownTemp/main.bal | 0 .../source/noWrap/Ballerina.toml | 0 .../source/noWrap/Format.toml | 2 +- .../source/noWrap/main.bal | 0 .../source/noWrapTemp/main.bal | 0 .../source/wrap/Ballerina.toml | 0 .../source/wrap/Format.toml | 2 +- .../source/wrap/main.bal | 0 .../source/wrapTemp/main.bal | 0 .../source/project/Format.toml | 2 +- .../core/FormattingTreeModifier.java | 6 +-- .../formatter/core/options/FormatSection.java | 2 +- .../core/options/FormattingOptions.java | 20 ++++---- ...java => FunctionDefFormattingOptions.java} | 50 +++++++++---------- .../main/resources/format-toml-schema.json | 2 +- .../src/main/resources/formatter.properties | 8 +-- .../FormatFileResolutionTest.java | 2 +- .../FormatOptionNegativeTest.java | 8 +-- .../remote/source/Ballerina.toml | 2 +- .../validator/invalid/Format.toml | 2 +- .../validator/valid/Format.toml | 2 +- 29 files changed, 72 insertions(+), 73 deletions(-) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/assert/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/assert/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/assert/wrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/chopDown/Ballerina.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/chopDown/Format.toml (80%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/chopDown/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/chopDownTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/noWrap/Ballerina.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/noWrap/Format.toml (72%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/noWrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/noWrapTemp/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/wrap/Ballerina.toml (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/wrap/Format.toml (86%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/wrap/main.bal (100%) rename misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/{functionDeclaration => functionDefinition}/source/wrapTemp/main.bal (100%) rename misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/{FunctionDeclFormattingOptions.java => FunctionDefFormattingOptions.java} (63%) diff --git a/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml index d68d4dc5017a..f34eb5049103 100644 --- a/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml +++ b/language-server/modules/langserver-core/src/test/resources/formatting/project/Format.toml @@ -6,7 +6,7 @@ maxLineLength = 80 simpleBlocksInOneLine = true simpleFunctionsInOneLine = true -[functionDeclaration] +[functionDefinition] alignMultilineParameters = true [ifStatement] diff --git a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java index f8a35b8ae876..0ef6e827d68d 100644 --- a/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java +++ b/misc/formatter/modules/formatter-cli/src/test/java/org/ballerinalang/formatter/cli/FormatCmdTest.java @@ -103,40 +103,39 @@ public void formatCLIOnBallerinaProjectWithConfigurations(String testCase, List< @DataProvider(name = "provideConfigurationProjects") private Object[][] provideConfigurationProjects() { + Path basePath = RES_DIR.resolve(Path.of("configurations", "options")); return new Object[][]{ {"brace", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "brace", "source", "project")) + basePath.resolve(Path.of("brace", "source", "project")) )}, {"functionCall", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "chopDown")), - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "noWrap")), - RES_DIR.resolve(Path.of("configurations", "options", "functionCall", "source", "wrap")) + basePath.resolve(Path.of("functionCall", "source", "chopDown")), + basePath.resolve(Path.of("functionCall", "source", "noWrap")), + basePath.resolve(Path.of("functionCall", "source", "wrap")) )}, - {"functionDeclaration", List.of( - RES_DIR.resolve( - Path.of("configurations", "options", "functionDeclaration", "source", "chopDown")), - RES_DIR.resolve( - Path.of("configurations", "options", "functionDeclaration", "source", "noWrap")), - RES_DIR.resolve(Path.of("configurations", "options", "functionDeclaration", "source", "wrap")) + {"functionDefinition", List.of( + basePath.resolve(Path.of("functionDefinition", "source", "chopDown")), + basePath.resolve(Path.of("functionDefinition", "source", "noWrap")), + basePath.resolve(Path.of("functionDefinition", "source", "wrap")) )}, {"ifStatement", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "ifStatement", "source", "ifelse")) + basePath.resolve(Path.of("ifStatement", "source", "ifelse")) )}, {"imports", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "imports", "source", "project")) + basePath.resolve(Path.of("imports", "source", "project")) )}, {"indent", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "indent", "source", "project")) + basePath.resolve(Path.of("indent", "source", "project")) )}, {"query", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "query", "source", "project")) + basePath.resolve(Path.of("query", "source", "project")) )} , {"spacing", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "spacing", "source", "project")) + basePath.resolve(Path.of("spacing", "source", "project")) )}, {"wrapping", List.of( - RES_DIR.resolve(Path.of("configurations", "options", "wrapping", "source", "project")) + basePath.resolve(Path.of("wrapping", "source", "project")) )} }; } diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/assert/wrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/assert/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/Format.toml similarity index 80% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/Format.toml index 75c3ddbfddb7..89109c454b0a 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/Format.toml @@ -1,4 +1,4 @@ -[functionDeclaration] +[functionDefinition] parametersWrap = "ChopDown" alignMultilineParameters = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDown/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDown/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDownTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDownTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/chopDownTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/chopDownTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/Format.toml similarity index 72% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/Format.toml index f0fce7dc7d10..c7b0a4ca7559 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/Format.toml @@ -1,4 +1,4 @@ -[functionDeclaration] +[functionDefinition] parametersWrap = "NoWrap" [wrapping] diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/noWrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/noWrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/Ballerina.toml similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Ballerina.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/Ballerina.toml diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/Format.toml similarity index 86% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/Format.toml index 94978d78125f..eda71c706a8d 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/Format.toml @@ -1,4 +1,4 @@ -[functionDeclaration] +[functionDefinition] parametersWrap = "Wrap" alignMultilineParameters = true newLineAfterLeftParen = true diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrap/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrap/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrapTemp/main.bal b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrapTemp/main.bal similarity index 100% rename from misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDeclaration/source/wrapTemp/main.bal rename to misc/formatter/modules/formatter-cli/src/test/resources/configurations/options/functionDefinition/source/wrapTemp/main.bal diff --git a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml index f53a8a07cb6b..7435aa1545ce 100644 --- a/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml +++ b/misc/formatter/modules/formatter-cli/src/test/resources/configurations/projectWithModule/source/project/Format.toml @@ -5,7 +5,7 @@ continuationIndentSize = 4 maxLineLength = 80 -[functionDeclaration] +[functionDefinition] alignMultilineParameters = true newLineAfterLeftParen = true diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java index 65cbae3545c9..70b94cd7d3f9 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/FormattingTreeModifier.java @@ -252,7 +252,7 @@ import org.ballerinalang.formatter.core.options.BraceStyle; import org.ballerinalang.formatter.core.options.FormattingOptions; import org.ballerinalang.formatter.core.options.FunctionCallFormattingOptions; -import org.ballerinalang.formatter.core.options.FunctionDeclFormattingOptions; +import org.ballerinalang.formatter.core.options.FunctionDefFormattingOptions; import org.ballerinalang.formatter.core.options.WrappingMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -374,7 +374,7 @@ public ResourcePathParameterNode transform(ResourcePathParameterNode resourcePat @Override public FunctionSignatureNode transform(FunctionSignatureNode functionSignatureNode) { int parenTrailingNL = 0; - FunctionDeclFormattingOptions funcOptions = options.functionDeclFormattingOptions(); + FunctionDefFormattingOptions funcOptions = options.functionDefFormattingOptions(); if (hasNonWSMinutiae(functionSignatureNode.openParenToken().trailingMinutiae()) || funcOptions.newLineAfterLeftParen()) { parenTrailingNL++; @@ -4269,7 +4269,7 @@ private boolean shouldWrapLine(Node node, Node parent) { case REQUIRED_PARAM: case REST_PARAM: case RETURN_TYPE_DESCRIPTOR: - if (options.functionDeclFormattingOptions().parametersWrap() == WrappingMethod.NoWrap) { + if (options.functionDefFormattingOptions().parametersWrap() == WrappingMethod.NoWrap) { return false; } return true; diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java index 0a812485641f..4a6bedd7b776 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormatSection.java @@ -25,7 +25,7 @@ public enum FormatSection { BRACES("braces"), FUNCTION_CALL("functionCall"), - FUNCTION_DECLARATION("functionDeclaration"), + FUNCTION_DEFINITION("functionDefinition"), IF_STATEMENT("ifStatement"), IMPORT("import"), INDENT("indent"), diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java index 5626f20fc18f..ccf9191dd8e7 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FormattingOptions.java @@ -34,7 +34,7 @@ public class FormattingOptions { private final IndentFormattingOptions indentFormattingOptions; private final WrappingFormattingOptions wrappingFormattingOptions; private final BraceFormattingOptions braceFormattingOptions; - private final FunctionDeclFormattingOptions functionDeclFormattingOptions; + private final FunctionDefFormattingOptions functionDefFormattingOptions; private final FunctionCallFormattingOptions functionCallFormattingOptions; private final IfStatementFormattingOptions ifStatementFormattingOptions; private final SpacingFormattingOptions spacingFormattingOptions; @@ -45,7 +45,7 @@ public class FormattingOptions { private FormattingOptions(IndentFormattingOptions indentFormattingOptions, WrappingFormattingOptions wrappingFormattingOptions, BraceFormattingOptions braceFormattingOptions, - FunctionDeclFormattingOptions functionDeclFormattingOptions, + FunctionDefFormattingOptions functionDefFormattingOptions, FunctionCallFormattingOptions functionCallFormattingOptions, IfStatementFormattingOptions ifStatementFormattingOptions, SpacingFormattingOptions spacingFormattingOptions, @@ -55,7 +55,7 @@ private FormattingOptions(IndentFormattingOptions indentFormattingOptions, this.indentFormattingOptions = indentFormattingOptions; this.wrappingFormattingOptions = wrappingFormattingOptions; this.braceFormattingOptions = braceFormattingOptions; - this.functionDeclFormattingOptions = functionDeclFormattingOptions; + this.functionDefFormattingOptions = functionDefFormattingOptions; this.functionCallFormattingOptions = functionCallFormattingOptions; this.ifStatementFormattingOptions = ifStatementFormattingOptions; this.spacingFormattingOptions = spacingFormattingOptions; @@ -84,8 +84,8 @@ public BraceFormattingOptions braceFormattingOptions() { return braceFormattingOptions; } - public FunctionDeclFormattingOptions functionDeclFormattingOptions() { - return functionDeclFormattingOptions; + public FunctionDefFormattingOptions functionDefFormattingOptions() { + return functionDefFormattingOptions; } public FunctionCallFormattingOptions functionCallFormattingOptions() { @@ -122,8 +122,8 @@ public static class FormattingOptionsBuilder { private IndentFormattingOptions indentFormattingOptions = IndentFormattingOptions.builder().build(); private WrappingFormattingOptions wrappingFormattingOptions = WrappingFormattingOptions.builder().build(); private BraceFormattingOptions braceFormattingOptions = BraceFormattingOptions.builder().build(); - private FunctionDeclFormattingOptions functionDeclFormattingOptions = - FunctionDeclFormattingOptions.builder().build(); + private FunctionDefFormattingOptions functionDefFormattingOptions = + FunctionDefFormattingOptions.builder().build(); private FunctionCallFormattingOptions functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(); private IfStatementFormattingOptions ifStatementFormattingOptions = @@ -175,7 +175,7 @@ public FormattingOptionsBuilder setWrappingFormattingOptions( public FormattingOptions build() { return new FormattingOptions(indentFormattingOptions, wrappingFormattingOptions, braceFormattingOptions, - functionDeclFormattingOptions, functionCallFormattingOptions, ifStatementFormattingOptions, + functionDefFormattingOptions, functionCallFormattingOptions, ifStatementFormattingOptions, spacingFormattingOptions, forceFormattingOptions, importFormattingOptions, queryFormattingOptions); } @@ -197,8 +197,8 @@ public FormattingOptions build(Path root, Object formatSection) throws Formatter case INDENT -> indentFormattingOptions = IndentFormattingOptions.builder().build(configs); case WRAPPING -> wrappingFormattingOptions = WrappingFormattingOptions.builder().build(configs); case BRACES -> braceFormattingOptions = BraceFormattingOptions.builder().build(configs); - case FUNCTION_DECLARATION -> - functionDeclFormattingOptions = FunctionDeclFormattingOptions.builder().build(configs); + case FUNCTION_DEFINITION -> + functionDefFormattingOptions = FunctionDefFormattingOptions.builder().build(configs); case FUNCTION_CALL -> functionCallFormattingOptions = FunctionCallFormattingOptions.builder().build(configs); case IF_STATEMENT -> diff --git a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDefFormattingOptions.java similarity index 63% rename from misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java rename to misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDefFormattingOptions.java index 29aaaca0fffe..f6d8a72c816a 100644 --- a/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDeclFormattingOptions.java +++ b/misc/formatter/modules/formatter-core/src/main/java/org/ballerinalang/formatter/core/options/FunctionDefFormattingOptions.java @@ -27,15 +27,15 @@ * * @since 2201.9.0 */ -public class FunctionDeclFormattingOptions { +public class FunctionDefFormattingOptions { private final WrappingMethod parametersWrap; private final boolean alignMultilineParameters; private final boolean newLineAfterLeftParen; private final boolean rightParenOnNewLine; - private FunctionDeclFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, - boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { + private FunctionDefFormattingOptions(WrappingMethod parametersWrap, boolean alignMultilineParameters, + boolean newLineAfterLeftParen, boolean rightParenOnNewLine) { this.parametersWrap = parametersWrap; this.alignMultilineParameters = alignMultilineParameters; this.newLineAfterLeftParen = newLineAfterLeftParen; @@ -58,64 +58,64 @@ public boolean rightParenOnNewLine() { return rightParenOnNewLine; } - public static FunctionDeclFormattingOptionsBuilder builder() { - return new FunctionDeclFormattingOptions.FunctionDeclFormattingOptionsBuilder(); + public static FunctionDefFormattingOptionsBuilder builder() { + return new FunctionDefFormattingOptionsBuilder(); } - public static class FunctionDeclFormattingOptionsBuilder { + public static class FunctionDefFormattingOptionsBuilder { private static final String PARAMETERS_WRAP = "parametersWrap"; private static final String ALIGN_MULTILINE_PARAMETERS = "alignMultilineParameters"; private static final String NEWLINE_AFTER_LEFT_PAREN = "newLineAfterLeftParen"; private static final String RIGHT_PAREN_ON_NEWLINE = "rightParenOnNewLine"; private WrappingMethod parametersWrap = - WrappingMethod.valueOf(getDefaultString(FormatSection.FUNCTION_DECLARATION, PARAMETERS_WRAP)); + WrappingMethod.valueOf(getDefaultString(FormatSection.FUNCTION_DEFINITION, PARAMETERS_WRAP)); private boolean alignMultilineParameters = - getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, ALIGN_MULTILINE_PARAMETERS); + getDefaultBoolean(FormatSection.FUNCTION_DEFINITION, ALIGN_MULTILINE_PARAMETERS); private boolean newLineAfterLeftParen = - getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, NEWLINE_AFTER_LEFT_PAREN); + getDefaultBoolean(FormatSection.FUNCTION_DEFINITION, NEWLINE_AFTER_LEFT_PAREN); private boolean rightParenOnNewLine = - getDefaultBoolean(FormatSection.FUNCTION_DECLARATION, RIGHT_PAREN_ON_NEWLINE); + getDefaultBoolean(FormatSection.FUNCTION_DEFINITION, RIGHT_PAREN_ON_NEWLINE); - public FunctionDeclFormattingOptionsBuilder setParametersWrap(WrappingMethod parametersWrap) { + public FunctionDefFormattingOptionsBuilder setParametersWrap(WrappingMethod parametersWrap) { this.parametersWrap = parametersWrap; return this; } - public FunctionDeclFormattingOptionsBuilder setAlignMultilineParameters(boolean alignMultilineParameters) { + public FunctionDefFormattingOptionsBuilder setAlignMultilineParameters(boolean alignMultilineParameters) { this.alignMultilineParameters = alignMultilineParameters; return this; } - public FunctionDeclFormattingOptionsBuilder setNewLineAfterLeftParen(boolean newLineAfterLeftParen) { + public FunctionDefFormattingOptionsBuilder setNewLineAfterLeftParen(boolean newLineAfterLeftParen) { this.newLineAfterLeftParen = newLineAfterLeftParen; return this; } - public FunctionDeclFormattingOptionsBuilder setRightParenOnNewLine(boolean rightParenOnNewLine) { + public FunctionDefFormattingOptionsBuilder setRightParenOnNewLine(boolean rightParenOnNewLine) { this.rightParenOnNewLine = rightParenOnNewLine; return this; } - public FunctionDeclFormattingOptions build() { - return new FunctionDeclFormattingOptions(parametersWrap, alignMultilineParameters, + public FunctionDefFormattingOptions build() { + return new FunctionDefFormattingOptions(parametersWrap, alignMultilineParameters, newLineAfterLeftParen, rightParenOnNewLine); } - public FunctionDeclFormattingOptions build(Map configs) throws FormatterException { - for (Map.Entry functionDeclarationEntry : configs.entrySet()) { - String functionDeclarationKey = functionDeclarationEntry.getKey(); - switch (functionDeclarationKey) { + public FunctionDefFormattingOptions build(Map configs) throws FormatterException { + for (Map.Entry functionDefinitionEntry : configs.entrySet()) { + String functionDefinitionKey = functionDefinitionEntry.getKey(); + switch (functionDefinitionKey) { case PARAMETERS_WRAP -> - setParametersWrap(WrappingMethod.fromString((String) functionDeclarationEntry.getValue())); + setParametersWrap(WrappingMethod.fromString((String) functionDefinitionEntry.getValue())); case ALIGN_MULTILINE_PARAMETERS -> - setAlignMultilineParameters((Boolean) functionDeclarationEntry.getValue()); + setAlignMultilineParameters((Boolean) functionDefinitionEntry.getValue()); case NEWLINE_AFTER_LEFT_PAREN -> - setNewLineAfterLeftParen((Boolean) functionDeclarationEntry.getValue()); + setNewLineAfterLeftParen((Boolean) functionDefinitionEntry.getValue()); case RIGHT_PAREN_ON_NEWLINE -> - setRightParenOnNewLine((Boolean) functionDeclarationEntry.getValue()); + setRightParenOnNewLine((Boolean) functionDefinitionEntry.getValue()); default -> throw new FormatterException( - "invalid function declaration formatting option: " + functionDeclarationKey); + "invalid function definition formatting option: " + functionDefinitionKey); } } return build(); diff --git a/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json index 7542b6e61911..58ac484cc42a 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json +++ b/misc/formatter/modules/formatter-core/src/main/resources/format-toml-schema.json @@ -47,7 +47,7 @@ } } }, - "functionDeclaration": { + "functionDefinition": { "type": "object", "additionalProperties": false, "properties": { diff --git a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties index 7445b4293dac..5032c3635571 100644 --- a/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties +++ b/misc/formatter/modules/formatter-core/src/main/resources/formatter.properties @@ -21,10 +21,10 @@ functionCall.alignMultilineArguments=false functionCall.newLineAfterLeftParen=false functionCall.rightParenOnNewLine=false -functionDeclaration.parametersWrap=Wrap -functionDeclaration.alignMultilineParameters=false -functionDeclaration.newLineAfterLeftParen=false -functionDeclaration.rightParenOnNewLine=false +functionDefinition.parametersWrap=Wrap +functionDefinition.alignMultilineParameters=false +functionDefinition.newLineAfterLeftParen=false +functionDefinition.rightParenOnNewLine=false ifStatement.elseOnNewLine=false diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java index 03a625ba6c0c..ce3fe382a2d6 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatFileResolutionTest.java @@ -36,7 +36,7 @@ public class FormatFileResolutionTest { private final Path resDir = Path.of("src", "test", "resources", "configurations", "resolution"); private final String validRemoteUrl = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw" + - "/db0909d0b66f97cd0035f19bcb7cde9a239f5d54/format.toml"; + "/8dc3204aec3f158105a811a6a67488bef45ff742/format.toml"; private final Path validRemote = resDir.resolve("validRemote"); private final Path withTarget = resDir.resolve("withTarget"); private final Path invalidLocal = resDir.resolve("invalidLocal"); diff --git a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java index 933bdaef05ae..4736fccfa1ad 100644 --- a/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java +++ b/misc/formatter/modules/formatter-core/src/test/java/org/ballerinalang/formatter/core/configurations/FormatOptionNegativeTest.java @@ -23,7 +23,7 @@ import org.ballerinalang.formatter.core.options.BraceStyle; import org.ballerinalang.formatter.core.options.FormatSection; import org.ballerinalang.formatter.core.options.FunctionCallFormattingOptions; -import org.ballerinalang.formatter.core.options.FunctionDeclFormattingOptions; +import org.ballerinalang.formatter.core.options.FunctionDefFormattingOptions; import org.ballerinalang.formatter.core.options.IfStatementFormattingOptions; import org.ballerinalang.formatter.core.options.ImportFormattingOptions; import org.ballerinalang.formatter.core.options.IndentFormattingOptions; @@ -68,8 +68,8 @@ public void testInvalidFunctionCallOptions() throws FormatterException { } @Test(expectedExceptions = FormatterException.class, - expectedExceptionsMessageRegExp = "invalid function declaration formatting option: parametersInLine") - public void testInvalidFunctionDeclarationOptions() throws FormatterException { + expectedExceptionsMessageRegExp = "invalid function definition formatting option: parametersInLine") + public void testInvalidFunctionDefinitionOptions() throws FormatterException { Map configs = new HashMap<>() {{ put("parametersWrap", "Wrap"); put("newLineAfterLeftParen", true); @@ -77,7 +77,7 @@ public void testInvalidFunctionDeclarationOptions() throws FormatterException { put("rightParenOnNewLine", true); put("parametersInLine", true); }}; - FunctionDeclFormattingOptions.builder().build(configs); + FunctionDefFormattingOptions.builder().build(configs); } @Test(expectedExceptions = FormatterException.class, diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml index 4fa2b95cd975..176784afabdd 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/remote/source/Ballerina.toml @@ -1,2 +1,2 @@ [format] -configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/cca92fd7156172057a4957edd47f1e1bd349b2ae/format.toml" +configPath = "https://gist.githubusercontent.com/ballerina-bot/ae54cc7303e9d474d730d732c1594c61/raw/8dc3204aec3f158105a811a6a67488bef45ff742/format.toml" diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml index 78d3c109de72..786888481362 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/invalid/Format.toml @@ -11,7 +11,7 @@ simpleFunctionsInOneLine = "true" classBraceStyle = "NEWLINE" functionBraceStyle = "NEWLINE" -[functionDeclaration] +[functionDefinition] parametersWrap = "CHOPDOWN" paramterExtend = true diff --git a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml index b60765cbdc29..285f78a79845 100644 --- a/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml +++ b/misc/formatter/modules/formatter-core/src/test/resources/configurations/validator/valid/Format.toml @@ -11,7 +11,7 @@ simpleFunctionsInOneLine = true classBraceStyle = "NewLine" functionBraceStyle = "NewLine" -[functionDeclaration] +[functionDefinition] parametersWrap = "ChopDown" alignMultilineParameters = true newLineAfterLeftParen = false