Package selection and path extraction

Hey all,

I'm working on a plugin that will generate some code into a Java package selected by the user. The plugin is not invoked by right clicking a specific path on the project's file tree, but rather from the tools menu, which later allows selection of the target package using PackageChooserDialog.

For this purpose, I would need to extract two values, one would be the qualified name for the package, which as you probably know is available via dialog.getSelectedPackage().getQualifiedName(), and the other one would be the root path of that package.

For example, the following:


Returns something like this for a selected package in an Android project:


I would need the following value in this case:


Sure, this seems fairly easy:

PsiPackage selectedPackage = dialog.getSelectedPackage();
PsiDirectory[] directories = selectedPackage.getDirectories();
(directories.length > 0) {
  String path = directories[0].getVirtualFile().getPath();
  // Horrible solution for figuring out the package root path
String qualifiedName = selectedPackage.getQualifiedName();
String packageRootPath = StringUtils.removeEndIgnoreCase(path,
qualifiedName.replace('.', File.separatorChar));

But for some reason it feels like there's a much better way of doing this :)

Would appreciate any advice.

Thanks a lot!

Comment actions Permalink

You could use this method:

PsiDirectory rootDir = com.intellij.psi.util.ClassUtil.sourceRoot(packageDir);

Comment actions Permalink

Marcin, that is perfect.


Comment actions Permalink

You're finding this operation difficult because it doesn't make sense from the point of view of IntelliJ IDEA's model. What you're trying to obtain is a source root. You cannot extract the source root from a package because a package corresponds to multiple directories in different source roots. You can of course take the first directory from the list of directories corresponding to a package, but this almost amounts to picking a random module and source root from within the project; there is absolutely no guaranteed order in which PsiPackage.getDirectories() returns the directories.

What IntelliJ IDEA itself does in similar situations, and what you should consider doing as well, is letting the user choose explicity which source root they would like to use.

Comment actions Permalink

Makes sense, thanks for clearing this out.


Please sign in to leave a comment.