Skip to content

Commit

Permalink
Merge pull request #42129 from poorna2152/formatter
Browse files Browse the repository at this point in the history
Add support to provide formatting configurations through a configuration file
  • Loading branch information
MaryamZi authored Apr 4, 2024
2 parents b04020c + 9e6172d commit a7cb9bf
Show file tree
Hide file tree
Showing 158 changed files with 3,470 additions and 324 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,15 @@
"type": "boolean"
}
}
},
"format": {
"type": "object",
"additionalProperties": true,
"properties": {
"configPath": {
"type": "string"
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.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;
import org.ballerinalang.langserver.common.utils.PathUtil;
Expand Down Expand Up @@ -112,6 +116,8 @@
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.ballerinalang.formatter.core.FormatterUtils.buildFormattingOptions;

/**
* Text document service implementation for ballerina.
*/
Expand Down Expand Up @@ -439,7 +445,16 @@ public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormatting
if (syntaxTree.isEmpty()) {
return Collections.emptyList();
}
String formattedSource = Formatter.format(syntaxTree.get()).toSourceCode();
String formattedSource;
if (FormatterUtils.isBuildProject(context.currentModule())) {
Path rootPath = context.workspace().projectRoot(context.filePath());
BuildProject project = BuildProject.load(rootPath, BuildOptions.builder().build());
FormattingOptions options = buildFormattingOptions(project);
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[format]
configPath = "Format.toml"
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[indent]
indentSize = 2

[wrapping]
maxLineLength = 80
simpleBlocksInOneLine = true
simpleFunctionsInOneLine = true

[functionDefinition]
alignMultilineParameters = true

[ifStatement]
elseOnNewLine = true
Original file line number Diff line number Diff line change
@@ -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}`; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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}`; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@
"detail": "Table Array",
"sortText": "C",
"insertText": "[[dependency]]"
},
{
"label": "format",
"kind": "Snippet",
"detail": "Table",
"sortText": "C",
"insertText": "[format]"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,13 @@
"detail": "Boolean",
"sortText": "A",
"insertText": "template=${1:false}"
},
{
"label": "format",
"kind": "Snippet",
"detail": "Table",
"sortText": "C",
"insertText": "[format]"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,13 @@
"detail": "Boolean",
"sortText": "A",
"insertText": "template=${1:false}"
},
{
"label": "format",
"kind": "Snippet",
"detail": "Table",
"sortText": "C",
"insertText": "[format]"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.FormatterUtils;
import org.ballerinalang.formatter.core.options.FormattingOptions;

import java.io.File;
import java.io.FileOutputStream;
Expand Down Expand Up @@ -122,9 +124,11 @@ static void execute(List<String> argList, boolean helpFlag, String moduleName, S
Path projectPath = sourceRootPath.resolve(argList.get(0));

BuildProject project;
FormattingOptions options;

try {
project = BuildProject.load(projectPath, constructBuildOptions());
options = FormatterUtils.buildFormattingOptions(project);
} catch (ProjectException e) {
throw LauncherUtils.createLauncherException(e.getMessage());
}
Expand All @@ -141,7 +145,7 @@ static void execute(List<String> 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);
}
Expand Down Expand Up @@ -178,7 +182,7 @@ static void execute(List<String> 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);
}
Expand All @@ -188,9 +192,10 @@ static void execute(List<String> argList, boolean helpFlag, String moduleName, S
}
} else {
BuildProject project;

FormattingOptions options;
try {
project = BuildProject.load(sourceRootPath, constructBuildOptions());
options = FormatterUtils.buildFormattingOptions(project);
} catch (ProjectException e) {
throw LauncherUtils.createLauncherException(e.getMessage());
}
Expand All @@ -207,7 +212,7 @@ static void execute(List<String> 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);
}
Expand Down Expand Up @@ -244,16 +249,18 @@ static void execute(List<String> 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);
}
});
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());
}
}

Expand Down Expand Up @@ -293,12 +300,13 @@ private static void generateChangeReport(List<String> formattedFiles, boolean dr
}

private static void formatAndWrite(Path documentPath, Path sourceRootPath,
List<String> formattedFiles, boolean dryRun) throws IOException, FormatterException {
List<String> 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) {
Expand All @@ -309,13 +317,14 @@ private static void formatAndWrite(Path documentPath, Path sourceRootPath,
}
}

private static List<String> iterateAndFormat(List<Path> documentPaths, Path sourceRootPath, boolean dryRun)
private static List<String> iterateAndFormat(List<Path> documentPaths, Path sourceRootPath,
FormattingOptions options, boolean dryRun)
throws IOException, FormatterException {
List<String> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: ";

Expand Down
Loading

0 comments on commit a7cb9bf

Please sign in to comment.