1

I have a gradle project that has a calculated variable I need to pass into an application. When i attempt to do this is passes a null value, not the set value I want.

I have the below example file that demonstrates the issue to run just do gradle foo I want both lines of output to be 4.

def String sum

task add {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'sh'
                args = ['-c', 'echo $((2 + 2))']
                standardOutput = os
            }
            sum = os.toString()
            afterEvaluate {
                tasks.foo {
                    systemProperty "foo.bar", "${sum}"
                }
            }
        }
    }
}

task foo {
    doLast{
        println System.properties['foo.bar']
        println "${sum}"
    }
}

tasks.foo.dependsOn( add )
ken
  • 11
  • 5

1 Answers1

0

Given this (note the simple assignment to System.properties['foo.bar']):

def String sum

task add {
    doLast {
        new ByteArrayOutputStream().withStream { os ->
            def result = exec {
                executable = 'sh'
                args = ['-c', 'echo $((2 + 2))']
                standardOutput = os
            }
            sum = os.toString()
            System.properties['foo.bar'] = sum
        }
    }
}

task foo {
    doLast{
        println System.properties['foo.bar']
        println "${sum}"
    }
}

tasks.foo.dependsOn( add )

then this is the output:

$ gradle foo 
:add
:foo
4

4
Michael Easter
  • 23,733
  • 7
  • 76
  • 107