Search in sources :

Example 6 with FileRename

use of org.eclipse.lsp4j.FileRename in project eclipse.jdt.ls by eclipse.

the class FileEventHandler method computeFileRenameEdit.

private static WorkspaceEdit computeFileRenameEdit(FileRename[] renameEvents, IProgressMonitor monitor) {
    SubMonitor submonitor = SubMonitor.convert(monitor, "Computing file rename updates...", 100 * renameEvents.length);
    WorkspaceEdit root = null;
    for (FileRename event : renameEvents) {
        String oldUri = event.getOldUri();
        String newUri = event.getNewUri();
        ICompilationUnit unit = JDTUtils.resolveCompilationUnit(oldUri);
        SubMonitor splitedMonitor = submonitor.split(100);
        try {
            if (unit == null || !unit.exists()) {
                JavaLanguageServerPlugin.logError("Failed to compute the file rename edit because the file '" + oldUri + "' doesn't exist.");
                continue;
            }
            if (unit != null) {
                String oldPrimaryType = getPrimaryTypeName(oldUri);
                String newPrimaryType = getPrimaryTypeName(newUri);
                if (!unit.getType(newPrimaryType).exists() && unit.getType(oldPrimaryType).exists()) {
                    WorkspaceEdit edit = getRenameEdit(unit.getType(oldPrimaryType), newPrimaryType, splitedMonitor);
                    root = ChangeUtil.mergeChanges(root, edit, true);
                }
            }
        } catch (CoreException e) {
            JavaLanguageServerPlugin.logException("Computing the file rename edit: ", e);
        } finally {
            splitedMonitor.done();
        }
    }
    submonitor.done();
    return root;
}
Also used : FileRename(org.eclipse.lsp4j.FileRename) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CoreException(org.eclipse.core.runtime.CoreException) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit)

Example 7 with FileRename

use of org.eclipse.lsp4j.FileRename in project eclipse.jdt.ls by eclipse.

the class FileEventHandler method handleWillRenameFiles.

public static WorkspaceEdit handleWillRenameFiles(RenameFilesParams params, IProgressMonitor monitor) {
    List<FileRename> files = params.getFiles();
    if (files == null || files.isEmpty()) {
        return null;
    }
    FileRename[] renameFiles = new FileRename[0];
    FileRename[] renameFolders = new FileRename[0];
    FileRename[] moveFiles = new FileRename[0];
    if (files.size() == 1) {
        FileRename renameEvent = files.get(0);
        if (isFileNameRenameEvent(renameEvent)) {
            renameFiles = new FileRename[] { renameEvent };
        } else if (isFolderRenameEvent(renameEvent)) {
            renameFolders = new FileRename[] { renameEvent };
        } else if (isMoveEvent(renameEvent)) {
            moveFiles = new FileRename[] { renameEvent };
        }
    } else {
        moveFiles = files.stream().filter(event -> isMoveEvent(event)).toArray(FileRename[]::new);
    }
    if (renameFiles.length == 0 && renameFolders.length == 0 && moveFiles.length == 0) {
        return null;
    }
    SourcePath[] sourcePaths = getSourcePaths();
    if (sourcePaths == null || sourcePaths.length == 0) {
        return null;
    }
    WorkspaceEdit root = null;
    SubMonitor submonitor = SubMonitor.convert(monitor, "Computing rename updates...", renameFiles.length + renameFolders.length + moveFiles.length);
    if (renameFiles.length > 0) {
        WorkspaceEdit edit = computeFileRenameEdit(renameFiles, submonitor.split(renameFiles.length));
        root = ChangeUtil.mergeChanges(root, edit, true);
    }
    if (renameFolders.length > 0) {
        WorkspaceEdit edit = computePackageRenameEdit(renameFolders, sourcePaths, submonitor.split(renameFolders.length));
        root = ChangeUtil.mergeChanges(root, edit, true);
    }
    if (moveFiles.length > 0) {
        WorkspaceEdit edit = computeMoveEdit(moveFiles, sourcePaths, submonitor.split(moveFiles.length));
        root = ChangeUtil.mergeChanges(root, edit, true);
    }
    submonitor.done();
    return ChangeUtil.hasChanges(root) ? root : null;
}
Also used : FileRename(org.eclipse.lsp4j.FileRename) SourcePath(org.eclipse.jdt.ls.core.internal.commands.BuildPathCommand.SourcePath) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit)

