Rtransat
Rtransat

Reputation: 43

How to create a file from an action event for an IntelliJ plugin?

I'm creating a PhpStorm plugin with IntelliJ IDEA Community Edition and I would like to know how to create a file on disk from a PSIFile or VirtualFile.

Here my code: (The context is an action from NewGroup)

I've tried to use the PsiDirectory.copyFileFrom method to create the file but I have an exception com.intellij.util.IncorrectOperationException: Cannot copy non-physical file: PHP file

package fr.florent.idea.zendgenerator.action.NewGroup;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.util.ResourceUtil;
import com.jetbrains.php.lang.PhpFileType;
import fr.florent.idea.zendgenerator.action.AbstractDumbAwareAction;
import icons.PhpIcons;
import org.jetbrains.annotations.NotNull;

import java.net.URL;

public class CreateQueryAction extends AbstractDumbAwareAction {

    public CreateQueryAction() {
        super("Query", "Create query", PhpIcons.Php_icon);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        URL url = ResourceUtil.getResource(getClass(), "templates", "query.php"); // it contains an empty PHP class
        VirtualFile virtualFile = VfsUtil.findFileByURL(url);

        PsiFile file = PsiFileFactory.getInstance(e.getProject()).createFileFromText(
                virtualFile.getPath(),
                PhpFileType.INSTANCE,
                LoadTextUtil.loadText(virtualFile)
        );

        PsiDirectory directory = LangDataKeys.IDE_VIEW.getData(e.getDataContext()).getOrChooseDirectory();

        directory.copyFileFrom("query.php", file);

        System.out.println("Create query");
    }
}

I would like to have the file created in the project folder from the context of my action.

It will be great if someone can explain the process of creating a file in a IntelliJ plugin. I think the docs is really light.

In my case I would like to have the process to edit the query.php file, rename the class name, add method, properties, doc block and save it to the disk but I don't understand the PSI element.

Upvotes: 0

Views: 2315

Answers (1)

Dmitrii
Dmitrii

Reputation: 3557

You might want to ask this also on JB forum, there's a similar question: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001787320-Create-VirtualFile-or-PsiFile-from-content

The answer is:

final PsiFileFactory factory = PsiFileFactory.getInstance(project);

final PsiFile file = factory.createFileFromText(language, text);

Upvotes: 1

Related Questions