or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ant-builder.mdfile-utilities.mdgroovy-compilation.mdgroovy-documentation.mdgroovy-execution.mdindex.md

groovy-execution.mddocs/

0

# Groovy Script Execution

1

2

The Groovy Ant task enables execution of Groovy scripts and code snippets directly within Ant build files, providing full access to the Ant project context, properties, and build environment.

3

4

## Capabilities

5

6

### Groovy Task

7

8

Executes Groovy scripts from files or inline text with comprehensive configuration options and build integration.

9

10

```java { .api }

11

/**

12

* Executes a series of Groovy statements within an Ant build context.

13

* Statements can be read from a file using the src attribute or embedded inline.

14

*/

15

public class Groovy extends org.apache.tools.ant.taskdefs.Java {

16

/** Set the source file containing Groovy script to execute */

17

public void setSrc(File srcFile);

18

19

/** Add inline Groovy code to execute */

20

public void addText(String txt);

21

22

/** Execute script in a forked JVM process */

23

public void setFork(boolean fork);

24

25

/** Use GroovyShell for forked execution instead of Ant's Java task */

26

public void setUseGroovyShell(boolean useGroovyShell);

27

28

/** Include Ant runtime classpath when forking */

29

public void setIncludeAntRuntime(boolean includeAntRuntime);

30

31

/** Enable compiler stack trace reporting on errors */

32

public void setStacktrace(boolean stacktrace);

33

34

/** Set the classpath for script execution */

35

public void setClasspath(Path classpath);

36

37

/** Create a nested classpath element */

38

public Path createClasspath();

39

40

/** Set classpath using a reference */

41

public void setClasspathRef(Reference ref);

42

43

/** Get the current classpath */

44

public Path getClasspath();

45

46

/** Add a fileset of scripts to execute */

47

public void addFileset(FileSet set);

48

49

/** Set output file for script results */

50

public void setOutput(File output);

51

52

/** Append to output file instead of overwriting */

53

public void setAppend(boolean append);

54

55

/** Set configuration script for compiler customization */

56

public void setConfigscript(String configscript);

57

58

/** Enable invokedynamic support */

59

public void setIndy(boolean indy);

60

61

/** Set base class for script compilation */

62

public void setScriptBaseClass(String scriptBaseClass);

63

64

/** Generate parameter metadata for reflection */

65

public void setParameters(boolean parameters);

66

67

/** Check if parameter metadata generation is enabled */

68

public boolean getParameters();

69

70

/** Create command line argument for script */

71

public org.apache.tools.ant.types.Commandline.Argument createArg();

72

73

/** Set context classloader for script execution */

74

public void setContextClassLoader(boolean contextClassLoader);

75

76

/** Execute the Groovy script */

77

public void execute() throws BuildException;

78

}

79

```

80

81

### Script Context Access

82

83

Scripts executed through the Groovy task have access to the following built-in variables:

84

85

```java { .api }

86

// Available variables in Groovy scripts

87

public interface GroovyScriptContext {

88

/** Access to the AntBuilder for executing Ant tasks */

89

AntBuilder ant;

90

91

/** Reference to the current Ant project */

92

Project project;

93

94

/** Delegate for accessing project properties */

95

AntProjectPropertiesDelegate properties;

96

97

/** Reference to the current build target */

98

Target target;

99

100

/** Reference to the current task */

101

Task task;

102

103

/** Command line arguments passed to the script */

104

String[] args;

105

106

/** Maven POM object (when running under Maven) */

107

Object pom; // Available only in Maven context

108

}

109

```

110

111

## Usage Examples

112

113

### Basic Inline Script Execution

114

```xml

115

<groovy>

116

println "Current working directory: ${project.baseDir}"

117

println "Build timestamp: ${new Date()}"

118

119

// Access project properties

120

properties.each { key, value ->

121

if (key.startsWith('java.')) {

122

println "$key = $value"

123

}

124

}

125

</groovy>

126

```

127

128

### Execute Script from File