Example 8 with FileRename

use of org.eclipse.lsp4j.FileRename in project eclipse.jdt.ls by eclipse.

the class FileEventHandler method computeMoveEdit.

private static WorkspaceEdit computeMoveEdit(FileRename[] moveEvents, SourcePath[] sourcePaths, IProgressMonitor monitor) {
    IPath[] newPaths = Stream.of(moveEvents).map(event -> ResourceUtils.filePathFromURI(event.getNewUri())).toArray(IPath[]::new);
    IPath destinationPath = ResourceUtils.getLongestCommonPath(newPaths);
    if (destinationPath == null) {
        return null;
    }
    // Verify all files are moving to the same destination.
    for (FileRename event : moveEvents) {
        IPath oldPath = ResourceUtils.filePathFromURI(event.getOldUri());
        IPath expectedNewPath = destinationPath.append(oldPath.lastSegment());
        IPath actualNewPath = ResourceUtils.filePathFromURI(event.getNewUri());
        if (!Objects.equals(expectedNewPath, actualNewPath)) {
            JavaLanguageServerPlugin.logError("Failed to compute move refactoring because the files are not moving to the same destination " + destinationPath.toOSString());
            return null;
        }
    }
    IPackageFragment destinationPackage = resolvePackageFragment(destinationPath, sourcePaths);
    if (destinationPackage == null) {
        return null;
    }
    // formatter:off
    ICompilationUnit[] cus = Stream.of(moveEvents).filter(event -> {
        IPath oldPath = ResourceUtils.filePathFromURI(event.getOldUri());
        return oldPath != null && oldPath.toFile().isFile();
    }).map(event -> JDTUtils.resolveCompilationUnit(event.getOldUri())).filter(cu -> cu != null && cu.getJavaProject() != null).toArray(ICompilationUnit[]::new);
    // formatter:on
    List<ICompilationUnit> nonClasspathCus = new ArrayList<>();
    for (ICompilationUnit unit : cus) {
        if (!unit.getJavaProject().isOnClasspath(unit)) {
            nonClasspathCus.add(unit);
        }
    }
    WorkspaceEdit[] root = new WorkspaceEdit[1];
    if (cus.length > 0) {
        try {
            // otherwise invoking cu.getBuffer() will throw exception.
            for (ICompilationUnit cu : nonClasspathCus) {
                cu.becomeWorkingCopy(monitor);
            }
            IReorgDestination packageDestination = ReorgDestinationFactory.createDestination(destinationPackage);
            ResourcesPlugin.getWorkspace().run((pm) -> {
                root[0] = MoveHandler.move(new IResource[0], cus, packageDestination, true, pm);
            }, monitor);
        } catch (CoreException e) {
            JavaLanguageServerPlugin.logException("Failed to compute the move update", e);
        } finally {
            for (ICompilationUnit cu : nonClasspathCus) {
                try {
                    cu.discardWorkingCopy();
                } catch (JavaModelException e) {
                // do nothing
                }
            }
        }
    }
    return ChangeUtil.hasChanges(root[0]) ? root[0] : null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) Arrays(java.util.Arrays) BuildPathCommand(org.eclipse.jdt.ls.core.internal.commands.BuildPathCommand) RenamePackageProcessor(org.eclipse.jdt.ls.core.internal.corext.refactoring.rename.RenamePackageProcessor) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) JavaModelException(org.eclipse.jdt.core.JavaModelException) SubMonitor(org.eclipse.core.runtime.SubMonitor) RenameSupport(org.eclipse.jdt.ls.core.internal.corext.refactoring.rename.RenameSupport) ProjectUtils(org.eclipse.jdt.ls.core.internal.ProjectUtils) CoreException(org.eclipse.core.runtime.CoreException) CheckConditionsOperation(org.eclipse.ltk.core.refactoring.CheckConditionsOperation) RefactoringTickProvider(org.eclipse.ltk.core.refactoring.RefactoringTickProvider) ArrayList(java.util.ArrayList) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) FileRename(org.eclipse.lsp4j.FileRename) IPath(org.eclipse.core.runtime.IPath) SourcePath(org.eclipse.jdt.ls.core.internal.commands.BuildPathCommand.SourcePath) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) Change(org.eclipse.ltk.core.refactoring.Change) ReorgDestinationFactory(org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgDestinationFactory) RenameFilesParams(org.eclipse.lsp4j.RenameFilesParams) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) ResourceUtils(org.eclipse.jdt.ls.core.internal.ResourceUtils) JDTUtils(org.eclipse.jdt.ls.core.internal.JDTUtils) NotCancelableProgressMonitor(org.eclipse.ltk.internal.core.refactoring.NotCancelableProgressMonitor) IJavaProject(org.eclipse.jdt.core.IJavaProject) ListCommandResult(org.eclipse.jdt.ls.core.internal.commands.BuildPathCommand.ListCommandResult) JavaLanguageServerPlugin(org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin) IReorgDestination(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) IJavaElement(org.eclipse.jdt.core.IJavaElement) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) IResource(org.eclipse.core.resources.IResource) Path(org.eclipse.core.runtime.Path) RenameRefactoring(org.eclipse.ltk.core.refactoring.participants.RenameRefactoring) ChangeUtil(org.eclipse.jdt.ls.core.internal.ChangeUtil) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IReorgDestination(org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) ArrayList(java.util.ArrayList) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) FileRename(org.eclipse.lsp4j.FileRename) CoreException(org.eclipse.core.runtime.CoreException) IResource(org.eclipse.core.resources.IResource)

