Requesting user input for JavaExec task

With Gradle 5.1, I’m trying to setup a JavaExec task that asks for the user input. Inside of the block below, the groovy script does correctly ask the user for input but the value that gets assigned to configFile inside of the doFirst block gets ignored (configFile is null) when the command is actually executed.

How do I actually get the value for configFile scoped such that the updated value in doFirst is sent to args.

import org.gradle.api.internal.tasks.userinput.UserInputHandler;
def queryConfigFile(baseDirectory) {
  ...
  def files = []
  def handler = services.get(UserInputHandler)
  def selection = handler.selectOption('But did you die?', files, 0) 
  return selection
}

task importStaticData(type: JavaExec) {
  def configFile;

  doFirst {
    configFile = queryConfigFile(CONFIG_DIRECTORY)
    println "Config - ${configFile}"
  }

  classpath = files(configurations.configurator, configurations.runtime)

  main = 'com.company.cli.Main'

  args = ['--debug',
          '--file',
          "${configFile}"
          ]

}

I’m also open to different version of the implementation, but the net result is that I do need to run a jar.

Hello,

the issue is that you are assigning value of configFile in configuration phase and reading value to it in execution phase. So when the value is assigned it has already been read.
I would suggest using argumentProvider and inside it reading the value from command line
it could look like this (i havent tried it, i use kotlin dsl so i am not sure if it is functional in groovy):

task importStaticData(type: JavaExec) {
  classpath = files(configurations.configurator, configurations.runtime)

  main = 'com.company.cli.Main'

  args = ['--debug',
          '--file',
          ]
  argumentProviders.add {
      def configFile = queryConfigFile(CONFIG_DIRECTORY)
      [configFile]
  }
}

Thanks for the input @drichter, I’m not sure how to translate that to groovy but you gave me a different perspective that allowed me to do what I wanted to do, here is the end result:

import org.gradle.api.internal.tasks.userinput.UserInputHandler;
def queryConfigFile(baseDirectory) {
  ...
  def files = []
  def handler = services.get(UserInputHandler)
  def selection = handler.selectOption('But did you die?', files, 0) 
  return selection
}

task importStaticData(type: JavaExec) {
  doFirst {
    def userSelection = queryConfigFile(CONFIG_DIRECTORY)
    args(userSelection)
    workingDir = new File(userSelection).getParent()
  }

  classpath = files(configurations.configurator, configurations.runtime)

  main = 'com.company.cli.Main'

  args = ['--debug', '--file']
}

You are welcome, i actually tried to write it in groovy i just wasn’t sure if it will work because i wrote it in browser and did not tried it in gradle groovy project.