129

```xml

130

<groovy src="scripts/build-helper.groovy">

131

<classpath>

132

<fileset dir="lib" includes="*.jar"/>

133

<pathelement location="build/classes"/>

134

</classpath>

135

</groovy>

136

```

137

138

### Forked Execution with Custom Configuration

139

```xml

140

<groovy fork="true"

141

includeAntRuntime="false"

142

useGroovyShell="true"

143

stacktrace="true">

144

<classpath>

145

<path refid="compile.classpath"/>

146

</classpath>

147

148

// Script with heavy processing that benefits from forking

149

def data = (1..1000000).collect { "Item $it" }

150

println "Processed ${data.size()} items"

151

</groovy>

152

```

153

154

### Dynamic Ant Task Execution

155

```xml

156

<groovy>

157

// Use the ant builder to execute tasks dynamically

158

def sourceFiles = ['src/main/java', 'src/main/groovy']

159

160

sourceFiles.each { srcDir ->

161

if (new File(srcDir).exists()) {

162

ant.copy(todir: 'backup') {

163

fileset(dir: srcDir, includes: '**/*')

164

}

165

println "Backed up $srcDir"

166

}

167

}

168

169

// Set properties dynamically

170

project.setProperty('backup.completed', 'true')

171

</groovy>

172

```

173

174

### Script with Output File

175

```xml

176

<groovy output="build/reports/build-info.txt" append="false">

177

println "Build Information Report"

178

println "========================"

179

println "Build time: ${new Date()}"

180

println "Groovy version: ${GroovySystem.version}"

181

println "Java version: ${System.getProperty('java.version')}"

182

183

// Generate file listing

184

println "\nSource files:"

185

new File('src').eachFileRecurse { file ->

186

if (file.name.endsWith('.groovy') || file.name.endsWith('.java')) {

187

println " ${file.path}"

188

}

189

}

190

</groovy>

191

```

192

193

### Error Handling and Validation

194

```xml

195

<groovy stacktrace="true">

196

try {

197

// Validate required properties

198

def requiredProps = ['version', 'build.dir', 'src.dir']

199

requiredProps.each { prop ->

200

if (!project.getProperty(prop)) {

201

throw new BuildException("Required property '$prop' is not set")

202

}

203

}

204

205

println "All required properties are set"

206

207

} catch (Exception e) {

208

// Log error and re-throw as BuildException

209

println "Validation failed: ${e.message}"

210

throw new BuildException("Property validation failed", e)

211

}

212

</groovy>

213

```

214

215

### Integration with FileSet Processing

216

```xml

217

<groovy>

218

<fileset dir="src" includes="**/*.properties"/>

219

220

// Process properties files

221

def propsCount = 0

222

filesets[0].each { file ->

223

def props = new Properties()

224

file.withInputStream { props.load(it) }

225

226

println "Processing ${file.name}: ${props.size()} properties"

227

propsCount++

228

}

229

230

project.setProperty('properties.files.count', propsCount.toString())

231

</groovy>

232

```

233

234

## Configuration Options

235

236

### Compilation Configuration

237

238

```java { .api }

239

public interface CompilerConfiguration {

240

/** Set script base class for compilation */

241

public void setScriptBaseClass(String className);

242

243

/** Enable debug information in compiled classes */

244

public void setDebug(boolean debug);

245

246

/** Set target bytecode version */

247

public void setTargetBytecode(String version);

248

249

/** Enable parameter metadata generation */

250

public void setParameters(boolean parameters);

251

252

/** Configure optimization options */

253

public Map<String, Object> getOptimizationOptions();

254

}

255

```

256

257

### Execution Environment

258

259

Scripts have access to a rich execution environment including:

260

261

- **Project Context**: Full access to Ant project, targets, and properties

262

- **File System**: Current working directory and project structure

263

- **Classpath**: All dependencies and build artifacts

264

- **System Properties**: JVM and environment configuration

265

- **Build State**: Current target, task hierarchy, and execution context