Run Gradle task from plugin action
Hello,
I'm creating a plugin which will reformat a file via a gradle task (e.g. gradle formatApply <filepath>). What is the preferred way to execute a gradle task in the background from a plugin -- in particular when that task is used to reformat code?
I tried using `GeneralCommandLine` witih `CapturingAnsiEscapesAwareProcessHandler`, but get:
Synchronous execution on EDT: ./gradlew ...
Any help would be appreciated. Thanks!
UPDATE:
I figured out that this works:
GradleExecuteTaskAction.runGradle(myProject, null, Objects.requireNonNull(myProject.getBasePath()),
String.format("-filepath=\"%s\" applyFormatting", fileToProcess.getVirtualFile().getPath()));
The only issue with it is it causes the terminal to pop up with the running command, which some users probably won't want. Any chance there's a way to make this show as an async task with a progress bar rather than the terminal showing?
UPDATE #2:
I got the following to work as well:
ExternalSystemTaskExecutionSettings settings = new ExternalSystemTaskExecutionSettings();
settings.setExternalProjectPath(myProject.getBasePath());
settings.setTaskNames(Collections.singletonList("applyFormatting"));
settings.setScriptParameters(String.format("-filepath=\"%s\"", fileToProcess.getVirtualFile().getPath()));
settings.setVmOptions("");
settings.setExternalSystemIdString(GradleConstants.SYSTEM_ID.getId());
ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID);
However, even though
ProgressExecutionMode.IN_BACKGROUND_ASYNC
is set, the window showing the output of the gradle task and its status still pops up :(
UPDATE #3:
I figured it out! I found a different signature for `runTask`, and if you call `ExternalSystemUtil.runTask` as follows:
ExternalSystemUtil.runTask(settings, DefaultRunExecutor.EXECUTOR_ID, myProject, GradleConstants.SYSTEM_ID,
null, ProgressExecutionMode.IN_BACKGROUND_ASYNC, false);
The gradle task kicks off and runs in the background without the tool window!
Please sign in to leave a comment.
To run a Gradle task from a Kotlin plugin file, you can use the code below:
Before I got to this solution (thanks Ryan!), I spent way too long trying to make live-plugin's runShellScript and GeneralCommandLine work. For some obscure reason, I got the gradle output you would expect, but the task did not actually run.