mirror of
https://github.com/hashicorp/packer.git
synced 2026-06-09 08:42:33 -04:00
* Updating the license from MPL to Business Source License Going forward, this project will be licensed under the Business Source License v1.1. Please see our blog post for more details at https://hashi.co/bsl-blog, FAQ at https://hashi.co/license-faq, and details of the license at www.hashicorp.com/bsl. * Update copyright file headers to BUSL-1.1 --------- Co-authored-by: hashicorp-copywrite[bot] <110428419+hashicorp-copywrite[bot]@users.noreply.github.com>
73 lines
2.1 KiB
Go
73 lines
2.1 KiB
Go
// Copyright (c) HashiCorp, Inc.
|
|
// SPDX-License-Identifier: BUSL-1.1
|
|
|
|
package hcl2template
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/hashicorp/go-version"
|
|
"github.com/hashicorp/hcl/v2"
|
|
"github.com/zclconf/go-cty/cty"
|
|
"github.com/zclconf/go-cty/cty/convert"
|
|
)
|
|
|
|
// VersionConstraint represents a version constraint on some resource that
|
|
// carries with it a source range so that a helpful diagnostic can be printed
|
|
// in the event that a particular constraint does not match.
|
|
type VersionConstraint struct {
|
|
Required version.Constraints
|
|
DeclRange hcl.Range
|
|
}
|
|
|
|
func decodeVersionConstraint(attr *hcl.Attribute) (VersionConstraint, hcl.Diagnostics) {
|
|
ret := VersionConstraint{
|
|
DeclRange: attr.Range,
|
|
}
|
|
|
|
val, diags := attr.Expr.Value(nil)
|
|
if diags.HasErrors() {
|
|
return ret, diags
|
|
}
|
|
var err error
|
|
val, err = convert.Convert(val, cty.String)
|
|
if err != nil {
|
|
diags = append(diags, &hcl.Diagnostic{
|
|
Severity: hcl.DiagError,
|
|
Summary: "Invalid version constraint",
|
|
Detail: fmt.Sprintf("A string value is required for %s.", attr.Name),
|
|
Subject: attr.Expr.Range().Ptr(),
|
|
})
|
|
return ret, diags
|
|
}
|
|
|
|
if val.IsNull() {
|
|
// A null version constraint is strange, but we'll just treat it
|
|
// like an empty constraint set.
|
|
return ret, diags
|
|
}
|
|
|
|
if !val.IsWhollyKnown() {
|
|
// If there is a syntax error, HCL sets the value of the given attribute
|
|
// to cty.DynamicVal. A diagnostic for the syntax error will already
|
|
// bubble up, so we will move forward gracefully here.
|
|
return ret, diags
|
|
}
|
|
|
|
constraintStr := val.AsString()
|
|
constraints, err := version.NewConstraint(constraintStr)
|
|
if err != nil {
|
|
// NewConstraint doesn't return user-friendly errors, so we'll just
|
|
// ignore the provided error and produce our own generic one.
|
|
diags = append(diags, &hcl.Diagnostic{
|
|
Severity: hcl.DiagError,
|
|
Summary: "Invalid version constraint",
|
|
Detail: "This string does not use correct version constraint syntax. Check out the docs: https://packer.io/docs/templates/hcl_templates/blocks/packer#version-constraints",
|
|
Subject: attr.Expr.Range().Ptr(),
|
|
})
|
|
return ret, diags
|
|
}
|
|
|
|
ret.Required = constraints
|
|
return ret, diags
|
|
}
|