下面列出了怎么用org.eclipse.lsp4j.WorkspaceEdit的API类实例代码及写法,或者点击链接到github查看源代码。
private static void createCodeActionsForGenerateGetterAndSetter(IVariableNode variableNode, String uri, String fileText, Range codeActionsRange, List<Either<Command, CodeAction>> codeActions)
{
WorkspaceEdit getSetEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, true, true);
CodeAction getAndSetCodeAction = new CodeAction();
getAndSetCodeAction.setTitle("Generate 'get' and 'set' accessors");
getAndSetCodeAction.setEdit(getSetEdit);
getAndSetCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(getAndSetCodeAction));
WorkspaceEdit getterEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, true, false);
CodeAction getterCodeAction = new CodeAction();
getterCodeAction.setTitle("Generate 'get' accessor (make read-only)");
getterCodeAction.setEdit(getterEdit);
getterCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(getterCodeAction));
WorkspaceEdit setterEdit = createWorkspaceEditForGenerateGetterAndSetter(
variableNode, uri, fileText, false, true);
CodeAction setterCodeAction = new CodeAction();
setterCodeAction.setTitle("Generate 'set' accessor (make write-only)");
setterCodeAction.setEdit(setterEdit);
setterCodeAction.setKind(CodeActionKind.RefactorRewrite);
codeActions.add(Either.forRight(setterCodeAction));
}
public static CodeAction replaceAt(String title, String replaceText, TextDocumentItem document,
Diagnostic diagnostic, Collection<Range> ranges) {
CodeAction insertContentAction = new CodeAction(title);
insertContentAction.setKind(CodeActionKind.QuickFix);
insertContentAction.setDiagnostics(Arrays.asList(diagnostic));
VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(
document.getUri(), document.getVersion());
List<TextEdit> edits = new ArrayList<TextEdit>();
for (Range range : ranges) {
TextEdit edit = new TextEdit(range, replaceText);
edits.add(edit);
}
TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, edits);
WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));
insertContentAction.setEdit(workspaceEdit);
return insertContentAction;
}
public static WorkspaceEdit createWorkspaceEditForGenerateLocalVariable(
IIdentifierNode identifierNode, String uri, String text)
{
TextEdit textEdit = createTextEditForGenerateLocalVariable(identifierNode, text);
if (textEdit == null)
{
return null;
}
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
HashMap<String,List<TextEdit>> changes = new HashMap<>();
List<TextEdit> edits = new ArrayList<>();
edits.add(textEdit);
changes.put(uri, edits);
workspaceEdit.setChanges(changes);
return workspaceEdit;
}
@Test
public void testConvertSimpleCompositeChange() throws CoreException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
CompositeChange change = new CompositeChange("simple composite change");
RenameCompilationUnitChange resourceChange = new RenameCompilationUnitChange(cu, "ENew.java");
change.add(resourceChange);
CompilationUnitChange textChange = new CompilationUnitChange("insertText", cu);
textChange.setEdit(new InsertEdit(0, "// some content"));
change.add(textChange);
WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
assertEquals(edit.getDocumentChanges().size(), 2);
assertTrue(edit.getDocumentChanges().get(0).getRight() instanceof RenameFile);
assertTrue(edit.getDocumentChanges().get(1).getLeft() instanceof TextDocumentEdit);
}
public static WorkspaceEdit createWorkspaceEditForAddImport(IDefinition definition, String fileText, String uri, ImportRange importRange)
{
TextEdit textEdit = createTextEditForAddImport(definition.getQualifiedName(), fileText, importRange);
if (textEdit == null)
{
return null;
}
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
HashMap<String,List<TextEdit>> changes = new HashMap<>();
List<TextEdit> edits = new ArrayList<>();
edits.add(textEdit);
changes.put(uri, edits);
workspaceEdit.setChanges(changes);
return workspaceEdit;
}
/** Adds a quick-fix code action with the given title, edit and command */
public void acceptQuickfixCodeAction(QuickfixContext context, String title, WorkspaceEdit edit, Command command) {
if (edit == null && command == null) {
return;
}
CodeAction codeAction = new CodeAction();
codeAction.setTitle(title);
codeAction.setEdit(edit);
codeAction.setCommand(command);
codeAction.setKind(CodeActionKind.QuickFix);
if (context.options != null && context.options.getCodeActionParams() != null) {
CodeActionContext cac = context.options.getCodeActionParams().getContext();
if (cac != null && cac.getDiagnostics() != null) {
codeAction.setDiagnostics(cac.getDiagnostics());
}
}
codeActions.add(Either.forRight(codeAction));
}
@Test
public void testOrganizeImportsUnused() throws CoreException, BadLocationException {
IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
StringBuilder buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.ArrayList;\n");
buf.append("\n");
buf.append("public class E {\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("package test1;\n");
buf.append("\n");
buf.append("public class E {\n");
buf.append("}\n");
WorkspaceEdit rootEdit = new WorkspaceEdit();
command.organizeImportsInCompilationUnit(cu, rootEdit);
assertEquals(buf.toString(), getOrganizeImportResult(cu, rootEdit));
}
private Optional<Either<Command, CodeAction>> convertToWorkspaceEditAction(CodeActionContext context, ICompilationUnit cu, String name, String kind, TextEdit edit) {
WorkspaceEdit workspaceEdit = convertToWorkspaceEdit(cu, edit);
if (!ChangeUtil.hasChanges(workspaceEdit)) {
return Optional.empty();
}
Command command = new Command(name, CodeActionHandler.COMMAND_ID_APPLY_EDIT, Collections.singletonList(workspaceEdit));
if (preferenceManager.getClientPreferences().isSupportedCodeActionKind(kind)) {
CodeAction codeAction = new CodeAction(name);
codeAction.setKind(kind);
codeAction.setCommand(command);
codeAction.setDiagnostics(context.getDiagnostics());
return Optional.of(Either.forRight(codeAction));
} else {
return Optional.of(Either.forLeft(command));
}
}
public static WorkspaceEdit createWorkspaceEditForRemoveUnusedImport(String fileText, String uri, Range range)
{
TextEdit textEdit = createTextEditForRemoveUnusedImport(fileText, range);
if (textEdit == null)
{
return null;
}
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
HashMap<String,List<TextEdit>> changes = new HashMap<>();
List<TextEdit> edits = new ArrayList<>();
edits.add(textEdit);
changes.put(uri, edits);
workspaceEdit.setChanges(changes);
return workspaceEdit;
}
@Test
public void testGenericOrganizeImportsCall() throws Exception {
importProjects("eclipse/hello");
IProject project = WorkspaceHelper.getProject("hello");
String filename = project.getFile("src/java/Foo4.java").getRawLocationURI().toString();
OrganizeImportsCommand command = new OrganizeImportsCommand();
Object result = command.organizeImports(Arrays.asList(filename));
assertNotNull(result);
assertTrue(result instanceof WorkspaceEdit);
WorkspaceEdit ws = (WorkspaceEdit) result;
assertFalse(ws.getChanges().isEmpty());
TextEdit edit = ws.getChanges().values().stream().findFirst().get().get(0);
assertEquals(0, edit.getRange().getStart().getLine());
assertEquals(4, edit.getRange().getEnd().getLine());
}
public static WorkspaceEdit createWorkspaceEditForGenerateGetterAndSetter(
IVariableNode variableNode, String uri, String text, boolean generateGetter, boolean generateSetter)
{
TextEdit textEdit = createTextEditForGenerateGetterAndSetter(variableNode, text, generateGetter, generateSetter);
if (textEdit == null)
{
return null;
}
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
HashMap<String,List<TextEdit>> changes = new HashMap<>();
List<TextEdit> edits = new ArrayList<>();
edits.add(textEdit);
changes.put(uri, edits);
workspaceEdit.setChanges(changes);
return workspaceEdit;
}
public static WorkspaceEdit createWorkspaceEditForAddMXMLNamespace(String nsPrefix, String nsURI, String fileText, String fileURI, int startIndex, int endIndex)
{
TextEdit textEdit = createTextEditForAddMXMLNamespace(nsPrefix, nsURI, fileText, startIndex, endIndex);
if (textEdit == null)
{
return null;
}
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
HashMap<String,List<TextEdit>> changes = new HashMap<>();
List<TextEdit> edits = new ArrayList<>();
edits.add(textEdit);
changes.put(fileURI, edits);
workspaceEdit.setChanges(changes);
return workspaceEdit;
}
public static void applyEdit(PsiElement elem, String newName, UsageInfo[] infos,
RefactoringElementListener listener, List<VirtualFile> openedEditors) {
Map<String, List<TextEdit>> edits = new HashMap<>();
if (elem instanceof LSPPsiElement) {
LSPPsiElement lspElem = (LSPPsiElement) elem;
if (Stream.of(infos).allMatch(info -> info.getElement() instanceof LSPPsiElement)) {
Stream.of(infos).forEach(ui -> {
Editor editor = FileUtils.editorFromVirtualFile(ui.getVirtualFile(), ui.getProject());
TextRange range = ui.getElement().getTextRange();
Range lspRange = new Range(DocumentUtils.offsetToLSPPos(editor, range.getStartOffset()),
DocumentUtils.offsetToLSPPos(editor, range.getEndOffset()));
TextEdit edit = new TextEdit(lspRange, newName);
String uri = null;
try {
uri = FileUtils.sanitizeURI(
new URL(ui.getVirtualFile().getUrl().replace(" ", FileUtils.SPACE_ENCODED)).toURI()
.toString());
} catch (MalformedURLException | URISyntaxException e) {
LOG.warn(e);
}
if (edits.keySet().contains(uri)) {
edits.get(uri).add(edit);
} else {
List<TextEdit> textEdits = new ArrayList<>();
textEdits.add(edit);
edits.put(uri, textEdits);
}
});
WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits);
applyEdit(workspaceEdit, "Rename " + lspElem.getName() + " to " + newName, openedEditors);
}
}
}
@Test
public void testOrganizeImportsModuleInfo() throws Exception {
setupJava9();
IPackageFragment pack1 = fSourceFolder.createPackageFragment("", false, null);
StringBuilder buf = new StringBuilder();
buf.append("import foo.bar.MyDriverAction;\n");
buf.append("import java.sql.DriverAction;\n");
buf.append("import java.sql.SQLException;\n");
buf.append("\n");
buf.append("module mymodule.nine {\n");
buf.append(" requires java.sql;\n");
buf.append(" exports foo.bar;\n");
buf.append(" provides DriverAction with MyDriverAction;\n");
buf.append("}\n");
ICompilationUnit cu = pack1.createCompilationUnit("module-info.java", buf.toString(), false, null);
buf = new StringBuilder();
buf.append("import java.sql.DriverAction;\n");
buf.append("\n");
buf.append("import foo.bar.MyDriverAction;\n");
buf.append("\n");
buf.append("module mymodule.nine {\n");
buf.append(" requires java.sql;\n");
buf.append(" exports foo.bar;\n");
buf.append(" provides DriverAction with MyDriverAction;\n");
buf.append("}\n");
WorkspaceEdit rootEdit = new WorkspaceEdit();
command.organizeImportsInCompilationUnit(cu, rootEdit);
assertEquals(buf.toString(), getOrganizeImportResult(cu, rootEdit));
}
/**
* Merge the changes of two workspace edits to a new edit.
*/
public static WorkspaceEdit mergeChanges(WorkspaceEdit editA, WorkspaceEdit editB, boolean ignoreResourceChange) {
if (editA == null && editB == null) {
return null;
}
WorkspaceEdit result = new WorkspaceEdit();
appendChanges(result, editA, ignoreResourceChange);
appendChanges(result, editB, ignoreResourceChange);
return result;
}
/**
* Create a CodeAction to insert a new content at the end of the given range.
*
* @param title
* @param range
* @param insertText
* @param document
* @param diagnostic
*
* @return the CodeAction to insert a new content at the end of the given range.
*/
public static CodeAction insert(String title, Position position, String insertText, TextDocumentItem document,
Diagnostic diagnostic) {
CodeAction insertContentAction = new CodeAction(title);
insertContentAction.setKind(CodeActionKind.QuickFix);
insertContentAction.setDiagnostics(Arrays.asList(diagnostic));
TextDocumentEdit textDocumentEdit = insertEdit(insertText, position, document);
WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));
insertContentAction.setEdit(workspaceEdit);
return insertContentAction;
}
public static CodeAction ca(Diagnostic d, Either<TextDocumentEdit, ResourceOperation>... ops) {
CodeAction codeAction = new CodeAction();
codeAction.setDiagnostics(Collections.singletonList(d));
codeAction.setEdit(new WorkspaceEdit(Arrays.asList(ops)));
codeAction.setTitle("");
return codeAction;
}
public static void assertRename(String value, String newText, List<TextEdit> expectedEdits)
throws BadLocationException {
int offset = value.indexOf("|");
value = value.substring(0, offset) + value.substring(offset + 1);
DOMDocument document = DOMParser.getInstance().parse(value, "test://test/test.html", null);
Position position = document.positionAt(offset);
XMLLanguageService languageService = new XMLLanguageService();
WorkspaceEdit workspaceEdit = languageService.doRename(document, position, newText);
List<TextEdit> actualEdits = workspaceEdit.getChanges().get("test://test/test.html");
assertArrayEquals(expectedEdits.toArray(), actualEdits.toArray());
}
@Test
public void testRenameTypeParameter() throws JavaModelException, BadLocationException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes= {
"package test1;\n",
"public class A<T|*> {\n",
" private T t;\n",
" public T get() { return t; }\n",
"}\n"
};
StringBuilder builder = new StringBuilder();
Position pos = mergeCode(builder, codes);
ICompilationUnit cu = pack1.createCompilationUnit("A.java", builder.toString(), false, null);
WorkspaceEdit edit = getRenameEdit(cu, pos, "TT");
assertNotNull(edit);
assertEquals(edit.getChanges().size(), 1);
assertEquals(TextEditUtil.apply(builder.toString(), edit.getChanges().get(JDTUtils.toURI(cu))),
"package test1;\n" +
"public class A<TT> {\n" +
" private TT t;\n" +
" public TT get() { return t; }\n" +
"}\n"
);
}
/** @return string for given element */
public String toString(WorkspaceEdit edit) {
if (edit == null) {
return "";
}
String str = Strings.join(", ",
Strings.toString(this::toString6, edit.getDocumentChanges()),
"\n " + Strings.toString("\n ", edit.getChanges(), this::relativize,
(l) -> Strings.toString(this::toString, l)));
return "(" + str + ")";
}
@Test(expected = ResponseErrorException.class)
public void testRenameTypeWithErrors() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes = { "package test1;\n",
"public class Newname {\n",
" }\n",
"}\n" };
StringBuilder builder = new StringBuilder();
mergeCode(builder, codes);
ICompilationUnit cu = pack1.createCompilationUnit("Newname.java", builder.toString(), false, null);
String[] codes1 = { "package test1;\n",
"public class E|* {\n",
" public E() {\n",
" }\n",
" public int bar() {\n", " }\n",
" public int foo() {\n",
" this.bar();\n",
" }\n",
"}\n" };
builder = new StringBuilder();
Position pos = mergeCode(builder, codes1);
cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);
WorkspaceEdit edit = getRenameEdit(cu, pos, "Newname");
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> resourceChanges = edit.getDocumentChanges();
assertEquals(resourceChanges.size(), 3);
}
/**
* Fix the issues of the same kind in the entire file.
*/
@ExecutableCommandHandler(COMPOSITE_FIX_FILE)
public Void fixAllInFile(String title, String code, String fixId, CodeActionParams codeActionParams,
ILanguageServerAccess access, CancelIndicator cancelIndicator) {
String uriString = codeActionParams.getTextDocument().getUri();
URI uri = uriExtensions.toUri(uriString);
WorkspaceEdit edit = codeActionService.applyToFile(uri, code, fixId, cancelIndicator);
access.getLanguageClient().applyEdit(new ApplyWorkspaceEditParams(edit, title));
return null;
}
/**
* Fix the issues of the same kind in the entire project.
*/
@ExecutableCommandHandler(COMPOSITE_FIX_PROJECT)
public Void fixAllInProject(String title, String code, String fixId, CodeActionParams codeActionParams,
ILanguageServerAccess access, CancelIndicator cancelIndicator) {
String uriString = codeActionParams.getTextDocument().getUri();
URI uri = uriExtensions.toUri(uriString);
WorkspaceEdit edit = codeActionService.applyToProject(uri, code, fixId, cancelIndicator);
access.getLanguageClient().applyEdit(new ApplyWorkspaceEditParams(edit, title));
return null;
}
/**
* Converts Change to WorkspaceEdit for further consumption.
*
* @param change
* {@link Change} to convert
* @return {@link WorkspaceEdit} converted from the change
* @throws CoreException
*/
public static WorkspaceEdit convertToWorkspaceEdit(Change change) throws CoreException {
WorkspaceEdit edit = new WorkspaceEdit();
if (change instanceof CompositeChange) {
convertCompositeChange((CompositeChange) change, edit);
} else {
convertSingleChange(change, edit);
}
return edit;
}
private void assertRenameFileOperation(Either<Command, CodeAction> codeAction, String newUri) {
WorkspaceEdit edit = getWorkspaceEdit(codeAction);
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = edit.getDocumentChanges();
assertNotNull(documentChanges);
assertEquals(1, documentChanges.size());
ResourceOperation resourceOperation = documentChanges.get(0).getRight();
assertNotNull(resourceOperation);
assertTrue(resourceOperation instanceof RenameFile);
assertEquals(newUri, ((RenameFile) resourceOperation).getNewUri());
}
/** Adds a quick-fix code action with the given title and text edits */
@Override
public void acceptQuickfixCodeAction(QuickfixContext context, String title, List<TextEdit> textEdits) {
if (textEdits == null || textEdits.isEmpty()) {
return;
}
String uri = context.options.getCodeActionParams().getTextDocument().getUri();
Map<String, List<TextEdit>> changes = new HashMap<>();
changes.put(uri, textEdits);
WorkspaceEdit edit = new WorkspaceEdit();
edit.setChanges(changes);
acceptQuickfixCodeAction(context, title, edit, null);
}
@Test
public void testRenameAutoQuoteRef() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("type Foo {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("type Bar extends Foo {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final String model = _builder.toString();
final String file = this.writeFile("foo/Foo.renametl", model);
this.initialize();
final TextDocumentIdentifier identifier = new TextDocumentIdentifier(file);
final Position position = new Position(3, 18);
PrepareRenameParams _prepareRenameParams = new PrepareRenameParams(identifier, position);
final Range range = this.languageServer.prepareRename(_prepareRenameParams).get().getLeft();
this.assertEquals("Foo", new Document(Integer.valueOf(0), model).getSubstring(range));
final RenameParams params = new RenameParams(identifier, position, "type");
final WorkspaceEdit workspaceEdit = this.languageServer.rename(params).get();
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("changes :");
_builder_1.newLine();
_builder_1.append("documentChanges : ");
_builder_1.newLine();
_builder_1.append(" ");
_builder_1.append("Foo.renametl <1> : ^type [[0, 5] .. [0, 8]]");
_builder_1.newLine();
_builder_1.append(" ");
_builder_1.append("^type [[3, 17] .. [3, 20]]");
_builder_1.newLine();
this.assertEquals(_builder_1.toString(), this.toExpectation(workspaceEdit));
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
public void testApplyTextEdit() throws Exception {
clearWorkDir();
FileObject wd = FileUtil.toFileObject(getWorkDir());
FileObject sourceFile1 = wd.createData("Test1.txt");
try (OutputStream out = sourceFile1.getOutputStream()) {
out.write(("0123456789\n" +
"0123456789\n" +
"0123456789\n" +
"0123456789\n" +
"0123456789\n").getBytes("UTF-8"));
}
FileObject sourceFile2 = wd.createData("Test2.txt");
try (OutputStream out = sourceFile2.getOutputStream()) {
out.write(("0123456789\n" +
"0123456789\n" +
"0123456789\n" +
"0123456789\n" +
"0123456789\n").getBytes("UTF-8"));
}
Map<String, List<TextEdit>> changes = new HashMap<>();
changes.put(Utils.toURI(sourceFile1), Arrays.asList(new TextEdit(new Range(new Position(2, 3), new Position(2, 6)), "a"),
new TextEdit(new Range(new Position(1, 2), new Position(1, 6)), "b"),
new TextEdit(new Range(new Position(3, 1), new Position(4, 4)), "c")));
changes.put(Utils.toURI(sourceFile2), Arrays.asList(new TextEdit(new Range(new Position(2, 3), new Position(2, 6)), "a"),
new TextEdit(new Range(new Position(1, 2), new Position(1, 6)), "b"),
new TextEdit(new Range(new Position(3, 1), new Position(4, 4)), "c")));
WorkspaceEdit edit = new WorkspaceEdit(changes);
Utils.applyWorkspaceEdit(edit);
assertContent("0123456789\n" +
"01b6789\n" +
"012a6789\n" +
"0c456789\n",
sourceFile1);
assertContent("0123456789\n" +
"01b6789\n" +
"012a6789\n" +
"0c456789\n",
sourceFile2);
LifecycleManager.getDefault().saveAll();
}
private static void convertTextChange(TextChange textChange, WorkspaceEdit rootEdit) {
Object modifiedElement = textChange.getModifiedElement();
if (!(modifiedElement instanceof IJavaElement)) {
return;
}
TextEdit textEdits = textChange.getEdit();
if (textEdits == null) {
return;
}
ICompilationUnit compilationUnit = (ICompilationUnit) ((IJavaElement) modifiedElement).getAncestor(IJavaElement.COMPILATION_UNIT);
convertTextEdit(rootEdit, compilationUnit, textEdits);
}
public Object organizeImports(List<Object> arguments) throws CoreException {
WorkspaceEdit edit = new WorkspaceEdit();
if (arguments != null && !arguments.isEmpty() && arguments.get(0) instanceof String) {
final String fileUri = (String) arguments.get(0);
final IPath rootPath = ResourceUtils.filePathFromURI(fileUri);
if (rootPath == null) {
throw new CoreException(new Status(IStatus.ERROR, IConstants.PLUGIN_ID, "URI is not found"));
}
final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot();
IResource resource = wsroot.getFileForLocation(rootPath);
if (resource == null) {
resource = wsroot.getContainerForLocation(rootPath);
}
if (resource != null) {
final OrganizeImportsCommand command = new OrganizeImportsCommand();
int type = resource.getType();
switch (type) {
case IResource.PROJECT:
edit = command.organizeImportsInProject(resource.getAdapter(IProject.class));
break;
case IResource.FOLDER:
edit = command.organizeImportsInDirectory(fileUri, resource.getProject());
break;
case IResource.FILE:
edit = command.organizeImportsInFile(fileUri);
break;
default://This can only be IResource.ROOT. Which is not relevant to jdt.ls
// do nothing allow to return the empty WorkspaceEdit.
break;
}
}
}
return edit;
}