Skip to content

Commit

Permalink
Merge pull request #480 from dulajdilshan/revamp-delete-api
Browse files Browse the repository at this point in the history
Add LS API support for component deletion
  • Loading branch information
LakshanWeerasinghe authored Nov 8, 2024
2 parents faed508 + abe5764 commit 1a27c22
Show file tree
Hide file tree
Showing 20 changed files with 674 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.ballerina.compiler.syntax.tree.BlockStatementNode;
import io.ballerina.compiler.syntax.tree.ImportDeclarationNode;
import io.ballerina.compiler.syntax.tree.ModulePartNode;
Expand All @@ -33,6 +34,7 @@
import io.ballerina.tools.diagnostics.Diagnostic;
import io.ballerina.tools.diagnostics.DiagnosticInfo;
import io.ballerina.tools.diagnostics.DiagnosticSeverity;
import io.ballerina.tools.text.LinePosition;
import io.ballerina.tools.text.LineRange;
import io.ballerina.tools.text.TextDocument;
import io.ballerina.tools.text.TextDocumentChange;
Expand All @@ -52,23 +54,34 @@
*
* @since 1.4.0
*/
public class DeleteNodeGenerator {
public class DeleteNodeHandler {

private final Gson gson;
private static final Gson gson = new Gson();
private final FlowNode nodeToDelete;
private final Path filePath;

public DeleteNodeGenerator(JsonElement nodeToDelete, Path filePath) {
this.gson = new Gson();
public DeleteNodeHandler(JsonElement nodeToDelete, Path filePath) {
this.nodeToDelete = new Gson().fromJson(nodeToDelete, FlowNode.class);
this.filePath = filePath;
}

@Deprecated
public JsonElement getTextEditsToDeletedNode(Document document, Project project) {
LineRange lineRange = nodeToDelete.codedata().lineRange();
return getTextEditsToDeletedNode(lineRange, filePath, document, project);
}

public static JsonElement getTextEditsToDeletedNode(JsonElement node, Path filePath,
Document document, Project project) {
return getTextEditsToDeletedNode(getNodeLineRange(node), filePath, document, project);
}

private static JsonElement getTextEditsToDeletedNode(LineRange lineRange, Path filePath,
Document document, Project project) {
TextDocument textDocument = document.textDocument();
int startTextPosition = textDocument.textPositionFrom(lineRange.startLine());
int endTextPosition = textDocument.textPositionFrom(lineRange.endLine());

io.ballerina.tools.text.TextEdit te = io.ballerina.tools.text.TextEdit.from(TextRange.from(startTextPosition,
endTextPosition - startTextPosition), "");
TextDocument apply = textDocument
Expand Down Expand Up @@ -103,7 +116,22 @@ public JsonElement getTextEditsToDeletedNode(Document document, Project project)
return gson.toJsonTree(textEditsMap);
}

private ImportDeclarationNode getUnusedImport(LineRange diagnosticLocation,
private static LineRange getNodeLineRange(JsonElement node) {
FlowNode nodeToDelete = gson.fromJson(node, FlowNode.class);
if (nodeToDelete.codedata() != null) {
return nodeToDelete.codedata().lineRange();
}

// Assume that the node has the following attributes: startLine, startColumn, endLine, endColumn
JsonObject jsonObject = node.getAsJsonObject();
LinePosition startLinePosition = LinePosition.from(
jsonObject.get("startLine").getAsInt(), jsonObject.get("startColumn").getAsInt());
LinePosition endLinePosition = LinePosition.from(
jsonObject.get("endLine").getAsInt(), jsonObject.get("endColumn").getAsInt());
return LineRange.from(jsonObject.get("filePath").getAsString(), startLinePosition, endLinePosition);
}

private static ImportDeclarationNode getUnusedImport(LineRange diagnosticLocation,
NodeList<ImportDeclarationNode> imports) {
for (ImportDeclarationNode importNode : imports) {
if (PositionUtil.isWithinLineRange(diagnosticLocation, importNode.lineRange())) {
Expand All @@ -113,7 +141,7 @@ private ImportDeclarationNode getUnusedImport(LineRange diagnosticLocation,
throw new IllegalStateException("There should be an import node");
}

private LineRange checkElseToDelete(Document document, int nodeStart, int nodeEnd) {
private static LineRange checkElseToDelete(Document document, int nodeStart, int nodeEnd) {
ModulePartNode modulePartNode = document.syntaxTree().rootNode();
NonTerminalNode node = modulePartNode.findNode(TextRange.from(nodeStart, nodeEnd - nodeStart)).parent();
if (node != null && node.kind() == SyntaxKind.BLOCK_STATEMENT) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import io.ballerina.flowmodelgenerator.core.AvailableNodesGenerator;
import io.ballerina.flowmodelgenerator.core.ConnectorGenerator;
import io.ballerina.flowmodelgenerator.core.CopilotContextGenerator;
import io.ballerina.flowmodelgenerator.core.DeleteNodeGenerator;
import io.ballerina.flowmodelgenerator.core.DeleteNodeHandler;
import io.ballerina.flowmodelgenerator.core.ErrorHandlerGenerator;
import io.ballerina.flowmodelgenerator.core.FunctionGenerator;
import io.ballerina.flowmodelgenerator.core.ModelGenerator;
Expand All @@ -34,6 +34,7 @@
import io.ballerina.flowmodelgenerator.core.SourceGenerator;
import io.ballerina.flowmodelgenerator.core.SuggestedComponentService;
import io.ballerina.flowmodelgenerator.core.SuggestedModelGenerator;
import io.ballerina.flowmodelgenerator.extension.request.ComponentDeleteRequest;
import io.ballerina.flowmodelgenerator.extension.request.CopilotContextRequest;
import io.ballerina.flowmodelgenerator.extension.request.FilePathRequest;
import io.ballerina.flowmodelgenerator.extension.request.FlowModelAvailableNodesRequest;
Expand All @@ -46,6 +47,7 @@
import io.ballerina.flowmodelgenerator.extension.request.FlowNodeDeleteRequest;
import io.ballerina.flowmodelgenerator.extension.request.OpenAPIServiceGenerationRequest;
import io.ballerina.flowmodelgenerator.extension.request.SuggestedComponentRequest;
import io.ballerina.flowmodelgenerator.extension.response.ComponentDeleteResponse;
import io.ballerina.flowmodelgenerator.extension.response.CopilotContextResponse;
import io.ballerina.flowmodelgenerator.extension.response.FlowModelAvailableNodesResponse;
import io.ballerina.flowmodelgenerator.extension.response.FlowModelGeneratorResponse;
Expand Down Expand Up @@ -375,21 +377,23 @@ public CompletableFuture<CopilotContextResponse> getCopilotContext(CopilotContex
}

@JsonRequest
@Deprecated
// TODO: Need to remove this API and usages must be migrated to `deleteComponent(ComponentDeleteRequest request)`
public CompletableFuture<FlowNodeDeleteResponse> deleteFlowNode(FlowNodeDeleteRequest request) {

return CompletableFuture.supplyAsync(() -> {
FlowNodeDeleteResponse response = new FlowNodeDeleteResponse();
try {
Path filePath = Path.of(request.filePath());
DeleteNodeGenerator deleteNodeGenerator = new DeleteNodeGenerator(request.flowNode(), filePath);
DeleteNodeHandler deleteNodeHandler = new DeleteNodeHandler(request.flowNode(), filePath);
Project project = this.workspaceManager.loadProject(filePath);
Optional<SemanticModel> semanticModel = this.workspaceManager.semanticModel(filePath);
Optional<Document> document = this.workspaceManager.document(filePath);
if (semanticModel.isEmpty() || document.isEmpty()) {
return response;
}
response.setTextEdits(
deleteNodeGenerator.getTextEditsToDeletedNode(document.get(), project));
deleteNodeHandler.getTextEditsToDeletedNode(document.get(), project));
} catch (Throwable e) {
//TODO: Handle errors generated by the flow model generator service.
response.setError(e);
Expand All @@ -398,6 +402,30 @@ public CompletableFuture<FlowNodeDeleteResponse> deleteFlowNode(FlowNodeDeleteRe
});
}

@JsonRequest
public CompletableFuture<ComponentDeleteResponse> deleteComponent(ComponentDeleteRequest request) {
return CompletableFuture.supplyAsync(() -> {
ComponentDeleteResponse response = new ComponentDeleteResponse();
try {
Path filePath = Path.of(request.filePath());
Project project = this.workspaceManager.loadProject(filePath);
Optional<SemanticModel> semanticModel = this.workspaceManager.semanticModel(filePath);
Optional<Document> document = this.workspaceManager.document(filePath);
if (semanticModel.isEmpty() || document.isEmpty()) {
return response;
}
response.setTextEdits(DeleteNodeHandler.getTextEditsToDeletedNode(
request.component(), filePath, document.get(), project
));
} catch (Throwable e) {
//TODO: Handle errors generated by the flow model generator service.
response.setError(e);
}

return response;
});
}

@JsonRequest
public CompletableFuture<OpenApiServiceGenerationResponse> generateServiceFromOpenApiContract(
OpenAPIServiceGenerationRequest request) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://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 io.ballerina.flowmodelgenerator.extension.request;

import com.google.gson.JsonElement;

/**
* Represents a request to delete a component.
*
* @param filePath file path of the source file
* @param component component to delete
* @since 1.4.0
*/
public record ComponentDeleteRequest(String filePath, JsonElement component) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://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 io.ballerina.flowmodelgenerator.extension.response;

import com.google.gson.JsonElement;

/**
* Represents the response for the deleteComponent API.
*
* @since 1.4.0
*/
public class ComponentDeleteResponse extends AbstractFlowModelResponse {

private JsonElement textEdits;

public void setTextEdits(JsonElement textEdits) {
this.textEdits = textEdits;
}

public JsonElement textEdits() {
return textEdits;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://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 io.ballerina.flowmodelgenerator.extension;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import io.ballerina.flowmodelgenerator.extension.request.ComponentDeleteRequest;
import org.eclipse.lsp4j.TextEdit;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Tests for the flow model source generator service.
*
* @since 1.4.0
*/
public class DeleteComponentTest extends AbstractLSTest {

private static final Type textEditListType = new TypeToken<Map<String, List<TextEdit>>>() {
}.getType();

@Override
@Test(dataProvider = "data-provider")
public void test(Path config) throws IOException {
Path configJsonPath = configDir.resolve(config);
TestConfig testConfig = gson.fromJson(Files.newBufferedReader(configJsonPath), TestConfig.class);

String sourcePath = getSourcePath(testConfig.filePath());
ComponentDeleteRequest deleteRequest = new ComponentDeleteRequest(sourcePath, gson.toJsonTree(testConfig));

JsonObject deleteResponse = getResponse(deleteRequest).getAsJsonObject("textEdits");
Map<String, List<TextEdit>> actualTextEdits = gson.fromJson(deleteResponse, textEditListType);

assertTextEdits(actualTextEdits, testConfig, configJsonPath);
}

private void assertTextEdits(Map<String, List<TextEdit>> actualTextEdits,
TestConfig testConfig, Path configJsonPath) throws IOException {
boolean assertFailure = false;
Map<String, List<TextEdit>> newMap = new HashMap<>();
for (Map.Entry<String, List<TextEdit>> entry : actualTextEdits.entrySet()) {
Path fullPath = Paths.get(entry.getKey());
String relativePath = sourceDir.relativize(fullPath).toString();

List<TextEdit> textEdits = testConfig.output().get(relativePath.replace("\\", "/"));
if (textEdits == null) {
log.info("No text edits found for the file: " + relativePath);
assertFailure = true;
} else if (!assertArray("text edits", entry.getValue(), textEdits)) {
assertFailure = true;
}

newMap.put(relativePath, entry.getValue());
}

if (assertFailure) {
TestConfig updatedConfig =
new TestConfig(testConfig.description(), testConfig.filePath(), testConfig.startLine(),
testConfig.startColumn(), testConfig.endLine(), testConfig.endColumn(), newMap);
// updateConfig(configJsonPath, updatedConfig);
Assert.fail(String.format("Failed test: '%s' (%s)", testConfig.description(), configJsonPath));
}
}


@Override
protected String getResourceDir() {
return "delete_component";
}

@Override
protected Class<? extends AbstractLSTest> clazz() {
return DeleteComponentTest.class;
}

@Override
protected String getApiName() {
return "deleteComponent";
}

/**
* Represents the test configuration for the delete node test.
*
* @param description The description of the test.
* @param filePath The path to the source file that contains the nodes to be deleted.
* @param startLine The starting line number of the node to be deleted.
* @param startColumn The starting column position of the node to be deleted.
* @param endLine The ending line number of the node to be deleted.
* @param endColumn The ending column position of the node to be deleted.
* @param output The expected output.
*/
private record TestConfig(String description, String filePath,
int startLine, int startColumn, int endLine, int endColumn,
Map<String, List<TextEdit>> output) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ public void test(Path config) throws IOException {
JsonObject deleteResponse = getResponse(deleteRequest).getAsJsonObject("textEdits");
Map<String, List<TextEdit>> actualTextEdits = gson.fromJson(deleteResponse, textEditListType);

assertTextEdits(actualTextEdits, testConfig, configJsonPath);
}

@Override
protected String[] skipList() {
// TODO: Remove after fixing the log symbol issue
return new String[]{
"delete_node8.json"
};
}

private void assertTextEdits(Map<String, List<TextEdit>> actualTextEdits,
TestConfig testConfig, Path configJsonPath) {
boolean assertFailure = false;
Map<String, List<TextEdit>> newMap = new HashMap<>();
for (Map.Entry<String, List<TextEdit>> entry : actualTextEdits.entrySet()) {
Expand All @@ -106,14 +119,6 @@ public void test(Path config) throws IOException {
}
}

@Override
protected String[] skipList() {
// TODO: Remove after fixing the log symbol issue
return new String[]{
"delete_node8.json"
};
}

private Optional<FlowNode> findNodeToDelete(FlowNode node, LinePosition deleteNodeStart,
LinePosition deleteNodeEnd) {
LinePosition nodeStart = node.codedata().lineRange().startLine();
Expand Down
Loading

0 comments on commit 1a27c22

Please sign in to comment.