package org.eclipse.ltk.core.refactoring.resource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
import org.eclipse.ltk.internal.core.refactoring.BasicElementLabels;
import org.eclipse.ltk.internal.core.refactoring.Messages;
import org.eclipse.ltk.internal.core.refactoring.RefactoringCoreMessages;
public class RenameResourceChange extends ResourceChange {
private final String fNewName;
private final IPath fResourcePath;
private final long fStampToRestore;
private ChangeDescriptor fDescriptor;
public RenameResourceChange(IPath resourcePath, String newName) {
this(resourcePath, newName, IResource.NULL_STAMP);
}
protected RenameResourceChange(IPath resourcePath, String newName, long stampToRestore) {
if (resourcePath == null || newName == null || newName.length() == 0) {
throw new IllegalArgumentException();
}
fResourcePath= resourcePath;
fNewName= newName;
fStampToRestore= stampToRestore;
fDescriptor= null;
setValidationMethod(VALIDATE_NOT_DIRTY);
}
@Override
public ChangeDescriptor getDescriptor() {
return fDescriptor;
}
public void setDescriptor(ChangeDescriptor descriptor) {
fDescriptor= descriptor;
}
@Override
protected IResource getModifiedResource() {
return getResource();
}
@Override
public String getName() {
return Messages.format(RefactoringCoreMessages.RenameResourceChange_name, new String[] { BasicElementLabels.getPathLabel(fResourcePath, false), BasicElementLabels.getResourceName(fNewName) });
}
public String getNewName() {
return fNewName;
}
private IResource getResource() {
return ResourcesPlugin.getWorkspace().getRoot().findMember(fResourcePath);
}
@Override
public Change perform(IProgressMonitor pm) throws CoreException {
try {
pm.beginTask(RefactoringCoreMessages.RenameResourceChange_progress_description, 1);
IResource resource= getResource();
long currentStamp= resource.getModificationStamp();
IPath newPath= renamedResourcePath(fResourcePath, fNewName);
resource.move(newPath, IResource.SHALLOW, pm);
if (fStampToRestore != IResource.NULL_STAMP) {
IResource newResource= ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
newResource.revertModificationStamp(fStampToRestore);
}
String oldName= fResourcePath.lastSegment();
return new RenameResourceChange(newPath, oldName, currentStamp);
} finally {
pm.done();
}
}
private static IPath renamedResourcePath(IPath path, String newName) {
return path.removeLastSegments(1).append(newName);
}
}