Example 9 with FileRename

use of org.eclipse.lsp4j.FileRename in project eclipse.jdt.ls by eclipse.

the class FileEventHandler method computePackageRenameEdit.

private static WorkspaceEdit computePackageRenameEdit(FileRename[] renameEvents, SourcePath[] sourcePaths, IProgressMonitor monitor) {
    WorkspaceEdit[] root = new WorkspaceEdit[1];
    SubMonitor submonitor = SubMonitor.convert(monitor, "Computing package rename updates...", 100 * renameEvents.length);
    for (FileRename event : renameEvents) {
        IPath oldLocation = ResourceUtils.filePathFromURI(event.getOldUri());
        IPath newLocation = ResourceUtils.filePathFromURI(event.getNewUri());
        IPackageFragment oldPackageFragment = resolvePackageFragment(oldLocation, sourcePaths);
        SubMonitor renameMonitor = submonitor.split(100);
        try {
            if (oldPackageFragment != null && !oldPackageFragment.isDefaultPackage() && oldPackageFragment.getResource() != null) {
                String newPackageName = resolvePackageName(newLocation, sourcePaths);
                if (newPackageName == null) {
                    continue;
                }
                oldPackageFragment.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
                if (oldPackageFragment.exists()) {
                    ResourcesPlugin.getWorkspace().run((pm) -> {
                        WorkspaceEdit edit = getRenameEdit(oldPackageFragment, newPackageName, pm);
                        root[0] = ChangeUtil.mergeChanges(root[0], edit, true);
                    }, oldPackageFragment.getSchedulingRule(), IResource.NONE, renameMonitor);
                }
            }
        } catch (CoreException e) {
            JavaLanguageServerPlugin.logException("Failed to compute the package rename update", e);
        } finally {
            renameMonitor.done();
        }
    }
    submonitor.done();
    return ChangeUtil.hasChanges(root[0]) ? root[0] : null;
}
Also used : FileRename(org.eclipse.lsp4j.FileRename) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) IPath(org.eclipse.core.runtime.IPath) CoreException(org.eclipse.core.runtime.CoreException) SubMonitor(org.eclipse.core.runtime.SubMonitor) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit)

