gradle-node-plugin icon indicating copy to clipboard operation
gradle-node-plugin copied to clipboard

You can't pass dynamic environment to npm run

Open kicktipp opened this issue 3 years ago • 6 comments

I know I can add environment variables like this:

task verify(type: NpmTask) {
    environment = ['CYPRESS_BASE_URL' : "http://localhost:9999"]
    args = ['run', 'verify']
}

But in my case the environment variable is only set later on from a custom plugin called "backendServer". So I tried to add environment in doFirst:

verify.doFirst {
    def randomPort = backendServer.getLocalPort()
    environment = ['CYPRESS_BASE_URL' : "http://localhost:" + randomPort]
}

But this does not work as environment is immutable.

kicktipp avatar Jun 13 '22 16:06 kicktipp

environment when set is a MapProperty so in the case of doFirst environment.put('CYPRESS_BASE_URL', 'http://localhost:" + randomPort] might work better.

Or if you can turn the randomPort part into a provider instead then it should be resolved at the right time and you shouldn't need doFirst

deepy avatar Jun 14 '22 07:06 deepy

Using environment.put does not help as "'environment' is final and cannot be changed any further."

I will try the provider option.

kicktipp avatar Jun 14 '22 09:06 kicktipp

https://docs.gradle.org/current/userguide/build_services.html might be of interest as well

deepy avatar Jun 14 '22 10:06 deepy

I implemented the provider option for me. It works fine. But the build service looks promising too. Thank you so much.

kicktipp avatar Jun 14 '22 14:06 kicktipp

@kicktipp: I would appreciate if you could share the relevant change required for getting it working with a provider in your case.

uwolfer avatar Aug 02 '22 20:08 uwolfer

I used a provider like this:

task verify(type: NpxTask) {
    inputs.files(fileTree('tests/e2e'))
    command = 'cypress'
    args = ['run', '--browser', 'chrome']
    environment = ['CYPRESS_BASE_URL' : project(':backend').backendServer.baseUrl.get()]
}

and in my gradle java plugin:

@NonNullApi
public abstract class BackendServerPluginExtension {
     ...
    @Internal
    final Provider<Integer> runningPort = getPort().map(this::resolvePort);

    @Internal
    final Provider<String> baseUrl = getPort().map(this::baseUrl);

If you can't figure it out, I can send you the complete code by mail.

kicktipp avatar Aug 04 '22 14:08 kicktipp