Skip to content

Commit

Permalink
Fix NPE in startswith condition if no default is provided
Browse files Browse the repository at this point in the history
  • Loading branch information
nadav-y committed Jan 8, 2025
1 parent facfea6 commit 1882d95
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ static void registerBaseFunctions(HCLParser parser) {
});

parser.registerFunction("startswith", (arguments) -> {
if(arguments.size() == 2) {
if(arguments.size() == 2 && arguments.get(0) != null && arguments.get(1) != null) {
String prefix = (String)(arguments.get(1));
String value = (String)(arguments.get(0));
return value.startsWith(prefix);
Expand Down
40 changes: 40 additions & 0 deletions src/test/groovy/com/bertramlabs/plugins/hcl4j/HCLParserSpec.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -1737,6 +1737,46 @@ resource "aws_instance" "bw-instance-1" {
results.resource["aws_instance"]["bw-instance-1"] != null

}

void "should parse startswith correctly if no default is provided from hcl"() {
given:

def hcl = '''
variable "server_id" {
type = string
description = "Server ID"
validation {
condition = length(var.server_id) == 19
error_message = "Server ID must be 19 characters long"
}
validation {
condition = startswith(var.server_id, "s-")
error_message = "Server ID must start with 's-'"
}
validation {
condition = lower(var.server_id) == var.server_id
error_message = "Server ID must be lowercase"
}
}
'''
HCLParser parser = new HCLParser();
when:
def results = parser.parse(hcl)
then:
results.containsKey('variable')
results.variable.containsKey("server_id")
results.variable.server_id.type.name == "string"
results.variable.server_id.description == "Server ID"
results.variable.server_id.validation.size() == 3
results.variable.server_id.validation[0].condition == false
results.variable.server_id.validation[0].error_message == "Server ID must be 19 characters long"
results.variable.server_id.validation[1].condition == null
results.variable.server_id.validation[1].error_message == "Server ID must start with 's-'"
results.variable.server_id.validation[2].condition == true
results.variable.server_id.validation[2].error_message == "Server ID must be lowercase"

}

}


Expand Down

0 comments on commit 1882d95

Please sign in to comment.