Example 10 with FileRename

use of org.eclipse.lsp4j.FileRename in project eclipse.jdt.ls by eclipse.

the class FileEventHandlerTest method testRenamePackage.

// Test renaming package from "parent.pack2" to "parent.newpack2"
@Test
public void testRenamePackage() throws JavaModelException, BadLocationException {
    when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
    IPackageFragment pack1 = sourceFolder.createPackageFragment("parent.pack1", false, null);
    IPackageFragment pack2 = sourceFolder.createPackageFragment("parent.pack2", false, null);
    StringBuilder codeA = new StringBuilder();
    codeA.append("package parent.pack1;\n");
    codeA.append("import parent.pack2.B;\n");
    codeA.append("public class A {\n");
    codeA.append("	public void foo() {\n");
    codeA.append("		B b = new B();\n");
    codeA.append("		b.foo();\n");
    codeA.append("	}\n");
    codeA.append("}\n");
    StringBuilder codeB = new StringBuilder();
    codeB.append("package parent.pack2;\n");
    codeB.append("public class B {\n");
    codeB.append("	public B() {}\n");
    codeB.append("	public void foo() {}\n");
    codeB.append("}\n");
    ICompilationUnit cuA = pack1.createCompilationUnit("A.java", codeA.toString(), false, null);
    ICompilationUnit cuB = pack2.createCompilationUnit("B.java", codeB.toString(), false, null);
    String pack2Uri = JDTUtils.getFileURI(pack2.getResource());
    String newPack2Uri = pack2Uri.replace("pack2", "newpack2");
    WorkspaceEdit edit = FileEventHandler.handleWillRenameFiles(new RenameFilesParams(Arrays.asList(new FileRename(pack2Uri, newPack2Uri))), new NullProgressMonitor());
    assertNotNull(edit);
    List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = edit.getDocumentChanges();
    assertEquals(2, documentChanges.size());
    assertTrue(documentChanges.get(0).isLeft());
    assertEquals(documentChanges.get(0).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuA));
    assertEquals(TextEditUtil.apply(codeA.toString(), documentChanges.get(0).getLeft().getEdits()), "package parent.pack1;\n" + "import parent.newpack2.B;\n" + "public class A {\n" + "	public void foo() {\n" + "		B b = new B();\n" + "		b.foo();\n" + "	}\n" + "}\n");
    assertTrue(documentChanges.get(1).isLeft());
    assertEquals(documentChanges.get(1).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuB));
    assertEquals(TextEditUtil.apply(codeB.toString(), documentChanges.get(1).getLeft().getEdits()), "package parent.newpack2;\n" + "public class B {\n" + "	public B() {}\n" + "	public void foo() {}\n" + "}\n");
}
Also used : FileRename(org.eclipse.lsp4j.FileRename) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) Either(org.eclipse.lsp4j.jsonrpc.messages.Either) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) RenameFilesParams(org.eclipse.lsp4j.RenameFilesParams) AbstractProjectsManagerBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest) Test(org.junit.Test)

Aggregations

FileRename (org.eclipse.lsp4j.FileRename)12 WorkspaceEdit (org.eclipse.lsp4j.WorkspaceEdit)12 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)10 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)10 RenameFilesParams (org.eclipse.lsp4j.RenameFilesParams)9 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)8 AbstractProjectsManagerBasedTest (org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest)8 Test (org.junit.Test)8 Either (org.eclipse.lsp4j.jsonrpc.messages.Either)5 ArrayList (java.util.ArrayList)4 SubMonitor (org.eclipse.core.runtime.SubMonitor)4 CoreException (org.eclipse.core.runtime.CoreException)3 TextEdit (org.eclipse.lsp4j.TextEdit)3 IPath (org.eclipse.core.runtime.IPath)2 SourcePath (org.eclipse.jdt.ls.core.internal.commands.BuildPathCommand.SourcePath)2 TextDocumentEdit (org.eclipse.lsp4j.TextDocumentEdit)2 File (java.io.File)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Objects (java.util.Objects)1