下面列出了怎么用com.intellij.psi.impl.file.PsiDirectoryFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param templateFile Name of the generated file
* @param destinationPath Relative path to the target file system entry
* @param extensionDefinition Extension definition containing all relevant metadata
* @param context Template Context variables
* @param project Project in context
*/
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull TYPO3ExtensionDefinition extensionDefinition, @NotNull Map<String, String> context, Project project) {
String template = readTemplateToString(templateFile, context);
VirtualFile targetDirectory = getOrCreateDestinationPath(extensionDefinition.getRootDirectory(), destinationPath);
LanguageFileType fileType = FileTypes.PLAIN_TEXT;
if (templateFile.endsWith(".php")) {
fileType = PhpFileType.INSTANCE;
}
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
CodeStyleManager.getInstance(project).reformat(fileFromText);
return PsiDirectoryFactory
.getInstance(project)
.createDirectory(targetDirectory)
.add(fileFromText);
}
/**
* @param templateFile Name of the generated file
* @param destinationPath Relative path to the target file system entry
* @param extensionRootDirectory Extension definition containing all relevant metadata
* @param context Template Context variables
* @param project Project in context
*/
public static PsiElement fromTemplate(@NotNull String templateFile, @NotNull String destinationPath, @NotNull String destinationFileName, @NotNull PsiDirectory extensionRootDirectory, @NotNull Map<String, String> context, Project project) {
String template = readTemplateToString(templateFile, context);
VirtualFile targetDirectory = getOrCreateDestinationPath(extensionRootDirectory.getVirtualFile(), destinationPath);
LanguageFileType fileType = FileTypes.PLAIN_TEXT;
if (templateFile.endsWith(".php")) {
fileType = PhpFileType.INSTANCE;
}
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(destinationFileName, fileType, template);
CodeStyleManager.getInstance(project).reformat(fileFromText);
return PsiDirectoryFactory
.getInstance(project)
.createDirectory(targetDirectory)
.add(fileFromText);
}
public static PsiDirectory createDirectory(Project project, String title, String description) {
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
descriptor.setTitle(title);
descriptor.setShowFileSystemRoots(false);
descriptor.setDescription(description);
descriptor.setHideIgnored(true);
descriptor.setRoots(project.getBaseDir());
descriptor.setForcedToUseIdeaFileChooser(true);
VirtualFile file = FileChooser.chooseFile(descriptor, project, project.getBaseDir());
if(Objects.isNull(file)){
Messages.showInfoMessage("Cancel " + title, "Error");
return null;
}
PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(project).createDirectory(file);
if(PsiDirectoryFactory.getInstance(project).isPackage(psiDirectory)){
return psiDirectory;
}else {
Messages.showInfoMessage("请选择正确的 package 路径。", "Error");
return createDirectory(project, title, description);
}
}
public Set<String> getModules() {
Set<String> modules = new HashSet<String>();
PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
if (isAndroidProject(baseDir)) {
Logger.debug(project.getName() + " is an Android project");
PsiDirectory[] dirs = baseDir.getSubdirectories();
for (PsiDirectory dir : dirs) {
if (!dir.getName().equals("build") && !dir.getName().equals("gradle")) {
if (isModule(dir)) {
Logger.debug(dir.getName() + " is a Module");
modules.add(dir.getName());
}
}
}
}
Logger.debug(modules.toString());
return modules;
}
public PsiDirectory getResDir(String moduleName) {
PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
PsiDirectory moduleDir = baseDir.findSubdirectory(moduleName);
if (moduleDir != null && moduleDir.isDirectory()) {
PsiDirectory srcDir = moduleDir.findSubdirectory("src");
if (srcDir != null && srcDir.isDirectory()) {
PsiDirectory mainDir = srcDir.findSubdirectory("main");
if (mainDir != null && mainDir.isDirectory()) {
PsiDirectory resDir = mainDir.findSubdirectory("res");
if (resDir != null && resDir.isDirectory()) {
return resDir;
}
}
}
}
return null;
}
@Override
public void create(CodeTemplate template, CodeContext context, Map<String, Object> extraMap){
VelocityContext velocityContext = new VelocityContext(BuilderUtil.transBean2Map(context));
velocityContext.put("serialVersionUID", BuilderUtil.computeDefaultSUID(context.getModel(), context.getFields()));
// $!dateFormatUtils.format($!now,'yyyy-MM-dd')
velocityContext.put("dateFormatUtils", new org.apache.commons.lang.time.DateFormatUtils());
if (extraMap != null && extraMap.size() > 0) {
for (Map.Entry<String, Object> entry: extraMap.entrySet()) {
velocityContext.put(entry.getKey(), entry.getValue());
}
}
String fileName = VelocityUtil.evaluate(velocityContext, template.getFilename());
String subPath = VelocityUtil.evaluate(velocityContext, template.getSubPath());
String temp = VelocityUtil.evaluate(velocityContext, template.getTemplate());
WriteCommandAction.runWriteCommandAction(this.project, () -> {
try {
VirtualFile vFile = VfsUtil.createDirectoryIfMissing(outputPath);
PsiDirectory psiDirectory = PsiDirectoryFactory.getInstance(this.project).createDirectory(vFile);
PsiDirectory directory = subDirectory(psiDirectory, subPath, template.getResources());
// TODO: 这里干啥用的, 没用的话是不是可以删除了
if (JavaFileType.INSTANCE == this.languageFileType) {
PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory);
if (psiPackage != null && !StringUtils.isEmpty(psiPackage.getQualifiedName())) {
extraMap.put(fileName, new StringBuilder(psiPackage.getQualifiedName()).append(".").append(fileName));
}
}
createFile(project, directory, fileName + "." + this.languageFileType.getDefaultExtension(), temp, this.languageFileType);
} catch (Exception e) {
LOGGER.error(StringUtils.getStackTraceAsString(e));
}
});
}
GraphQLConfigDirectoryDialog(@NotNull Project project, List<VirtualFile> configDirectoryCandidates) {
super(project);
final PsiDirectoryFactory factory = PsiDirectoryFactory.getInstance(project);
this.configDirectoryCandidates = configDirectoryCandidates.stream().map(factory::createDirectory).collect(Collectors.toList());
setTitle("Select GraphQL Configuration Folder");
init();
comboBox.requestFocus();
}
void createOrUpdateIntrospectionOutputFile(String schemaText, IntrospectionOutputFormat format, VirtualFile introspectionSourceFile, String outputFileName) {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
final String header;
switch (format) {
case SDL:
header = "# This file was generated based on \"" + introspectionSourceFile.getName() + "\". Do not edit manually.\n\n";
break;
case JSON:
header = "";
break;
default:
throw new IllegalArgumentException("unsupported output format: " + format);
}
String relativeOutputFileName = StringUtils.replaceChars(outputFileName, '\\', '/');
VirtualFile outputFile = introspectionSourceFile.getParent().findFileByRelativePath(relativeOutputFileName);
if (outputFile == null) {
PsiDirectory directory = PsiDirectoryFactory.getInstance(myProject).createDirectory(introspectionSourceFile.getParent());
CreateFileAction.MkDirs dirs = new CreateFileAction.MkDirs(relativeOutputFileName, directory);
outputFile = dirs.directory.getVirtualFile().createChildData(introspectionSourceFile, dirs.newName);
}
outputFile.putUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_JSON, true);
final FileEditor[] fileEditors = FileEditorManager.getInstance(myProject).openFile(outputFile, true, true);
if (fileEditors.length > 0) {
final FileEditor fileEditor = fileEditors[0];
setEditorTextAndFormatLines(header + schemaText, fileEditor);
} else {
Notifications.Bus.notify(new Notification("GraphQL", "GraphQL Error", "Unable to open an editor for '" + outputFile.getPath() + "'", NotificationType.ERROR));
}
} catch (IOException ioe) {
Notifications.Bus.notify(new Notification("GraphQL", "GraphQL IO Error", "Unable to create file '" + outputFileName + "' in directory '" + introspectionSourceFile.getParent().getPath() + "': " + ioe.getMessage(), NotificationType.ERROR));
}
});
}
public @Nullable String getCurrentModule() {
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
String path = FileDocumentManager.getInstance().getFile(editor.getDocument()).getPath();
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.substring(0,path.indexOf("/src")));
if (virtualFile!= null && virtualFile.isDirectory()) {
PsiDirectory directory = PsiDirectoryFactory.getInstance(project).createDirectory(virtualFile);
if (isModule(directory)) {
return directory.getName();
}
}
return null;
}
public PsiDirectory getOrCreateDrawableDir(String moduleName,String dirName) {
PsiDirectory baseDir = PsiDirectoryFactory.getInstance(project).createDirectory(project.getBaseDir());
PsiDirectory moduleDir = baseDir.findSubdirectory(moduleName);
if (moduleDir != null) {
PsiDirectory srcDir = moduleDir.findSubdirectory("src");
if (srcDir == null) {
srcDir = moduleDir.createSubdirectory("src");
Logger.debug("Creating dir :" + srcDir.getName());
}
PsiDirectory mainDir = srcDir.findSubdirectory("main");
if (mainDir == null) {
mainDir = srcDir.createSubdirectory("main");
Logger.debug("Creating dir :" + mainDir.getName());
}
PsiDirectory resDir = mainDir.findSubdirectory("res");
if (resDir == null) {
resDir = mainDir.createSubdirectory("res");
Logger.debug("Creating dir :" + resDir.getName());
}
PsiDirectory drawableDir = resDir.findSubdirectory(dirName);
if (drawableDir == null) {
drawableDir = resDir.createSubdirectory(dirName);
Logger.debug("Creating dir :" + drawableDir.getName());
}
return drawableDir;
}
return null;
}
@NotNull
public static PsiElement createBundleFile(@NotNull PhpClass bundleClass, @NotNull String template, @NotNull String className, Map<String, String> vars) throws Exception {
VirtualFile directory = bundleClass.getContainingFile().getContainingDirectory().getVirtualFile();
if(fileExists(directory, new String[] {className})) {
throw new Exception("File already exists");
}
String COMPILER_TEMPLATE = "/fileTemplates/" + template + ".php";
String fileTemplateContent = getFileTemplateContent(COMPILER_TEMPLATE);
if(fileTemplateContent == null) {
throw new Exception("Template content error");
}
String[] split = className.split("\\\\");
String ns = bundleClass.getNamespaceName();
String join = StringUtils.join(Arrays.copyOf(split, split.length - 1), "/");
vars.put("ns", (ns.startsWith("\\") ? ns.substring(1) : ns) + join.replace("/", "\\"));
vars.put("class", split[split.length - 1]);
for (Map.Entry<String, String> entry : vars.entrySet()) {
fileTemplateContent = fileTemplateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
}
VirtualFile compilerDirectory = getAndCreateDirectory(directory, join);
if(compilerDirectory == null) {
throw new Exception("Directory creation failed");
}
Project project = bundleClass.getProject();
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(split[split.length - 1] + ".php", PhpFileType.INSTANCE, fileTemplateContent);
CodeStyleManager.getInstance(project).reformat(fileFromText);
return PsiDirectoryFactory.getInstance(project).createDirectory(compilerDirectory).add(fileFromText);
}
private void genStructure(PageModel pageModel) {
Project project = directory.getProject();
PsiFileFactory factory = PsiFileFactory.getInstance(project);
PsiDirectoryFactory directoryFactory =
PsiDirectoryFactory.getInstance(directory.getProject());
String packageName = directoryFactory.getQualifiedName(directory, true);
FileSaver fileSaver = new IDEFileSaver(factory, directory, DartFileType.INSTANCE);
fileSaver.setListener(fileName -> {
int ok = Messages.showOkCancelDialog(
textResources.getReplaceDialogMessage(fileName),
textResources.getReplaceDialogTitle(), "OK", "NO",
UIUtil.getQuestionIcon());
return ok == 0;
});
final String moduleName =
FileIndexFacade.getInstance(project).getModuleForFile(directory.getVirtualFile()).getName();
Map<String, Object> rootMap = new HashMap<String, Object>();
rootMap.put("ProjectName", moduleName);
rootMap.put("PageType", pageModel.pageType);
if (pageModel.pageType.equals(CUSTOMSCROLLVIEW)) {
rootMap.put("GenerateCustomScrollView", true);
} else {
rootMap.put("GenerateCustomScrollView", false);
}
rootMap.put("PageName", pageModel.pageName);
rootMap.put("ModelEntryName", pageModel.modelName);
rootMap.put("GenerateListView", pageModel.genListView);
rootMap.put("GenerateBottomTabBar", pageModel.genBottomTabBar);
rootMap.put("GenerateAppBar", pageModel.genAppBar);
rootMap.put("GenerateDrawer", pageModel.genDrawer);
rootMap.put("GenerateTopTabBar", pageModel.genTopTabBar);
rootMap.put("GenerateWebView", pageModel.genWebView);
rootMap.put("GenerateActionButton", pageModel.genActionButton);
rootMap.put("viewModelQuery", pageModel.viewModelQuery);
rootMap.put("viewModelGet", pageModel.viewModelGet);
rootMap.put("viewModelCreate", pageModel.viewModelCreate);
rootMap.put("viewModelUpdate", pageModel.viewModelUpdate);
rootMap.put("viewModelDelete", pageModel.viewModelDelete);
rootMap.put("GenSliverFixedExtentList", pageModel.genSliverFixedList);
rootMap.put("GenSliverGrid", pageModel.genSliverGrid);
rootMap.put("GenSliverToBoxAdapter", pageModel.genSliverToBoxAdapter);
rootMap.put("FabInAppBar", pageModel.genSliverFab);
rootMap.put("GenSliverTabBar", pageModel.genSliverTabBar);
rootMap.put("GenSliverTabView", pageModel.genSliverTabView);
rootMap.put("IsCustomWidget", pageModel.isCustomWidget);
if (pageModel.genActionButton) {
rootMap.put("HasActionSearch", pageModel.hasActionSearch);
rootMap.put("ActionList", pageModel.actionList);
rootMap.put("ActionBtnCount", pageModel.actionList.size());
} else {
rootMap.put("HasActionSearch", false);
rootMap.put("ActionList", new ArrayList<String>());
rootMap.put("ActionBtnCount", 0);
}
if (!pageModel.isUIOnly) {
for (ClassModel classModel : pageModel.classModels) {
if (classModel.getName().equals(pageModel.modelName)) {
rootMap.put("genDatabase", classModel.isGenDBModule());
if (classModel.getUniqueField() != null) {
rootMap.put("clsUNName", classModel.getUniqueField());
rootMap.put("clsUNNameType", classModel.getUniqueFieldType());
}
}
generateModelEntry(classModel, rootMap);
}
generateRepository(rootMap);
generateRedux(rootMap);
}
generateFeature(rootMap, pageModel.isCustomWidget, pageModel.genSliverTabView);
}
@Override
public void onModelsReady(List<ClassModel> data, String singleFileName, int annotationsType) {
AnnotationGenerator annotations = null;
switch (annotationsType) {
case 1:
annotations = new GsonAnnotations();
break;
case 2:
annotations = new FastJsonAnnotation();
break;
case 3:
annotations = new MoshiAnnotations();
break;
case 4:
annotations = new JacksonAnnotations();
break;
}
Project project = directory.getProject();
PsiFileFactory factory = PsiFileFactory.getInstance(project);
PsiDirectoryFactory directoryFactory = PsiDirectoryFactory.getInstance(directory.getProject());
String packageName = directoryFactory.getQualifiedName(directory, true);
FileSaver fileSaver = new IDEFileSaver(factory, directory, KotlinFileType.INSTANCE);
fileSaver.setListener(fileName -> {
int ok = Messages.showOkCancelDialog(
textResources.getReplaceDialogMessage(fileName),
textResources.getReplaceDialogTitle(),
UIUtil.getQuestionIcon());
return ok == 0;
});
SourceFilesGenerator generator;
if (singleFileName == null) {
generator = new MultipleFilesGenerator(fileSaver, languageResolver, annotations);
} else {
generator = new SingleFileGenerator(singleFileName, languageResolver, annotations, fileSaver);
}
generator.setListener(filesCount ->
NotificationsHelper.showNotification(directory.getProject(),
textResources.getGeneratedFilesMessage(filesCount))
);
generator.generateFiles(packageName, data);
}
public static void createContract(AnActionEvent e, EditEntity editEntity) {
Project project = e.getProject();
PsiDirectory moduleDir = PsiDirectoryFactory.getInstance(project).createDirectory(e.getData(PlatformDataKeys.VIRTUAL_FILE));
GlobalSearchScope searchScope = GlobalSearchScope.allScope(project);
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
//create package and class
String contractName = editEntity.getContractName() + "Contract";
String modelName = editEntity.getContractName() + "Model";
String presenterName = editEntity.getContractName() + "Presenter";
PsiClass classContract ;
PsiClass classPresenter;
PsiClass classModel ;
PsiClass classView ;
if (editEntity.isSinglePackage())
{
String packageName = editEntity.getContractName().toLowerCase();
classContract = createClass(moduleDir, packageName, contractName);
classPresenter = createClass(moduleDir, packageName, presenterName);
classModel = createClass(moduleDir, packageName, modelName);
classView = createClass(moduleDir, packageName, editEntity.getViewName());
} else
{
classContract = createClass(moduleDir, PACKAGE_CONTRACT, contractName);
classPresenter = createClass(moduleDir, PACKAGE_PRESENTER, presenterName);
classModel = createClass(moduleDir, PACKAGE_MODEL, modelName);
classView = createOrGetView(moduleDir, editEntity);
}
//create view,presenter,model interface
PsiClass viewInterface = factory.createInterface("View");
PsiClass presenterInterface = factory.createInterface("Presenter");
PsiClass modelInterface = factory.createInterface("Model");
viewInterface.getModifierList().setModifierProperty("protect", true);
presenterInterface.getModifierList().setModifierProperty("protect", true);
modelInterface.getModifierList().setModifierProperty("protect", true);
importContractClass(project, classContract, editEntity.getViewParent());
importContractClass(project, classContract, editEntity.getPresenterParent());
importContractClass(project, classContract, editEntity.getPresenterParent());
//add parent interface class
extendsClass(factory, searchScope, viewInterface, editEntity.getViewParent());
extendsClass(factory, searchScope, presenterInterface, editEntity.getPresenterParent());
extendsClass(factory, searchScope, modelInterface, editEntity.getModelParent());
//add method to view,presenter,model interface
addMethodToClass(project, viewInterface, editEntity.getView(), false);
addMethodToClass(project, presenterInterface, editEntity.getPresenter(), false);
addMethodToClass(project, modelInterface, editEntity.getModel(), false);
//add view,presenter,model Interface to Contract
classContract.add(viewInterface);
classContract.add(presenterInterface);
classContract.add(modelInterface);
PsiImportStatement importStatement = factory.createImportStatement(classContract);
((PsiJavaFile) classPresenter.getContainingFile()).getImportList().add(importStatement);
((PsiJavaFile) classModel.getContainingFile()).getImportList().add(importStatement);
((PsiJavaFile) classView.getContainingFile()).getImportList().add(importStatement);
impInterface(factory, searchScope, classPresenter, editEntity.getContractName() + Constant.C_PRESENTER);
impInterface(factory, searchScope, classModel, editEntity.getContractName() + Constant.C_MODEL);
impInterface(factory, searchScope, classView, editEntity.getContractName() + Constant.C_VIEW);
//---------------------------------------
addExtendToPresenter(project, factory, searchScope, classPresenter, contractName, modelName);
addExtendToView(project, factory, searchScope, classView, editEntity.getBaseViewParent(), presenterName);
//---------------------------------------
addMethodToClass(project, classPresenter, editEntity.getPresenter(), true);
addMethodToClass(project, classModel, editEntity.getModel(), true);
addMethodToClass(project, classView, editEntity.getView(), true);
openFiles(project, classContract, classPresenter, classModel, classView);
}
public static PsiDirectory getPsiDirectory(AnActionEvent e)
{
return PsiDirectoryFactory.getInstance(e.getProject()).createDirectory(e.getData(PlatformDataKeys.VIRTUAL_FILE));
}
@Override
public void actionPerformed(AnActionEvent e) {
Project project = e.getProject();
Logger.init("SVG2VectorDrawable", Logger.INFO);
ModulesUtil util = new ModulesUtil(project);
if (!util.isAndroidProject()) {
CommonUtil.showTopic(
project,
"SVG to VectorDrawable",
"Please make sure the current file is in android module",
NotificationType.ERROR);
return;
}
String sourceDir = Configuration.getSvgDir();
if (TextUtils.isEmpty(sourceDir)) {
CommonUtil.showTopic(
project,
"SVG to VectorDrawable",
"SVG source directory not set, please setting it first",
NotificationType.ERROR);
return;
}
String currentModule = util.getCurrentModule();
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByPath(sourceDir);
PsiDirectory svgDir = PsiDirectoryFactory.getInstance(project).createDirectory(vf);
final List<String> files = new ArrayList<String>();
for (PsiFile svg : svgDir.getFiles()) {
if (svg != null && !svg.isDirectory() && svg.getName().toLowerCase().endsWith(".svg")) {
final Transformer transformer = new Transformer.Builder()
.setProject(project)
.setSVG((XmlFile) svg)
.setDpi("nodpi")
.setModule(currentModule)
.setXmlName(CommonUtil.getValidName(svg.getName().split("\\.")[0]) + ".xml")
.create();
Transformer.CallBack callBack = new Transformer.CallBack() {
@Override
public void onComplete(XmlFile dist) {
transformer.writeXmlToDir(dist, false);
files.add(dist.getName());
}
};
transformer.transforming(callBack);
}
}
String msg = "";
for (String s : files) {
msg = msg + s + "<br>";
}
CommonUtil.showTopic(project,
"SVG to VectorDrawable",
"Generating completed.<br>" + msg,
NotificationType.INFORMATION);
}