How to get a PsiFile from a Module?

Answered

Given a project with several modules - each of which could contain a certain identically named file (say an xml config file) - how do I get the file given the module?

I know how to do this if I have the Artifact:

PackagingElementResolvingContext context = ArtifactManager.getInstance(project).getResolvingContext();
VirtualFile descriptorFile = ArtifactUtil.findSourceFileByOutputPath(artifact, "my_config.xml", context);
XmlFile myConfig = (XmlFile) PsiManager.getInstance(project).findFile(descriptorFile);

How do I do something similar given a Module?

Note: I know that given a Module I can get a list of Artifacts containing the module output. However this doesn't seem ideal as I know that I don't need to search each Artifact for the desired config file.

3 comments

There's no one-to-one binding between modules and files (and artifacts). You should find the virtual file (e.g. LocalFileSystem.getInstance().findFileByPath) and then use PsiManager to get PsiFile. Module is not needed.

0

Thanks for the quick reply. 

In my use-case, I'm attempting to assemble ModuleDeploymentSources. For each available module in the project, e.g.: 

ModuleManager.getInstance(project).getModules();

I need to check a config file within that module to determine what do with deployment source. Are you saying that this approach is not valid? Could you suggest an alternative - maybe a way to get the root path of the module and then use the LocalFileSystem to load that config as you suggest? Just to be clear, each module may or may not have a certain config file that I need to check. 

0

A module might have a lot of roots of different types, it depends which ones you want. Most likely those are either content or source roots. Both are available from ModuleRootManager.getInstance(module).getContent/SourceRoots. When you have a root, you can use root.findFileByRelativePath().

0

Please sign in to leave a comment.