Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

LSP: Do not compute text edits in source actions on resolve call. #6990

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,43 @@
*/
package org.netbeans.modules.micronaut.db;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.awt.Dialog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.java.source.GeneratorUtilities;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.java.source.ModificationResult;
import org.netbeans.api.java.source.Task;
import org.netbeans.api.java.source.TreeUtilities;
import org.netbeans.api.java.source.WorkingCopy;
import org.netbeans.api.lsp.CodeAction;
import org.netbeans.api.lsp.LazyCodeAction;
import org.netbeans.api.lsp.Command;
import org.netbeans.api.lsp.Range;
import org.netbeans.api.lsp.TextDocumentEdit;
import org.netbeans.api.lsp.TextEdit;
Expand All @@ -56,25 +63,39 @@
import org.netbeans.modules.parsing.spi.ParseException;
import org.netbeans.spi.editor.codegen.CodeGenerator;
import org.netbeans.spi.lsp.CodeActionProvider;
import org.netbeans.spi.lsp.CommandProvider;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.URLMapper;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Union2;
import org.openide.util.lookup.ServiceProviders;
import org.openide.util.lookup.ServiceProvider;

/**
*
* @author Dusan Balek
*/
@ServiceProvider(service = CodeActionProvider.class)
public class MicronautDataEndpointGenerator implements CodeActionProvider {
@ServiceProviders({
@ServiceProvider(service = CodeActionProvider.class),
@ServiceProvider(service = CommandProvider.class)
})
public class MicronautDataEndpointGenerator implements CodeActionProvider, CommandProvider {

private static final String SOURCE = "source";
private static final String CONTROLLER_ANNOTATION_NAME = "io.micronaut.http.annotation.Controller";
private static final String GENERATE_DATA_ENDPOINT = "nbls.micronaut.generate.data.endpoint";
private static final String URI = "uri";
private static final String OFFSET = "offset";
private static final String REPOSITORIES = "repositories";
private static final String ENDPOINTS = "endpoints";

private final Gson gson = new Gson();

@Override
@NbBundle.Messages({
Expand Down Expand Up @@ -126,79 +147,107 @@ public List<CodeAction> getCodeActions(Document doc, Range range, Lookup context
}
});
if (!endpoints.isEmpty()) {
FileObject fo = cc.getFileObject();
List<ElementHandle<VariableElement>> repositoryHandles = repositories.stream().map(repository -> ElementHandle.create(repository)).collect(Collectors.toList());
return Collections.singletonList(new LazyCodeAction(Bundle.DN_GenerateDataEndpoint(), SOURCE, null, () -> {
try {
List<NotifyDescriptor.QuickPick.Item> items = endpoints.stream().map(endpoint -> new NotifyDescriptor.QuickPick.Item(endpoint, null)).collect(Collectors.toList());
NotifyDescriptor.QuickPick pick = new NotifyDescriptor.QuickPick(Bundle.DN_GenerateDataEndpoint(), Bundle.DN_SelectEndpoints(), items, true);
if (DialogDescriptor.OK_OPTION != DialogDisplayer.getDefault().notify(pick)) {
return null;
}
List<String> selectedIds = new ArrayList<>();
for (NotifyDescriptor.QuickPick.Item item : pick.getItems()) {
if (item.isSelected()) {
selectedIds.add(item.getLabel());
}
}
if (selectedIds.isEmpty()) {
return null;
}
JavaSource js = JavaSource.forFileObject(fo);
if (js == null) {
throw new IOException("Cannot get JavaSource for: " + fo.toURL().toString());
}
return modify2Edit(js, getTask(offset, repositoryHandles, selectedIds));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}));
Map<String, Object> data = new HashMap<>();
data.put(URI, cc.getFileObject().toURI().toString());
data.put(OFFSET, offset);
data.put(REPOSITORIES, repositories.stream().map(repository -> repository.getSimpleName().toString()).collect(Collectors.toList()));
data.put(ENDPOINTS, endpoints);
return Collections.singletonList(new CodeAction(Bundle.DN_GenerateDataEndpoint(), SOURCE, new Command(Bundle.DN_GenerateDataEndpoint(), "nbls.generate.code", Arrays.asList(GENERATE_DATA_ENDPOINT, data)), null));
}
} catch (IOException | ParseException ex) {
Exceptions.printStackTrace(ex);
}
return Collections.emptyList();
}

private static Task<WorkingCopy> getTask(int offset, List<ElementHandle<VariableElement>> repositoryHandles, List<String> endpointIds) {
@Override
public Set<String> getCommands() {
return Collections.singleton(GENERATE_DATA_ENDPOINT);
}

@Override
public CompletableFuture<Object> runCommand(String command, List<Object> arguments) {
if (arguments.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
JsonObject data = (JsonObject) arguments.get(0);
CompletableFuture<Object> future = new CompletableFuture<>();
RequestProcessor.getDefault().post(() -> {
try {
String uri = data.getAsJsonPrimitive(URI).getAsString();
FileObject fo = URLMapper.findFileObject(java.net.URI.create(uri).toURL());
JavaSource js = fo != null ? JavaSource.forFileObject(fo) : null;
if (js == null) {
throw new IOException("Cannot get JavaSource for: " + uri);
}
int offset = data.getAsJsonPrimitive(OFFSET).getAsInt();
List<NotifyDescriptor.QuickPick.Item> items = Arrays.asList(gson.fromJson(data.get(ENDPOINTS), String[].class)).stream().map(endpoint -> new NotifyDescriptor.QuickPick.Item(endpoint, null)).collect(Collectors.toList());
NotifyDescriptor.QuickPick pick = new NotifyDescriptor.QuickPick(Bundle.DN_GenerateDataEndpoint(), Bundle.DN_SelectEndpoints(), items, true);
if (DialogDescriptor.OK_OPTION != DialogDisplayer.getDefault().notify(pick)) {
future.complete(null);
} else {
List<String> selectedIds = new ArrayList<>();
for (NotifyDescriptor.QuickPick.Item item : pick.getItems()) {
if (item.isSelected()) {
selectedIds.add(item.getLabel());
}
}
if (selectedIds.isEmpty()) {
future.complete(null);
} else {
List<String> repositoryNames = Arrays.asList(gson.fromJson(data.get(REPOSITORIES), String[].class));
future.complete(modify2Edit(js, getTask(offset, repositoryNames, selectedIds)));
}
}
} catch (IOException ex) {
future.completeExceptionally(ex);
}
});
return future;
}

private static Task<WorkingCopy> getTask(int offset, List<String> repositoryNames, List<String> endpointIds) {
return copy -> {
copy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
TreePath tp = copy.getTreeUtilities().pathFor(offset);
tp = copy.getTreeUtilities().getPathElementOfKind(TreeUtilities.CLASS_TREE_KINDS, tp);
if (tp != null) {
ClassTree clazz = (ClassTree) tp.getLeaf();
List<Tree> members = new ArrayList<>();
for (ElementHandle<VariableElement> repositoryHandle : repositoryHandles) {
VariableElement repository = repositoryHandle.resolve(copy);
if (repository != null) {
TypeMirror repositoryType = repository.asType();
if (repositoryType.getKind() == TypeKind.DECLARED) {
TypeElement repositoryTypeElement = (TypeElement) ((DeclaredType) repositoryType).asElement();
String id = null;
if (repositoryHandles.size() > 1) {
id = '/' + repositoryTypeElement.getSimpleName().toString().toLowerCase();
if (id.endsWith("repository")) {
id = id.substring(0, id.length() - 10);
}
}
for (String endpointId : endpointIds) {
String delegateMethodName = null;
if (endpointId.equals(id != null ? id + "/ -- GET" : "/ -- GET")) {
delegateMethodName = "findAll";
} else if (endpointId.equals(id != null ? id + "/{id} -- GET" : "/{id} -- GET")) {
delegateMethodName = "findById";
} else if (endpointId.equals(id != null ? id + "/{id} -- DELETE" : "/{id} -- DELETE")) {
delegateMethodName = "deleteById";
TypeElement te = (TypeElement) copy.getTrees().getElement(tp);
if (te != null) {
List<VariableElement> fields = ElementFilter.fieldsIn(te.getEnclosedElements());
List<Tree> members = new ArrayList<>();
for (String repositoryName : repositoryNames) {
VariableElement repository = fields.stream().filter(ve -> repositoryName.contentEquals(ve.getSimpleName())).findFirst().orElse(null);
if (repository != null) {
TypeMirror repositoryType = repository.asType();
if (repositoryType.getKind() == TypeKind.DECLARED) {
TypeElement repositoryTypeElement = (TypeElement) ((DeclaredType) repositoryType).asElement();
String id = null;
if (repositoryNames.size() > 1) {
id = '/' + repositoryTypeElement.getSimpleName().toString().toLowerCase();
if (id.endsWith("repository")) {
id = id.substring(0, id.length() - 10);
}
}
if (delegateMethodName != null) {
members.add(Utils.createControllerDataEndpointMethod(copy, repositoryTypeElement, repository.getSimpleName().toString(), delegateMethodName, id));
for (String endpointId : endpointIds) {
String delegateMethodName = null;
if (endpointId.equals(id != null ? id + "/ -- GET" : "/ -- GET")) {
delegateMethodName = "findAll";
} else if (endpointId.equals(id != null ? id + "/{id} -- GET" : "/{id} -- GET")) {
delegateMethodName = "findById";
} else if (endpointId.equals(id != null ? id + "/{id} -- DELETE" : "/{id} -- DELETE")) {
delegateMethodName = "deleteById";
}
if (delegateMethodName != null) {
members.add(Utils.createControllerDataEndpointMethod(copy, repositoryTypeElement, repository.getSimpleName().toString(), delegateMethodName, id));
}
}
}
}
}
copy.rewrite(clazz, GeneratorUtilities.get(copy).insertClassMembers(clazz, members, offset));
}
copy.rewrite(clazz, GeneratorUtilities.get(copy).insertClassMembers(clazz, members, offset));
}
};
}
Expand Down Expand Up @@ -291,7 +340,7 @@ public List<? extends CodeGenerator> create(Lookup context) {
if (!endpoints.isEmpty()) {
int offset = comp.getCaretPosition();
FileObject fo = cc.getFileObject();
List<ElementHandle<VariableElement>> repositoryHandles = repositories.stream().map(repository -> ElementHandle.create(repository)).collect(Collectors.toList());
List<String> repositoryNames = repositories.stream().map(repository -> repository.getSimpleName().toString()).collect(Collectors.toList());
ret.add(new CodeGenerator() {
@Override
public String getDisplayName() {
Expand Down Expand Up @@ -320,8 +369,8 @@ public void invoke() {
if (js == null) {
throw new IOException("Cannot get JavaSource for: " + fo.toURL().toString());
}
js.runModificationTask(getTask(offset, repositoryHandles, selectedEndpoints)).commit();
} catch (Exception ex) {
js.runModificationTask(getTask(offset, repositoryNames, selectedEndpoints)).commit();
} catch (IOException | IllegalArgumentException ex) {
Exceptions.printStackTrace(ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,7 +549,7 @@ public static WorkspaceEdit workspaceEditFromApi(org.netbeans.api.lsp.WorkspaceE
String docUri = parts.first().getDocument();
try {
FileObject file = Utils.fromUri(docUri);
if (file == null) {
if (file == null && uri != null) {
file = Utils.fromUri(uri);
}
FileObject fo = file;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,14 @@ public CompletableFuture<Object> processCommand(NbCodeLanguageClient client, Str
}

protected CodeAction createCodeAction(NbCodeLanguageClient client, String name, String kind, Object data, String command, Object... commandArgs) {
return createCodeAction(client, name, kind, data, command, Arrays.asList(commandArgs));
}

protected CodeAction createCodeAction(NbCodeLanguageClient client, String name, String kind, Object data, String command, List<Object> commandArgs) {
CodeAction action = new CodeAction(name);
action.setKind(kind);
if (command != null) {
action.setCommand(new Command(name, Utils.encodeCommand(command, client.getNbCodeCapabilities()), Arrays.asList(commandArgs)));
action.setCommand(new Command(name, Utils.encodeCommand(command, client.getNbCodeCapabilities()), commandArgs));
}
if (data != null) {
Map<String, Object> map = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ public Set<String> getCommands() {
public CompletableFuture<Object> processCommand(NbCodeLanguageClient client, String command, List<Object> arguments) {
for (CommandProvider cmdProvider : Lookup.getDefault().lookupAll(CommandProvider.class)) {
if (cmdProvider.getCommands().contains(command)) {
return cmdProvider.runCommand(command, arguments);
return cmdProvider.runCommand(command, arguments).thenApply(ret -> {
if (ret instanceof WorkspaceEdit) {
return Utils.workspaceEditFromApi((WorkspaceEdit) ret, null, client);
}
return ret;
});
}
}
return CompletableFuture.completedFuture(false);
Expand Down Expand Up @@ -96,7 +101,7 @@ public List<CodeAction> getCodeActions(NbCodeLanguageClient client, ResultIterat
}
CodeAction codeAction = createCodeAction(client, ca.getTitle(), ca.getKind(), data, command, command != null ? ca.getCommand().getArguments() : null);
if (edit != null) {
codeAction.setEdit(TextDocumentServiceImpl.fromAPI(edit, uri, client));
codeAction.setEdit(Utils.workspaceEditFromApi(edit, uri, client));
}
allActions.add(codeAction);
}
Expand All @@ -115,7 +120,7 @@ public CompletableFuture<CodeAction> resolve(NbCodeLanguageClient client, CodeAc
if (obj.has(URL) && obj.has(INDEX)) {
LazyCodeAction inputAction = lastCodeActions.get(obj.getAsJsonPrimitive(INDEX).getAsInt());
if (inputAction != null) {
codeAction.setEdit(TextDocumentServiceImpl.fromAPI(inputAction.getLazyEdit().get(), obj.getAsJsonPrimitive(URL).getAsString(), client));
codeAction.setEdit(Utils.workspaceEditFromApi(inputAction.getLazyEdit().get(), obj.getAsJsonPrimitive(URL).getAsString(), client));
}
}
}
Expand Down
Loading
Loading