How to get Module name file physically belongs to in custom Macro?

I am implementing custom Macro which needs to figure out name of module file physically belongs to.
I am trying to get it inside com.intellij.ide.macro.Macro#expand(com.intellij.openapi.actionSystem.DataContext)

PlatformCoreDataKeys.MODULE.getData(dataContext)

Does not work. It returns module set in run configurations -cp field

VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
Project project = CommonDataKeys.PROJECT.getData(dataContext);
Module module = ModuleUtil.findModuleForFile(file, project);

Does not work, it seems that all *.FILE data keys only return file in editor?

Which file do you expect in the context?

Existing macros like FileNameMacro use the virtual file of the context and AFAIK that’s the file of the current editor, if there’s one.

Only run configurations support macros, if I’m not mistaken.
Each run configuration defines the module to pass to macros, see com.intellij.execution.util.ProgramParametersConfigurator#getModule.
The expansion is handled by com.intellij.execution.util.ProgramParametersConfigurator#configureConfiguration and similar methods.
There are run configurations implementations supporting a module context, and others don’t support it.

I don’t think that you can override the module or the file in the context.

Which file do you expect in the context?

I need file from the run configuration. Be it file containing main method, or file containing junit test being run. It does not necessarily need to be in context. Maybe there is some other way to get that file or module name directly?

Is your macro specific to Java run configurations?

Even with Java, there’s not always a file, e.g. when you run tests for a package.

As far as I know, there’s no single file, which is always available in a run configuration or to macros.

If you know which configurations you support, you may be lucky to fetch the run configuration from the context, e.g. similar to this intellij-community/platform/lang-api/src/com/intellij/execution/actions/ConfigurationContext.java at bc115671b83d9ce17980969af147db948c1fd688 · JetBrains/intellij-community · GitHub

But I didn’t test this and it’s not generic…

Is your macro specific to Java run configurations?
Yes, bare minimum is junit. Everything else would be a plus.

Even with Java, there’s not always a file, e.g. when you run tests for a package.
Well package normally is in some module so I was hoping I could get module from package/directory from context/run_configuration somehow…

RunConfiguration configuration = RunConfiguration.DATA_KEY.getData(dataContext);
ExecutionEnvironment environment = ExecutionDataKeys.EXECUTION_ENVIRONMENT.getData(dataContext);

both are null when in macro. Once that method is hit EXECUTION_ENVIRONMENT is filled so I will try to see where and how it is added.

I am starting to suspect I will need to look for a way to do this via something else than macros :confused: