Skip to content

Commit d2c3b29

Browse files
committed
add environment variables support for PythonTask (#8)
1 parent 7a5240a commit d2c3b29

File tree

5 files changed

+147
-0
lines changed

5 files changed

+147
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add environment variables support (#8):
2+
- Python object: `Python.environment` (single and map)
3+
- Python task: `PythonTask.environment` (single and map)
4+
15
### 2.0.0 (2020-03-13)
26
* (breaking) Drop java 7 support
37
* (breaking) Drop gradle 4 support

src/main/groovy/ru/vyarus/gradle/plugin/python/cmd/Python.groovy

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ class Python {
4444
private LogLevel logLevel = LogLevel.INFO
4545
private final List<String> pythonArgs = []
4646
private final List<String> extraArgs = []
47+
private final Map<String, Object> envVars = [:]
4748

4849
// run through cmd on win (when direct executable called)
4950
private final boolean withCmd
@@ -137,6 +138,37 @@ class Python {
137138
return this
138139
}
139140

141+
/**
142+
* Set environment variable for executed python process.
143+
* <p>
144+
* Specified variables could be cleared with {@link #clearEnvironment()}.
145+
*
146+
* @param var environment variable
147+
* @param value variable value
148+
* @return cli instance for chained calls
149+
*/
150+
Python environment(String var, Object value) {
151+
envVars.put(var, value)
152+
return this
153+
}
154+
155+
/**
156+
* Set environment variables for executed python process. This call does not replace previous variables map,
157+
* it only adds all specified values into existing map (with possible overriding of some variable values).
158+
* So if called multiple times, all specified maps would be aggregated.
159+
* <p>
160+
* Specified variables could be cleared with {@link #clearEnvironment()}.
161+
*
162+
* @param vars environment variables (may be null)
163+
* @return cli instance for chained calls
164+
*/
165+
Python environment(Map<String, Object> vars) {
166+
if (vars) {
167+
envVars.putAll(vars)
168+
}
169+
return this
170+
}
171+
140172
/**
141173
* Removes all registered python arguments.
142174
*
@@ -157,6 +189,11 @@ class Python {
157189
return this
158190
}
159191

192+
Python clearEnvironment() {
193+
this.envVars.clear()
194+
return this
195+
}
196+
160197
/**
161198
* Execute python command and return all output (without applying the prefix!).
162199
* Very handy for short scripts evaluation. In case of error, all output is logged (with prefix).
@@ -327,6 +364,9 @@ class Python {
327364
if (workDir) {
328365
setWorkingDir(workDir)
329366
}
367+
if (envVars) {
368+
it.environment(envVars)
369+
}
330370
}
331371
project.logger.info('Python execution time: {}',
332372
DurationFormatter.format(System.currentTimeMillis() - start))

src/main/groovy/ru/vyarus/gradle/plugin/python/task/PythonTask.groovy

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ class PythonTask extends BasePythonTask {
7575
@Input
7676
@Optional
7777
List<String> extraArgs = []
78+
/**
79+
* Environment variables for executed python process (variables specified in gradle's
80+
* {@link org.gradle.process.ExecSpec#environment(java.util.Map)} during python process execution).
81+
*/
82+
@Input
83+
@Optional
84+
Map<String, Object> environment = [:]
7885
/**
7986
* Prefix each line of python output. By default it's '\t' to indicate command output.
8087
*/
@@ -97,6 +104,7 @@ class PythonTask extends BasePythonTask {
97104
.workDir(getWorkDir())
98105
.pythonArgs(getPythonArgs())
99106
.extraArgs(getExtraArgs())
107+
.environment(environment)
100108

101109
if (mod) {
102110
python.callModule(mod, cmd)
@@ -129,6 +137,30 @@ class PythonTask extends BasePythonTask {
129137
}
130138
}
131139

140+
/**
141+
* Add environment variable for python process (will override previously set value).
142+
*
143+
* @param var variable name
144+
* @param value variable value
145+
*/
146+
@SuppressWarnings('ConfusingMethodName')
147+
void environment(String var, Object value) {
148+
getEnvironment().put(var, value)
149+
}
150+
151+
/**
152+
* Add environment variables for python process (will override already set values, but not replace context
153+
* map completely). May be called multiple times: all variables would be aggregated.
154+
*
155+
* @param vars (may be null)
156+
*/
157+
@SuppressWarnings('ConfusingMethodName')
158+
void environment(Map<String, Object> vars) {
159+
if (vars) {
160+
getEnvironment().putAll(vars)
161+
}
162+
}
163+
132164
private void initWorkDirIfRequired() {
133165
String dir = getWorkDir()
134166
if (dir && isCreateWorkDir()) {

src/test/groovy/ru/vyarus/gradle/plugin/python/cmd/PythonCliTest.groovy

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,5 +125,28 @@ class PythonCliTest extends AbstractTest {
125125
python.clearExtraArgs()
126126
then: 'set'
127127
python.extraArgs.empty
128+
129+
when: "set vars"
130+
python.environment('foo', 1)
131+
python.environment('bar', 2)
132+
then: 'set'
133+
python.envVars == ['foo': 1, 'bar' : 2]
134+
135+
when: 'clear vars'
136+
python.clearEnvironment()
137+
then: 'no vars'
138+
python.envVars.size() == 0
139+
140+
when: 'mass variables set'
141+
python.environment(['foo': 2, 'bar' : 3])
142+
python.environment(['foo': 1, 'baz' : 4])
143+
then: 'aggregated'
144+
python.envVars == ['foo': 1, 'bar' : 3, 'baz': 4]
145+
146+
when: 'additional var'
147+
python.environment('sample': 'sam')
148+
then: 'aggregated'
149+
python.envVars == ['foo': 1, 'bar' : 3, 'baz': 4, 'sample': 'sam']
150+
128151
}
129152
}

src/test/groovy/ru/vyarus/gradle/plugin/python/task/PythonTaskKitTest.groovy

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,52 @@ class PythonTaskKitTest extends AbstractKitTest {
184184
result.output.contains('\t sample')
185185
}
186186

187+
188+
def "Check env vars"() {
189+
setup:
190+
build """
191+
plugins {
192+
id 'ru.vyarus.use-python'
193+
}
194+
195+
task sample(type: PythonTask) {
196+
command = "-c \\"import os;print('variables: '+os.getenv('some', 'null')+' '+os.getenv('foo', 'null'))\\""
197+
environment 'some', 1
198+
environment(['foo': 'bar'])
199+
}
200+
"""
201+
202+
when: "run task"
203+
debug()
204+
BuildResult result = run('sample')
205+
206+
then: "executed"
207+
result.task(':sample').outcome == TaskOutcome.SUCCESS
208+
result.output.contains('variables: 1 bar')
209+
}
210+
211+
212+
def "Check python see system variables"() {
213+
setup:
214+
build """
215+
plugins {
216+
id 'ru.vyarus.use-python'
217+
}
218+
219+
assert System.getenv('some') == 'foo'
220+
221+
task sample(type: PythonTask) {
222+
command = "-c \\"import os;print('variables: '+os.getenv('some', 'null'))\\""
223+
}
224+
"""
225+
226+
when: "run task"
227+
BuildResult result = gradle('sample')
228+
.withEnvironment(['some': 'foo', 'PATH': System.getenv('PATH')])
229+
.build()
230+
231+
then: "executed"
232+
result.task(':sample').outcome == TaskOutcome.SUCCESS
233+
result.output.contains('variables: foo')
234+
}
187235
}

0 commit comments

Comments
 (0)