@@ -2,10 +2,13 @@ package types
22
33import (
44 "fmt"
5+ "regexp"
56 "slices"
7+ "strconv"
68 "strings"
79
810 "github.com/zclconf/go-cty/cty"
11+ "golang.org/x/xerrors"
912)
1013
1114// @typescript-ignore BlockTypeParameter
@@ -63,6 +66,50 @@ type ParameterValidation struct {
6366 Monotonic * string `json:"validation_monotonic"`
6467}
6568
69+ // TODO: Match implementation from https://github.com/coder/terraform-provider-coder/blob/main/provider/parameter.go#L404-L462
70+ // TODO: Does the value have to be an option from the set of options?
71+ func (v ParameterValidation ) Valid (p string ) error {
72+ validErr := xerrors .New (v .errorRendered (p ))
73+ if v .Regex != nil {
74+ exp , err := regexp .Compile (* v .Regex )
75+ if err != nil {
76+ return fmt .Errorf ("invalid regex %q: %w" , * v .Regex , err )
77+ }
78+
79+ if ! exp .MatchString (p ) {
80+ return validErr
81+ }
82+ }
83+
84+ if v .Min != nil || v .Max != nil {
85+ vd , err := strconv .ParseInt (p , 10 , 64 )
86+ if err != nil {
87+ return fmt .Errorf ("invalid number value %q: %w" , p , err )
88+ }
89+
90+ if v .Min != nil && vd < * v .Min {
91+ return validErr
92+ }
93+
94+ if v .Max != nil && vd > * v .Max {
95+ return validErr
96+ }
97+ }
98+
99+ // Monotonic?
100+
101+ return nil
102+ }
103+
104+ func (v ParameterValidation ) errorRendered (value string ) string {
105+ r := strings .NewReplacer (
106+ "{min}" , fmt .Sprintf ("%d" , safeDeref (v .Min )),
107+ "{max}" , fmt .Sprintf ("%d" , safeDeref (v .Max )),
108+ "{value}" , value ,
109+ )
110+ return r .Replace (v .Error )
111+ }
112+
66113type ParameterOption struct {
67114 Name string `json:"name"`
68115 Description string `json:"description"`
@@ -83,6 +130,14 @@ func (r *RichParameter) CtyType() (cty.Type, error) {
83130 case "list(string)" :
84131 return cty .List (cty .String ), nil
85132 default :
86- return cty.Type {}, fmt .Errorf ("unsupported type: %q" , r .Type )
133+ return cty .NilType , fmt .Errorf ("unsupported type: %q" , r .Type )
134+ }
135+ }
136+
137+ func safeDeref [T any ](v * T ) T {
138+ if v == nil {
139+ var zero T
140+ return zero
87141 }
142+ return * v
88143}
0 commit comments