Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.provider.MapProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
Expand Down Expand Up @@ -106,6 +108,13 @@ abstract class GenerateConfigurationMetadataTask extends DefaultTask {
@PathSensitive(PathSensitivity.RELATIVE)
abstract ConfigurableFileCollection getClassesDirs()

@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
abstract ConfigurableFileCollection getDslConfigurationFiles()

@Input
abstract MapProperty<String, String> getDslRootPrefixes()

@InputFile
@Optional
@PathSensitive(PathSensitivity.RELATIVE)
Expand All @@ -117,9 +126,15 @@ abstract class GenerateConfigurationMetadataTask extends DefaultTask {
@Inject
abstract FileSystemOperations getFileSystemOperations()

GenerateConfigurationMetadataTask() {
dslRootPrefixes.convention([:])
}

@TaskAction
void generate() {
Map<String, ClassModel> models = readModels()
List<Map<String, Object>> dslProperties = GroovyDslConfigurationMetadataParser.parse(
dslConfigurationFiles.files, dslRootPrefixes.get())
List<Map<String, Object>> groups = []
List<Map<String, Object>> properties = []
models.values().findAll { ClassModel model -> model.prefix != null }.sort { ClassModel model -> model.name }.each {
Expand All @@ -144,7 +159,7 @@ abstract class GenerateConfigurationMetadataTask extends DefaultTask {
}
}

Map<String, Object> metadata = merge(groups, properties, readOverlay())
Map<String, Object> metadata = merge([], dslProperties, groups, properties, readOverlay())
File output = outputDirectory.get().asFile
fileSystemOperations.delete { it.delete(output) }
File target = new File(output, 'META-INF/spring-configuration-metadata.json')
Expand Down Expand Up @@ -348,13 +363,17 @@ abstract class GenerateConfigurationMetadataTask extends DefaultTask {
file?.isFile() ? new JsonSlurper().parse(file, StandardCharsets.UTF_8.name()) as Map : [:]
}

private static Map<String, Object> merge(List<Map<String, Object>> groups,
List<Map<String, Object>> properties, Map overlay) {
private static Map<String, Object> merge(List<Map<String, Object>> dslGroups,
List<Map<String, Object>> dslProperties,
List<Map<String, Object>> typedGroups,
List<Map<String, Object>> typedProperties,
Map overlay) {
Map<String, Object> result = [:]
result['groups'] = mergeNamed(groups, (overlay.get('groups') ?: []) as List, 'groups')
result['properties'] = mergeNamed(properties, (overlay.get('properties') ?: []) as List, 'properties')
result['groups'] = mergeNamed(dslGroups, typedGroups, (overlay.get('groups') ?: []) as List, 'groups')
result['properties'] = mergeNamed(dslProperties, typedProperties,
(overlay.get('properties') ?: []) as List, 'properties')
if (overlay.containsKey('hints')) {
result['hints'] = mergeNamed([], overlay.get('hints') as List, 'hints')
result['hints'] = mergeNamed([], [], overlay.get('hints') as List, 'hints')
}
overlay.each { Object keyValue, Object value ->
String key = keyValue.toString()
Expand All @@ -365,27 +384,32 @@ abstract class GenerateConfigurationMetadataTask extends DefaultTask {
if (overlay.containsKey('ignored')) {
Map ignored = new LinkedHashMap((overlay.get('ignored') ?: [:]) as Map)
if (ignored.containsKey('properties')) {
ignored['properties'] = mergeNamed([], ignored.get('properties') as List, 'ignored.properties')
ignored['properties'] = mergeNamed([], [], ignored.get('properties') as List, 'ignored.properties')
}
result['ignored'] = ignored
}
result
}

private static List<Object> mergeNamed(List generated, List overlay, String category) {
Map<String, Object> generatedByName = indexByName(generated, category, 'generated')
private static List<Object> mergeNamed(List dsl, List typed, List overlay, String category) {
Map<String, Object> dslByName = indexByName(dsl, category, 'DSL')
Map<String, Object> typedByName = indexByName(typed, category, 'generated')
Map<String, Object> overlayByName = indexByName(overlay, category, 'overlay')
Map<String, Object> merged = new LinkedHashMap<>(generatedByName)
Map<String, Object> merged = new LinkedHashMap<>(dslByName)
typedByName.each { String name, Object value ->
merged[name] = mergeFields(merged[name], value)
}
overlayByName.each { String name, Object value ->
if (merged[name] instanceof Map && value instanceof Map) {
merged[name] = new LinkedHashMap((Map) merged[name]) + (Map) value
} else {
merged[name] = value
}
merged[name] = mergeFields(merged[name], value)
}
merged.keySet().sort().collect { String name -> merged[name] }
}

private static Object mergeFields(Object lowerPrecedence, Object higherPrecedence) {
lowerPrecedence instanceof Map && higherPrecedence instanceof Map ?
new LinkedHashMap((Map) lowerPrecedence) + (Map) higherPrecedence : higherPrecedence
}

private static Map<String, Object> indexByName(List source, String category, String sourceName) {
Map<String, Object> indexed = [:]
source.each { Object entry ->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.grails.buildsrc

import org.codehaus.groovy.ast.ModuleNode
import org.codehaus.groovy.ast.expr.ArgumentListExpression
import org.codehaus.groovy.ast.expr.BinaryExpression
import org.codehaus.groovy.ast.expr.ClassExpression
import org.codehaus.groovy.ast.expr.ClosureExpression
import org.codehaus.groovy.ast.expr.ConstantExpression
import org.codehaus.groovy.ast.expr.Expression
import org.codehaus.groovy.ast.expr.ListExpression
import org.codehaus.groovy.ast.expr.MapExpression
import org.codehaus.groovy.ast.expr.MethodCallExpression
import org.codehaus.groovy.ast.expr.PropertyExpression
import org.codehaus.groovy.ast.expr.TernaryExpression
import org.codehaus.groovy.ast.expr.VariableExpression
import org.codehaus.groovy.ast.stmt.BlockStatement
import org.codehaus.groovy.ast.stmt.ExpressionStatement
import org.codehaus.groovy.ast.stmt.IfStatement
import org.codehaus.groovy.ast.stmt.Statement
import org.codehaus.groovy.control.CompilationFailedException
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.syntax.Types

import java.nio.charset.StandardCharsets

/** Extracts configuration metadata from Groovy DSL source without evaluating source code. */
final class GroovyDslConfigurationMetadataParser {

private GroovyDslConfigurationMetadataParser() {
}

static List<Map<String, Object>> parse(Collection<File> files, Map<String, String> rootPrefixes) {
List<Map<String, Object>> properties = []
files.findAll { File file -> file.isFile() }.sort { File file -> file.absolutePath }.each { File file ->
parseFile(file, rootPrefixes, properties)
}
properties.sort { Map<String, Object> property -> property.name as String }
}

private static void parseFile(File file, Map<String, String> rootPrefixes,
List<Map<String, Object>> properties) {
ModuleNode module = parseSource(file)
module.statementBlock.statements.each { Statement statement ->
MethodCallExpression call = methodCall(statement)
String root = call?.methodAsString
ClosureExpression closure = call == null ? null : closureArgument(call)
String prefix = root == null ? null : rootPrefixes[root]
if (prefix != null && closure != null) {
parseStatements(closure.code, prefix, false, properties)
}
}
}

private static ModuleNode parseSource(File file) {
try {
SourceUnit source = SourceUnit.create(file.absolutePath, file.getText(StandardCharsets.UTF_8.name()))
source.parse()
source.completePhase()
source.nextPhase()
source.convert()
source.errorCollector.failIfErrors()
source.AST
} catch (CompilationFailedException exception) {
throw new IllegalArgumentException("Failed to parse Groovy DSL source '${file.absolutePath}'", exception)
}
}

private static void parseStatements(Statement statement, String prefix, boolean conditional,
List<Map<String, Object>> properties) {
if (statement instanceof BlockStatement) {
statement.statements.each { Statement child -> parseStatements(child, prefix, conditional, properties) }
} else if (statement instanceof IfStatement) {
parseStatements(statement.ifBlock, prefix, true, properties)
parseStatements(statement.elseBlock, prefix, true, properties)
} else if (statement instanceof ExpressionStatement) {
Expression expression = statement.expression
if (expression instanceof BinaryExpression && expression.operation.type == Types.ASSIGN) {
addAssignment(expression, prefix, conditional, properties)
} else if (expression instanceof MethodCallExpression) {
ClosureExpression closure = closureArgument(expression)
String nestedName = expression.methodAsString
if (closure != null && nestedName != null) {
parseStatements(closure.code, "${prefix}.${nestedName}", conditional, properties)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These sources are ConfigSlurper scripts at runtime (SpringSecurityUtils loads DefaultSecurityConfig with new ConfigSlurper(Environment.current.name).parse(...)), so an environments block is valid in them. This branch would treat it as an ordinary nested section and silently emit names like <prefix>.environments.production.foo instead of <prefix>.foo. Nothing hits this today since DefaultSecurityConfig.groovy uses Environment.current if-checks instead, but it may be worth handling an environments call like IfStatement (recurse into each environment closure with the unchanged prefix and conditional = true) — or failing loudly when one is encountered.

}
}
}
}

private static void addAssignment(BinaryExpression assignment, String prefix, boolean conditional,
List<Map<String, Object>> properties) {
List<String> segments = leftHandPath(assignment.leftExpression)
if (segments == null) {
return
}
String name = "${prefix}.${segments.join('.')}"
Inference inference = infer(assignment.rightExpression)
Map<String, Object> property = [name: name]
if (inference.type != null) {
property.type = inference.type
}
if (!conditional && inference.literal) {
property.defaultValue = inference.value
}
properties << property

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplicate assignments to the same property produce distinct entries here, and the DSL index in mergeNamed (indexByName) fails the task when two entries for one name aren't map-equal. Two patterns that are valid at runtime under ConfigSlurper's last-write-wins semantics trip this:

foo = 'default'
if (Environment.current == Environment.TEST) {
    foo = 'test' // conditional entry has no defaultValue -> conflicts with the unconditional entry
}

and if/else branches whose literals infer different types (e.g. = null in one branch, = true in the other). DefaultSecurityConfig.groovy avoids both today — the password branches assign the same types on both sides — but the next DSL source registered could fail the build on a perfectly legitimate config. Consider collapsing same-name entries before returning (union the type the way sharedType does, keep the unconditional defaultValue), or at least add a spec pinning the conflict failure so it's an explicit contract.

}

private static List<String> leftHandPath(Expression expression) {
if (expression instanceof VariableExpression) {
return [expression.name]
}
if (expression instanceof PropertyExpression && expression.property instanceof ConstantExpression &&
expression.property.value instanceof String) {
List<String> owner = leftHandPath(expression.objectExpression)
return owner == null ? null : owner + expression.property.value
}
null
}

private static MethodCallExpression methodCall(Statement statement) {
statement instanceof ExpressionStatement && statement.expression instanceof MethodCallExpression ?
statement.expression as MethodCallExpression : null
}

private static ClosureExpression closureArgument(MethodCallExpression call) {
call.arguments instanceof ArgumentListExpression ?
(call.arguments.expressions.find { Expression expression -> expression instanceof ClosureExpression } as ClosureExpression) : null
}

private static Inference infer(Expression expression) {
if (expression instanceof ConstantExpression) {
return new Inference(type: expression.value?.class?.name, literal: true, value: expression.value)
}
if (expression instanceof ListExpression) {
return listInference(expression)
}
if (expression instanceof MapExpression) {
return mapInference(expression)
}
if (expression instanceof TernaryExpression) {
return sharedType(infer(expression.trueExpression), infer(expression.falseExpression))
}
if (expression instanceof MethodCallExpression && isSystemCall(expression) &&
expression.methodAsString in ['getProperty', 'getenv']) {
return new Inference(type: 'java.lang.String')
}
new Inference()
}

private static boolean isSystemCall(MethodCallExpression expression) {
Expression receiver = expression.objectExpression
receiver instanceof ClassExpression && receiver.type.name == 'java.lang.System' ||
receiver instanceof VariableExpression && receiver.name == 'System'
}

private static Inference sharedType(Inference left, Inference right) {
left.type != null && left.type == right.type ? new Inference(type: left.type) : new Inference()
}

private static Inference listInference(ListExpression expression) {
List<Object> values = []
for (Expression element : expression.expressions) {
Inference inference = infer(element)
if (!inference.literal) {
return new Inference(type: 'java.util.List')
}
values << inference.value
}
new Inference(type: 'java.util.List', literal: true, value: values)
}

private static Inference mapInference(MapExpression expression) {
Map<String, Object> values = new LinkedHashMap<>()
for (def entry : expression.mapEntryExpressions) {
Inference key = infer(entry.keyExpression)
Inference value = infer(entry.valueExpression)
if (!key.literal || !(key.value instanceof String) || !value.literal) {
return new Inference(type: 'java.util.Map')
}
values[key.value] = value.value
}
new Inference(type: 'java.util.Map', literal: true, value: values)
}

private static final class Inference {
String type
boolean literal
Object value
}
}
Loading
Loading