下面列出了com.intellij.psi.util.PsiElementFilter#com.intellij.openapi.command.WriteCommandAction 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void doOptimize(Project project) {
DumbService.getInstance(project).runWhenSmart((DumbAwareRunnable) () -> new WriteCommandAction(project) {
@Override
protected void run(@NotNull Result result) {
for (VirtualFile virtualFile : virtualFiles) {
try {
PsiJavaFile javaFile = (PsiJavaFile) PsiManager.getInstance(project).findFile(virtualFile);
if (javaFile != null) {
CodeStyleManager.getInstance(project).reformat(javaFile);
JavaCodeStyleManager.getInstance(project).optimizeImports(javaFile);
JavaCodeStyleManager.getInstance(project).shortenClassReferences(javaFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
virtualFiles.clear();
}
}.execute());
}
public void revert() throws IOException {
try {
new WriteCommandAction(myProject, getCommandName()) {
@Override
protected void run(Result objectResult) throws Throwable {
myGateway.saveAllUnsavedDocuments();
doRevert();
myGateway.saveAllUnsavedDocuments();
}
}.execute();
}
catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException)cause;
}
throw e;
}
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
final Document document = editor.getDocument();
CaretModel caretModel = editor.getCaretModel();
final int offset = caretModel.getOffset();
new PopupChooserBuilder(QUERY_OPERATOR_LIST)
.setMovable(false)
.setCancelKeyEnabled(true)
.setItemChoosenCallback(new Runnable() {
public void run() {
final String selectedQueryOperator = (String) QUERY_OPERATOR_LIST.getSelectedValue();
if (selectedQueryOperator == null) return;
new WriteCommandAction(project, MONGO_OPERATOR_COMPLETION) {
@Override
protected void run(@NotNull Result result) throws Throwable {
document.insertString(offset, selectedQueryOperator);
}
}.execute();
}
})
.createPopup()
.showInBestPositionFor(editor);
}
public void testUnsavedDocument_DoNotGC() throws Exception {
final VirtualFile file = createFile();
Document document = myDocumentManager.getDocument(file);
int idCode = System.identityHashCode(document);
assertNotNull(file.toString(), document);
WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
@Override
public void run() {
myDocumentManager.getDocument(file).insertString(0, "xxx");
}
});
//noinspection UnusedAssignment
document = null;
System.gc();
System.gc();
document = myDocumentManager.getDocument(file);
assertEquals(idCode, System.identityHashCode(document));
}
private void buildModule() {
try {
copyFileFromResources("/toy-project/src/NopolExample.java", this.BASE_PATH_TOY_PROJECT + "/src/nopol_example/NopolExample.java");
copyFileFromResources("/toy-project/test/NopolExampleTest.java", this.BASE_PATH_TOY_PROJECT + "/test/nopol_example/NopolExampleTest.java");
copyFileFromResources("/toy-project/pom.xml", this.BASE_PATH_TOY_PROJECT + "/pom.xml");
} catch (IOException e) {
e.printStackTrace();
}
WriteCommandAction.runWriteCommandAction(project, () -> {
try {
ModuleManager.getInstance(project).loadModule(this.BASE_PATH_TOY_PROJECT + "/toy-project.iml");
project.getBaseDir().refresh(false, true);
} catch (Exception ignored) {
ignored.printStackTrace();
}
});
}
public static void doIntentionTest(@Nonnull final CodeInsightTestFixture fixture, @NonNls final String action,
@Nonnull final String before, @Nonnull final String after) {
fixture.configureByFile(before);
List<IntentionAction> availableIntentions = fixture.getAvailableIntentions();
final IntentionAction intentionAction = findIntentionByText(availableIntentions, action);
if (intentionAction == null) {
Assert.fail("Action not found: " + action + " in place: " + fixture.getElementAtCaret() + " among " + availableIntentions);
}
new WriteCommandAction(fixture.getProject()) {
@Override
protected void run(Result result) throws Throwable {
fixture.launchAction(intentionAction);
}
}.execute();
fixture.checkResultByFile(after, false);
}
private void performMultipleRefactoringsTest(List<Integer> eliminationGroupSizes) {
initTest();
eliminationGroupSizes = new ArrayList<>(eliminationGroupSizes);
Project project = myFixture.getProject();
while (eliminationGroupSizes.size() != 0) {
Set<TypeCheckEliminationGroup> eliminationGroups =
JDeodorantFacade.getTypeCheckEliminationRefactoringOpportunities(
new ProjectInfo(new AnalysisScope(project), false),
fakeProgressIndicator
);
assertEquals(eliminationGroupSizes.size(), eliminationGroups.size());
TypeCheckEliminationGroup eliminationGroup = eliminationGroups.iterator().next();
assertEquals(eliminationGroupSizes.get(0).intValue(), eliminationGroup.getCandidates().size());
WriteCommandAction.runWriteCommandAction(
project,
() -> createRefactoring(eliminationGroup.getCandidates().get(0), project).apply()
);
if (eliminationGroupSizes.get(0) == 1) {
eliminationGroupSizes.remove(0);
} else {
eliminationGroupSizes.set(0, eliminationGroupSizes.get(0) - 1);
}
}
checkTest();
}
private void doTest(String... files) throws Exception {
myFixture.configureByFiles(files);
if (IdeaTarget.IS_VERSION_17_COMPATIBLE) {
// The implementation of finishLookup in IDEA 2017 requires that it run OUTSIDE of a write command,
// while previous versions require that is run inside of one.
expandTemplate(myFixture.getEditor());
}
WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() {
@Override
public void run() {
if (!IdeaTarget.IS_VERSION_17_COMPATIBLE) {
expandTemplate(myFixture.getEditor());
}
CodeStyleManager.getInstance(myFixture.getProject()).reformat(myFixture.getFile());
}
});
myFixture.getEditor().getSelectionModel().removeSelection();
myFixture.checkResultByFile(getTestName(false) + "_after.hx");
}
protected PsiFile addFileToProject(final String rootPath, final String relativePath, final String fileText) {
return new WriteCommandAction<PsiFile>(getProject()) {
@Override
protected void run(Result<PsiFile> result) throws Throwable {
try {
if (myTempDirFixture instanceof LightTempDirTestFixtureImpl) {
final VirtualFile file = myTempDirFixture.createFile(relativePath, fileText);
result.setResult(PsiManager.getInstance(getProject()).findFile(file));
}
else {
result.setResult(((HeavyIdeaTestFixture)myProjectFixture).addFileToProject(rootPath, relativePath, fileText));
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
finally {
((PsiModificationTrackerImpl)PsiManager.getInstance(getProject()).getModificationTracker()).incCounter();
}
}
}.execute().getResultObject();
}
@Override
public void build(PsiFile psiFile, Project project1, Editor editor) {
if (psiFile == null) return;
WriteCommandAction.runWriteCommandAction(project1, () -> {
if (editor == null) return;
Project project = editor.getProject();
if (project == null) return;
PsiElement mouse = psiFile.findElementAt(editor.getCaretModel().getOffset());
PsiClass psiClass = PsiTreeUtil.getParentOfType(mouse, PsiClass.class);
if (psiClass == null) return;
if (psiClass.getNameIdentifier() == null) return;
String className = psiClass.getNameIdentifier().getText();
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
build(editor, mouse, elementFactory, project, psiClass, psiFile, className);
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
styleManager.optimizeImports(psiFile);
styleManager.shortenClassReferences(psiClass);
});
}
private void runActivityLater(Project project) {
LOG.info("run Js library manager");
Optional<VirtualFile> bsConfigFileOptional = ORProjectManager.findFirstBsConfigurationFile(project);
if (bsConfigFileOptional.isPresent()) {
VirtualFile bsConfigFile = bsConfigFileOptional.get();
LOG.debug("bucklescript config file", bsConfigFile);
String baseDir = "file://" + bsConfigFile.getParent().getPath() + "/node_modules/";
List<VirtualFile> sources = new ArrayList<>(readBsConfigDependencies(project, baseDir, bsConfigFile));
JSLibraryManager jsLibraryManager = JSLibraryManager.getInstance(project);
ScriptingLibraryModel bucklescriptModel = jsLibraryManager.getLibraryByName(LIB_NAME);
if (bucklescriptModel == null) {
LOG.debug("Creating js library", LIB_NAME);
jsLibraryManager.createLibrary(LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY, PROJECT, true);
} else {
LOG.debug("Updating js library", LIB_NAME);
jsLibraryManager.updateLibrary(LIB_NAME, LIB_NAME, sources.toArray(new VirtualFile[0]), EMPTY_ARRAY, EMPTY_STRING_ARRAY);
}
WriteCommandAction.runWriteCommandAction(project, (Runnable) jsLibraryManager::commitChanges);
}
}
@Override
public void projectOpened(@NotNull Project project) {
if (!(FileTypeManager.getInstance().getFileTypeByExtension("xlf") instanceof XmlFileType)) {
WriteCommandAction.runWriteCommandAction(ProjectManager.getInstance().getOpenProjects()[0], () -> {
FileTypeManager.getInstance().associateExtension(XmlFileType.INSTANCE, "xlf");
ApplicationManager.getApplication().invokeLater(() -> {
Notification notification = GROUP_DISPLAY_ID_INFO.createNotification(
"TYPO3 CMS Plugin",
"XLF File Type Association",
"The XLF File Type was re-assigned to XML to prevent errors with the XLIFF Plugin and allow autocompletion. Please re-index your projects.",
NotificationType.INFORMATION
);
Project[] projects = ProjectManager.getInstance().getOpenProjects();
Notifications.Bus.notify(notification, projects[0]);
});
});
}
}
/**
* This function should be executed (remove the underscore) if the current results are correct (manual testing).
*
* @throws Exception
*/
public void _testResultGenerator() throws Exception {
for (int binarySettings = 0; binarySettings < 128; ++binarySettings) {
tearDown();
setUp();
myFixture.configureByFiles("/generated/TestData.csv");
initCsvCodeStyleSettings(binarySettings);
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
}
}.execute();
try (PrintWriter writer = new PrintWriter(getTestDataPath() + String.format("/generated/TestResult%08d.csv", binarySettings))
) {
writer.print(myFixture.getFile().getText());
}
}
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
logger.debug("Loading sample!");
final Project project = anActionEvent.getProject();
final PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);
VirtualFile sample = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
project, null);
if (sample == null)
return;
try {
final String text = new String(sample.contentsToByteArray(), sample.getCharset());
new WriteCommandAction.Simple(project, psiFile) {
@Override
protected void run() throws Throwable {
document.setText(text);
}
}.execute();
} catch (Exception e) {
logger.error(e);
}
}
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) {
// See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary.
boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> {
try {
if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) {
return true;
}
}
catch (Exception e) {
LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e);
}
return false;
});
if (!couldEnsureLocationExists) {
String msg =
"Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path.";
Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project");
return false;
}
return true;
}
public void testError526() {
//TODO disable assertions for the moment
RecursionManager.disableMissedCacheAssertions(myFixture.getProjectDisposable());
PsiFile psiFile = loadToPsiFile(getTestName(false) + ".java");
assertNotNull(psiFile);
PsiClass psiClass = PsiTreeUtil.getParentOfType(psiFile.findElementAt(myFixture.getCaretOffset()), PsiClass.class);
assertNotNull(psiClass);
// call augmentprovider first time
final PsiMethod[] psiClassMethods = psiClass.getMethods();
assertEquals(8, psiClassMethods.length);
// change something to trigger cache drop
WriteCommandAction.writeCommandAction(getProject(), psiFile).compute(() ->
{
psiClass.getModifierList().addAnnotation("java.lang.SuppressWarnings");
return true;
}
);
// call augment provider second time
final PsiMethod[] psiClassMethods2 = psiClass.getMethods();
assertArrayEquals(psiClassMethods, psiClassMethods2);
}
@Override
public void applyFix(@NotNull Project project, PsiFile file, @Nullable Editor editor) {
Runnable runnable = new Runnable() {
@Override
public void run() {
SQFPsiCommand commandElement = commandPointer.getElement();
if (commandElement == null) {
return;
}
for (String command : SQFStatic.COMMANDS_SET) {
if (command.equalsIgnoreCase(commandElement.getText())) {
SQFPsiCommand c = PsiUtil.createElement(project, command, SQFFileType.INSTANCE, SQFPsiCommand.class);
if (c == null) {
return;
}
commandElement.replace(c);
return;
}
}
throw new IllegalStateException("command '" + commandElement.getText() + "' should have been matched");
}
};
WriteCommandAction.runWriteCommandAction(project, runnable);
}
/**
* Create package in the directory specific with a name
*
* @param parent package when create a subpackage
* @param packageName package name
* @return
*/
public static PsiDirectory createDirectory(PsiDirectory parent, String packageName) {
directoryCreated = null;
// Search subpackage with the same name
for (PsiDirectory dir : parent.getSubdirectories()) {
if (dir.getName().equalsIgnoreCase(packageName)) {
directoryCreated = dir;
break;
}
}
// When the search not found a package with the same name, create a subdirectory
if (directoryCreated == null) {
runnable = () -> directoryCreated = parent.createSubdirectory(packageName);
WriteCommandAction.runWriteCommandAction(project, runnable);
}
return directoryCreated;
}
private static void addProjectLibrary(final Module module,
final ModifiableRootModel model,
final String libName,
final VirtualFile... classesRoots) {
new WriteCommandAction.Simple(module.getProject()) {
@Override
protected void run() throws Throwable {
final LibraryTable libraryTable = ProjectLibraryTable.getInstance(module.getProject());
final Library library = libraryTable.createLibrary(libName);
final Library.ModifiableModel libraryModel = library.getModifiableModel();
for (VirtualFile root : classesRoots) {
libraryModel.addRoot(root, BinariesOrderRootType.getInstance());
}
libraryModel.commit();
model.addLibraryEntry(library);
final OrderEntry[] orderEntries = model.getOrderEntries();
OrderEntry last = orderEntries[orderEntries.length - 1];
System.arraycopy(orderEntries, 0, orderEntries, 1, orderEntries.length - 1);
orderEntries[0] = last;
model.rearrangeOrderEntries(orderEntries);
}
}.execute().throwException();
}
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
final PsiAnnotation myAnnotation = (PsiAnnotation) startElement;
final Editor editor = CodeInsightUtil.positionCursor(project, psiFile, myAnnotation);
if (editor != null) {
WriteCommandAction.writeCommandAction(project, psiFile).run(() ->
{
final PsiNameValuePair valuePair = selectAnnotationAttribute(myAnnotation);
if (null != valuePair) {
// delete this parameter
valuePair.delete();
}
if (null != myNewValue) {
//add new parameter
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myAnnotation.getProject());
PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText("@" + myAnnotation.getQualifiedName() + "(" + myName + "=" + myNewValue + ")", myAnnotation.getContext());
final PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes();
myAnnotation.setDeclaredAttributeValue(attributes[0].getName(), attributes[0].getValue());
}
UndoUtil.markPsiFileForUndo(psiFile);
}
);
}
}
public static void doFormattingTest(@Nonnull final CodeInsightTestFixture fixture,
@Nonnull final String before, @Nonnull final String after) {
fixture.configureByFile(before);
new WriteCommandAction(fixture.getProject()) {
@Override
protected void run(Result result) throws Throwable {
CodeStyleManager.getInstance(fixture.getProject()).reformat(fixture.getFile());
}
}.execute();
fixture.checkResultByFile(after, false);
}
protected void write(@NotNull final Project project, @NotNull final PhpClass phpClass, @NotNull String className) {
if(!className.endsWith("Command")) {
className += "Command";
}
final String finalClassName = className;
new WriteCommandAction(project) {
@Override
protected void run(@NotNull Result result) throws Throwable {
PsiElement bundleFile = null;
try {
bundleFile = PhpBundleFileFactory.createBundleFile(phpClass, "command", "Command\\" + finalClassName, new HashMap<String, String>() {{
String name = phpClass.getName();
if(name.endsWith("Bundle")) {
name = name.substring(0, name.length() - "Bundle".length());
}
put("name", StringUtils.underscore(name) + ":" + StringUtils.underscore(finalClassName));
}});
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error:" + e.getMessage());
return;
}
new OpenFileDescriptor(getProject(), bundleFile.getContainingFile().getVirtualFile(), 0).navigate(true);
}
@Override
public String getGroupID() {
return "Create Command";
}
}.execute();
}
private void execute(final Runnable readAction, final Runnable writeAction) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
readAction.run();
}
}, title, true, myProject);
new WriteCommandAction(myProject, title) {
protected void run(Result result) throws Throwable {
writeAction.run();
}
}.execute();
}
@Nonnull
public static VirtualFile copyFileInCommand(@Nonnull Project project, @Nonnull final VirtualFile file,
@Nonnull final VirtualFile newParent, @Nonnull final String newName) {
return new WriteCommandAction<VirtualFile>(project) {
@Override
protected void run(@Nonnull Result<VirtualFile> result) throws Throwable {
try {
result.setResult(file.copy(this, newParent, newName));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}.execute().getResultObject();
}
@Override
protected void runTest() throws Throwable {
if (isWriteActionRequired()) {
new WriteCommandAction(myFixture.getProject()) {
@Override
protected void run(@NotNull Result result) throws Throwable {
doRunTest();
}
}.execute();
} else {
doRunTest();
}
}
public void testInGlobDirectory() throws IOException {
new WriteCommandAction(getProject()) {
@Override
protected void run(@NotNull Result result) throws IOException {
myFixture.getTempDirFixture().findOrCreateDir("glob1").createChildData(this, "fileName1.txt");
myFixture.getTempDirFixture().findOrCreateDir("glob2").createChildData(this, "fileName2.txt");
}
}.execute();
doTestVariants("*/fileN<caret>", "fileName1.txt", "fileName2.txt");
}
@Override
public void setItem(Object anObject) {
if (anObject == null) anObject = "";
if (anObject.equals(getItem())) return;
final String s = (String)anObject;
new WriteCommandAction(myProject) {
@Override
protected void run(Result result) throws Throwable {
getDocument().setText(s);
}
}.execute();
final Editor editor = getEditor();
if (editor != null) editor.getCaretModel().moveToOffset(s.length());
}
public static void create(final @NotNull Editor editor, @NotNull Collection<String> services, final @NotNull Callback callback) {
final JBList<String> list = new JBList<>(services);
JBPopupFactory.getInstance().createListPopupBuilder(list)
.setTitle("Symfony: Service Suggestion")
.setItemChoosenCallback(() -> new WriteCommandAction.Simple(editor.getProject(), "Service Suggestion Insert") {
@Override
protected void run() {
callback.insert((String) list.getSelectedValue());
}
}.execute())
.createPopup()
.showInBestPositionFor(editor);
}
public static boolean checkFileExist(@Nullable PsiDirectory targetDirectory, int[] choice, PsiFile file, String name, String title) {
if (targetDirectory == null) return false;
final PsiFile existing = targetDirectory.findFile(name);
if (existing != null && !existing.equals(file)) {
int selection;
if (choice == null || choice[0] == -1) {
String message = String.format("File '%s' already exists in directory '%s'", name, targetDirectory.getVirtualFile().getPath());
String[] options = choice == null ? new String[]{"Overwrite", "Skip"} : new String[]{"Overwrite", "Skip", "Overwrite for all", "Skip for all"};
selection = Messages.showDialog(message, title, options, 0, Messages.getQuestionIcon());
}
else {
selection = choice[0];
}
if (choice != null && selection > 1) {
choice[0] = selection % 2;
selection = choice[0];
}
if (selection == 0 && file != existing) {
WriteCommandAction.writeCommandAction(targetDirectory.getProject()).withName(title).run(() -> existing.delete());
}
else {
return true;
}
}
return false;
}
@Override
public void checkResultByFile(final String expectedFile, final boolean ignoreTrailingWhitespaces) {
assertInitialized();
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Exception {
checkResultByFile(expectedFile, getHostFile(), ignoreTrailingWhitespaces);
}
}.execute().throwException();
}