From 9bb031472f367369aa305a8bb3854e897697ccaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20Fern=C3=A1ndez?= Date: Thu, 12 Nov 2026 21:39:30 +0000 Subject: [PATCH 1/2] fix(features): convert non-string option values like the reference CLI A string-typed (or untyped) feature option given a non-string JSON value failed with `option "packages" expects string, got []interface {}`. The reference CLI never type-checks option values: it writes each one into devcontainer-features.env through a JavaScript template literal, so ["jq","tree"] installs as jq,tree. MergeOptions now converts such values as JavaScript's String() does: arrays join with "," (null elements empty, nested arrays flattened), numbers use JavaScript's formatting (1e6 -> 1000000, 1e21 -> 1e+21), booleans and null take their literal form. Objects are still rejected and boolean options stay strict. Enums are checked against the converted string, and a WarnFeatureOptionCoerced warning reports each conversion. Non-string defaults and undeclared options are converted too, so feature.env never carries Go formatting such as [jq tree]. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1zV4YDcDbkxa8xkQS5dMA --- CHANGELOG.md | 9 +++ config/resolved.go | 1 + feature/options.go | 140 ++++++++++++++++++++++++++++++----- feature/options_test.go | 157 ++++++++++++++++++++++++++++++++++++++++ feature_options_test.go | 63 ++++++++++++++++ 5 files changed, 353 insertions(+), 17 deletions(-) create mode 100644 feature_options_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d86cd0..12a1948 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **features** — a feature option declared as a string (or untyped) that + is given a non-string value is converted the way the reference CLI + converts it, instead of failing with `option "packages" expects + string, got []interface {}`. Arrays join with `,` (`["jq","tree"]` → + `jq,tree`), numbers, booleans and `null` take their JavaScript string + form, and a `config.WarnFeatureOptionCoerced` warning is reported. + Objects are still rejected, and boolean options stay strict. + Non-string defaults and undeclared options are converted too, so + `feature.env` never carries Go formatting such as `[jq tree]`. - **engine** — `Up` and `Build` called without `ConfigPath` now use the discovered `devcontainer.json`'s directory for local features and the compose working directory. Previously they always assumed diff --git a/config/resolved.go b/config/resolved.go index a84d67f..b07013f 100644 --- a/config/resolved.go +++ b/config/resolved.go @@ -414,6 +414,7 @@ const ( WarnUnknownVariable WarningCode = "unknown_variable" WarnDeepFeatureChain WarningCode = "deep_feature_chain" WarnUnknownFeatureOption WarningCode = "unknown_feature_option" + WarnFeatureOptionCoerced WarningCode = "feature_option_coerced" WarnComposePortsIgnored WarningCode = "compose_ports_ignored" WarnUIDReconcileSkipped WarningCode = "uid_reconcile_skipped" ) diff --git a/feature/options.go b/feature/options.go index d2db2cd..9db31ea 100644 --- a/feature/options.go +++ b/feature/options.go @@ -1,9 +1,12 @@ package feature import ( + "encoding/json" "fmt" + "math" "regexp" "sort" + "strconv" "strings" "github.com/crunchloop/devcontainer/config" @@ -14,20 +17,34 @@ import ( // // Order of precedence (later wins): defaults → user. Keys not declared // in the feature's options are kept (some features accept arbitrary -// extras) but emit WarnUnknownFeatureOption. Enum-typed options are +// extras), converted to strings when they can be, and emit +// WarnUnknownFeatureOption. Enum-typed options are // hard-validated; values outside the enum produce an error. Proposals // (soft constraints) do not validate. // +// A string-typed (or untyped) option given a non-string value is +// converted the way the reference CLI converts it (see +// coerceOptionString) and emits WarnFeatureOptionCoerced; only an +// object is rejected. Boolean-typed options stay strict. +// // Returns the merged map and any non-fatal warnings. Errors are // validation failures (enum mismatch, type mismatch on declared options). func MergeOptions(meta config.FeatureMetadata, user map[string]any) (map[string]any, []config.Warning, error) { out := make(map[string]any, len(meta.Options)+len(user)) var warnings []config.Warning - // Start with defaults from the feature's declared options. + // Start with defaults from the feature's declared options. A + // non-string default of a string option is converted too, so the + // env file never carries Go's formatting of it. for name, opt := range meta.Options { - if opt.Default != nil { - out[name] = opt.Default + if opt.Default == nil { + continue + } + out[name] = opt.Default + if isStringOption(opt) { + if s, ok := coerceOptionString(opt.Default); ok { + out[name] = s + } } } @@ -35,44 +52,133 @@ func MergeOptions(meta config.FeatureMetadata, user map[string]any) (map[string] for name, val := range user { decl, declared := meta.Options[name] if !declared { + // The reference CLI writes undeclared options to the env + // file too; convert them the same way when it can. out[name] = val + if s, ok := coerceOptionString(val); ok { + out[name] = s + } warnings = append(warnings, config.Warning{ Code: config.WarnUnknownFeatureOption, Message: fmt.Sprintf("feature %q: option %q is not declared in devcontainer-feature.json", meta.ID, name), }) continue } - if err := validateOptionValue(name, decl, val); err != nil { + v, err := validateOptionValue(name, decl, val) + if err != nil { return nil, warnings, fmt.Errorf("feature %q: %w", meta.ID, err) } - out[name] = val + if _, wasString := val.(string); !wasString && isStringOption(decl) { + warnings = append(warnings, config.Warning{ + Code: config.WarnFeatureOptionCoerced, + Message: fmt.Sprintf("feature %q: option %q expects a string; %T value converted to %q", meta.ID, name, val, v), + }) + } + out[name] = v } return out, warnings, nil } -func validateOptionValue(name string, opt config.FeatureOption, val any) error { +func isStringOption(opt config.FeatureOption) bool { + return opt.Type == "string" || opt.Type == "" +} + +// validateOptionValue checks val against opt and returns the value to +// install with: val itself, or for a string option its string form. +func validateOptionValue(name string, opt config.FeatureOption, val any) (any, error) { + if isStringOption(opt) { + s, ok := coerceOptionString(val) + if !ok { + return nil, fmt.Errorf("option %q expects string, got %T", name, val) + } + val = s + } if len(opt.Enum) > 0 { for _, allowed := range opt.Enum { if anyEqual(allowed, val) { - return nil + return val, nil } } - return fmt.Errorf("option %q value %v is not in enum %v", name, val, opt.Enum) + return nil, fmt.Errorf("option %q value %v is not in enum %v", name, val, opt.Enum) } - switch opt.Type { - case "boolean": + if opt.Type == "boolean" { if _, ok := val.(bool); !ok { - return fmt.Errorf("option %q expects boolean, got %T", name, val) + return nil, fmt.Errorf("option %q expects boolean, got %T", name, val) } - case "string", "": - if _, ok := val.(string); !ok { - return fmt.Errorf("option %q expects string, got %T", name, val) + } + // Any other type: accept and let install.sh deal with it. + return val, nil +} + +// coerceOptionString converts a JSON option value to a string the way +// the reference CLI (@devcontainers/cli) does: it writes each value +// into devcontainer-features.env through a JavaScript template +// literal, i.e. JavaScript's String(). An array joins its elements +// with "," (null → "", nested arrays flatten), null is "null", and +// numbers use JavaScript's number formatting. An object (which +// JavaScript would write as "[object Object]") is not converted: it +// reports false so the option is rejected. +func coerceOptionString(v any) (string, bool) { + switch x := v.(type) { + case nil: + return "null", true + case string: + return x, true + case bool: + return strconv.FormatBool(x), true + case float64: + return jsNumberString(x), true + case float32: + return jsNumberString(float64(x)), true + case json.Number: + return x.String(), true + case int: + return strconv.Itoa(x), true + case int64: + return strconv.FormatInt(x, 10), true + case int32: + return strconv.FormatInt(int64(x), 10), true + case uint: + return strconv.FormatUint(uint64(x), 10), true + case uint64: + return strconv.FormatUint(x, 10), true + case uint32: + return strconv.FormatUint(uint64(x), 10), true + case []any: + parts := make([]string, len(x)) + for i, e := range x { + if e == nil { + continue // Array.prototype.join writes null as "". + } + s, ok := coerceOptionString(e) + if !ok { + return "", false + } + parts[i] = s } + return strings.Join(parts, ","), true default: - // Unknown type — accept and let install.sh deal with it. + return "", false + } +} + +// jsNumberString formats f as JavaScript's Number.prototype.toString +// does: shortest round-trip digits, positional notation for +// 1e-6 <= |f| < 1e21, and otherwise exponent form with no exponent +// padding ("1e+21", "1.5e-7"). +func jsNumberString(f float64) string { + if f == 0 { + return "0" // also -0 + } + if a := math.Abs(f); a >= 1e21 || a < 1e-6 { + s := strconv.FormatFloat(f, 'e', -1, 64) + mant, exp, _ := strings.Cut(s, "e") + sign := exp[:1] + exp = strings.TrimLeft(exp[1:], "0") + return mant + "e" + sign + exp } - return nil + return strconv.FormatFloat(f, 'f', -1, 64) } func anyEqual(a, b any) bool { diff --git a/feature/options_test.go b/feature/options_test.go index 35e799d..36b4dcc 100644 --- a/feature/options_test.go +++ b/feature/options_test.go @@ -1,6 +1,7 @@ package feature import ( + "encoding/json" "reflect" "strings" "testing" @@ -130,3 +131,159 @@ func TestSafeEnvKey(t *testing.T) { } } } + +// The reference CLI writes options into devcontainer-features.env +// through a JavaScript template literal, so a non-string value of a +// string option is converted as JavaScript's String() converts it. + +func stringOptionMeta(opt config.FeatureOption) config.FeatureMetadata { + return config.FeatureMetadata{ + ID: "apt-packages", + Options: map[string]config.FeatureOption{"packages": opt}, + } +} + +func coerced(t *testing.T, opt config.FeatureOption, val any) (string, []config.Warning) { + t.Helper() + merged, warns, err := MergeOptions(stringOptionMeta(opt), map[string]any{"packages": val}) + if err != nil { + t.Fatalf("MergeOptions(%#v): %v", val, err) + } + s, ok := merged["packages"].(string) + if !ok { + t.Fatalf("packages = %#v, want a string", merged["packages"]) + } + return s, warns +} + +func TestMergeOptions_ArrayJoinedWithWarning(t *testing.T) { + got, warns := coerced(t, config.FeatureOption{Type: "string"}, []any{"jq", "tree"}) + if got != "jq,tree" { + t.Errorf("packages = %q, want %q", got, "jq,tree") + } + if len(warns) != 1 || warns[0].Code != config.WarnFeatureOptionCoerced { + t.Fatalf("warnings = %v, want one %s", warns, config.WarnFeatureOptionCoerced) + } + if !strings.Contains(warns[0].Message, `"packages"`) || !strings.Contains(warns[0].Message, `"jq,tree"`) { + t.Errorf("warning message %q should name the option and the converted value", warns[0].Message) + } +} + +func TestMergeOptions_StringValueNoCoercionWarning(t *testing.T) { + _, warns := coerced(t, config.FeatureOption{Type: "string"}, "jq tree") + if len(warns) != 0 { + t.Errorf("unexpected warnings: %v", warns) + } +} + +func TestMergeOptions_EmptyArrayIsEmptyString(t *testing.T) { + if got, _ := coerced(t, config.FeatureOption{Type: "string"}, []any{}); got != "" { + t.Errorf("packages = %q, want empty", got) + } +} + +func TestMergeOptions_NestedArrayAndNilElement(t *testing.T) { + got, _ := coerced(t, config.FeatureOption{Type: "string"}, []any{[]any{"a", "b"}, nil, "c"}) + if got != "a,b,,c" { + t.Errorf("packages = %q, want %q", got, "a,b,,c") + } +} + +func TestMergeOptions_NumbersFormattedAsJavaScript(t *testing.T) { + cases := []struct { + in any + want string + }{ + {float64(5), "5"}, + {1.5, "1.5"}, + {1e6, "1000000"}, + {1e21, "1e+21"}, + {-1.5e22, "-1.5e+22"}, + {1e-7, "1e-7"}, + {0.000001, "0.000001"}, + {json.Number("42"), "42"}, + {7, "7"}, + } + for _, tc := range cases { + if got, _ := coerced(t, config.FeatureOption{Type: "string"}, tc.in); got != tc.want { + t.Errorf("%#v → %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestMergeOptions_BoolAndNullConverted(t *testing.T) { + if got, _ := coerced(t, config.FeatureOption{Type: "string"}, true); got != "true" { + t.Errorf("true → %q", got) + } + if got, _ := coerced(t, config.FeatureOption{Type: "string"}, nil); got != "null" { + t.Errorf("nil → %q", got) + } +} + +func TestMergeOptions_ObjectStillRejected(t *testing.T) { + for _, val := range []any{ + map[string]any{"a": float64(1)}, + []any{"a", map[string]any{"b": "c"}}, + } { + _, _, err := MergeOptions(stringOptionMeta(config.FeatureOption{Type: "string"}), map[string]any{"packages": val}) + if err == nil { + t.Fatalf("%#v should be rejected", val) + } + if !strings.Contains(err.Error(), `"packages"`) || !strings.Contains(err.Error(), "expects string") { + t.Errorf("error %q should name the option and its type", err) + } + } +} + +func TestMergeOptions_UntypedOptionConverted(t *testing.T) { + got, warns := coerced(t, config.FeatureOption{}, []any{"jq", "tree"}) + if got != "jq,tree" { + t.Errorf("packages = %q, want %q", got, "jq,tree") + } + if len(warns) != 1 { + t.Errorf("warnings = %v, want one", warns) + } +} + +func TestMergeOptions_EnumCheckedAfterConversion(t *testing.T) { + opt := config.FeatureOption{Type: "string", Enum: []any{"20", "22"}} + if got, _ := coerced(t, opt, float64(20)); got != "20" { + t.Errorf("20 → %q, want %q", got, "20") + } + _, _, err := MergeOptions(stringOptionMeta(opt), map[string]any{"packages": float64(18)}) + if err == nil || !strings.Contains(err.Error(), "enum") { + t.Errorf("18 should fail the enum check, got %v", err) + } +} + +func TestMergeOptions_NonStringDefaultConverted(t *testing.T) { + merged, _, err := MergeOptions(stringOptionMeta(config.FeatureOption{Type: "string", Default: []any{"git"}}), nil) + if err != nil { + t.Fatal(err) + } + if merged["packages"] != "git" { + t.Errorf("packages = %#v, want %q", merged["packages"], "git") + } +} + +func TestMergeOptions_UndeclaredArrayConverted(t *testing.T) { + merged, _, err := MergeOptions(config.FeatureMetadata{ID: "x"}, map[string]any{"extra": []any{"a", "b"}}) + if err != nil { + t.Fatal(err) + } + if merged["extra"] != "a,b" { + t.Errorf("extra = %#v, want %q", merged["extra"], "a,b") + } +} + +func TestSerializeEnvFile_AfterCoercion(t *testing.T) { + merged, _, err := MergeOptions(stringOptionMeta(config.FeatureOption{Type: "string"}), map[string]any{ + "packages": []any{"jq", "tree"}, + }) + if err != nil { + t.Fatal(err) + } + if got := string(SerializeEnvFile(merged)); got != "PACKAGES='jq,tree'\n" { + t.Errorf("env file = %q, want %q", got, "PACKAGES='jq,tree'\n") + } +} diff --git a/feature_options_test.go b/feature_options_test.go new file mode 100644 index 0000000..a4ce8d1 --- /dev/null +++ b/feature_options_test.go @@ -0,0 +1,63 @@ +package devcontainer + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/crunchloop/devcontainer/config" + "github.com/crunchloop/devcontainer/runtime" +) + +// buildContextRuntime is a fakeRuntime whose BuildImage keeps the +// first feature's feature.env from the build context it is handed, +// then fails as the fake does. +type buildContextRuntime struct { + *fakeRuntime + featureEnv []byte +} + +func (r *buildContextRuntime) BuildImage(ctx context.Context, spec runtime.BuildSpec, events chan<- runtime.BuildEvent) (runtime.ImageRef, error) { + env, err := os.ReadFile(filepath.Join(spec.ContextPath, "build-context", "0", "feature.env")) + if err == nil { + r.featureEnv = env + } + return r.fakeRuntime.BuildImage(ctx, spec, events) +} + +// A string option given a JSON array, as in apt-packages' "packages", +// is installed with the comma-joined value the reference CLI writes. +func TestLayerFeatures_ArrayOptionReachesFeatureEnvJoined(t *testing.T) { + f := newDepFixture(t, `{"ghcr.io/x/apt-packages:1":{"packages":["jq","tree"]}}`, map[string]depEntry{ + "ghcr.io/x/apt-packages": {digestOf('a'), config.FeatureMetadata{ + ID: "apt-packages", + Version: "1.0.0", + Options: map[string]config.FeatureOption{"packages": {Type: "string", Default: ""}}, + }}, + }) + rt := &buildContextRuntime{fakeRuntime: f.rt} + eng, err := New(EngineOptions{Runtime: rt, FeatureStore: f.store}) + if err != nil { + t.Fatal(err) + } + f.eng = eng + + cfg, err := f.layer(LockfileDisabled) + if err != nil { + t.Fatalf("layerFeatures: %v", err) + } + if got := string(rt.featureEnv); !strings.Contains(got, "PACKAGES='jq,tree'\n") { + t.Errorf("feature.env = %q, want PACKAGES='jq,tree'", got) + } + found := false + for _, w := range cfg.Warnings { + if w.Code == config.WarnFeatureOptionCoerced { + found = true + } + } + if !found { + t.Errorf("expected a %s warning, got %v", config.WarnFeatureOptionCoerced, cfg.Warnings) + } +} From bf2071e53292f180faf6592b9e7b1bc3395e8704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20Fern=C3=A1ndez?= Date: Fri, 13 Nov 2026 03:23:31 +0000 Subject: [PATCH 2/2] fix(features): accept "true"/"false" for boolean options, format json.Number like JavaScript The reference CLI never type-checks option values and writes "true" and true identically, so a boolean option given the string "true" or "false" now takes that boolean with a feature_option_coerced warning. Other non-boolean values still error. A json.Number is formatted through its float64 value, as JavaScript parses every JSON number as a double: "1e6" is 1000000, "1.50" is 1.5. Adds edge-case tests checked against node 22's String() (nested empty arrays, null elements, subnormal and max doubles, -0, precision loss) and a test that a second merge of merged options is a no-op, which SameOptions relies on. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01M1zV4YDcDbkxa8xkQS5dMA --- CHANGELOG.md | 9 +++-- feature/options.go | 49 +++++++++++++++++------ feature/options_test.go | 88 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12a1948..691a3ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,9 +54,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 string, got []interface {}`. Arrays join with `,` (`["jq","tree"]` → `jq,tree`), numbers, booleans and `null` take their JavaScript string form, and a `config.WarnFeatureOptionCoerced` warning is reported. - Objects are still rejected, and boolean options stay strict. - Non-string defaults and undeclared options are converted too, so - `feature.env` never carries Go formatting such as `[jq tree]`. + Objects are still rejected. A boolean option given the string + `"true"` or `"false"` takes that boolean (the reference CLI writes + both forms identically) with the same warning; any other non-boolean + still errors. Non-string defaults and undeclared options are + converted too, so `feature.env` never carries Go formatting such as + `[jq tree]`. - **engine** — `Up` and `Build` called without `ConfigPath` now use the discovered `devcontainer.json`'s directory for local features and the compose working directory. Previously they always assumed diff --git a/feature/options.go b/feature/options.go index 9db31ea..1798814 100644 --- a/feature/options.go +++ b/feature/options.go @@ -25,7 +25,9 @@ import ( // A string-typed (or untyped) option given a non-string value is // converted the way the reference CLI converts it (see // coerceOptionString) and emits WarnFeatureOptionCoerced; only an -// object is rejected. Boolean-typed options stay strict. +// object is rejected. A boolean-typed option accepts the strings +// "true" and "false" as the booleans (also with +// WarnFeatureOptionCoerced) and rejects any other non-boolean. // // Returns the merged map and any non-fatal warnings. Errors are // validation failures (enum mismatch, type mismatch on declared options). @@ -64,14 +66,18 @@ func MergeOptions(meta config.FeatureMetadata, user map[string]any) (map[string] }) continue } - v, err := validateOptionValue(name, decl, val) + v, converted, err := validateOptionValue(name, decl, val) if err != nil { return nil, warnings, fmt.Errorf("feature %q: %w", meta.ID, err) } - if _, wasString := val.(string); !wasString && isStringOption(decl) { + if converted { + want := decl.Type + if want == "" { + want = "string" + } warnings = append(warnings, config.Warning{ Code: config.WarnFeatureOptionCoerced, - Message: fmt.Sprintf("feature %q: option %q expects a string; %T value converted to %q", meta.ID, name, val, v), + Message: fmt.Sprintf("feature %q: option %q expects a %s; %T value converted to %#v", meta.ID, name, want, val, v), }) } out[name] = v @@ -85,30 +91,42 @@ func isStringOption(opt config.FeatureOption) bool { } // validateOptionValue checks val against opt and returns the value to -// install with: val itself, or for a string option its string form. -func validateOptionValue(name string, opt config.FeatureOption, val any) (any, error) { - if isStringOption(opt) { +// install with: val itself, or for a string option its string form, +// or for a boolean option given the string "true" or "false" that +// boolean. converted reports whether the returned value differs in +// type from val. +func validateOptionValue(name string, opt config.FeatureOption, val any) (v any, converted bool, err error) { + switch { + case isStringOption(opt): s, ok := coerceOptionString(val) if !ok { - return nil, fmt.Errorf("option %q expects string, got %T", name, val) + return nil, false, fmt.Errorf("option %q expects string, got %T", name, val) + } + _, wasString := val.(string) + val, converted = s, !wasString + case opt.Type == "boolean": + // The reference CLI writes "true" and true identically + // (TRUE="true"), so the strings "true" and "false" mean the + // boolean. Any other string stays an error. + if s, ok := val.(string); ok && (s == "true" || s == "false") { + val, converted = s == "true", true } - val = s } if len(opt.Enum) > 0 { for _, allowed := range opt.Enum { if anyEqual(allowed, val) { - return val, nil + return val, converted, nil } } - return nil, fmt.Errorf("option %q value %v is not in enum %v", name, val, opt.Enum) + return nil, false, fmt.Errorf("option %q value %v is not in enum %v", name, val, opt.Enum) } if opt.Type == "boolean" { if _, ok := val.(bool); !ok { - return nil, fmt.Errorf("option %q expects boolean, got %T", name, val) + return nil, false, fmt.Errorf("option %q expects boolean, got %T", name, val) } } // Any other type: accept and let install.sh deal with it. - return val, nil + return val, converted, nil } // coerceOptionString converts a JSON option value to a string the way @@ -132,6 +150,11 @@ func coerceOptionString(v any) (string, bool) { case float32: return jsNumberString(float64(x)), true case json.Number: + // JavaScript parses every JSON number as a double, so + // "1e6" is 1000000 and a 19-digit integer loses precision. + if f, err := x.Float64(); err == nil { + return jsNumberString(f), true + } return x.String(), true case int: return strconv.Itoa(x), true diff --git a/feature/options_test.go b/feature/options_test.go index 36b4dcc..7edc594 100644 --- a/feature/options_test.go +++ b/feature/options_test.go @@ -2,6 +2,7 @@ package feature import ( "encoding/json" + "math" "reflect" "strings" "testing" @@ -287,3 +288,90 @@ func TestSerializeEnvFile_AfterCoercion(t *testing.T) { t.Errorf("env file = %q, want %q", got, "PACKAGES='jq,tree'\n") } } + +// Outputs checked against node 22: `${v}` for each JSON value. +func TestMergeOptions_MatchesJavaScriptString(t *testing.T) { + cases := []struct { + in any + want string + }{ + {[]any{[]any{}}, ""}, + {[]any{[]any{[]any{}}}, ""}, + {[]any{[]any{nil, nil}}, ","}, + {[]any{nil, "a", []any{nil}}, ",a,"}, + {[]any{true, 1.5, nil}, "true,1.5,"}, + {false, "false"}, + {1.23e-18, "1.23e-18"}, + {5e-324, "5e-324"}, + {1.7976931348623157e308, "1.7976931348623157e+308"}, + {0.1, "0.1"}, + {math.Copysign(0, -1), "0"}, + {float64(123456789012345678), "123456789012345680"}, + {json.Number("1e6"), "1000000"}, + {json.Number("1.50"), "1.5"}, + {json.Number("123456789012345678"), "123456789012345680"}, + } + for _, tc := range cases { + if got, _ := coerced(t, config.FeatureOption{Type: "string"}, tc.in); got != tc.want { + t.Errorf("%#v → %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestMergeOptions_BooleanAcceptsTrueFalseStrings(t *testing.T) { + meta := config.FeatureMetadata{ + ID: "common-utils", + Options: map[string]config.FeatureOption{"installZsh": {Type: "boolean", Default: true}}, + } + for in, want := range map[string]bool{"true": true, "false": false} { + merged, warns, err := MergeOptions(meta, map[string]any{"installZsh": in}) + if err != nil { + t.Fatalf("%q: %v", in, err) + } + if merged["installZsh"] != want { + t.Errorf("%q → %#v, want %v", in, merged["installZsh"], want) + } + if len(warns) != 1 || warns[0].Code != config.WarnFeatureOptionCoerced { + t.Errorf("%q: warnings = %v, want one %s", in, warns, config.WarnFeatureOptionCoerced) + } + } + // The env file is what the reference CLI writes for "true" and true. + merged, _, err := MergeOptions(meta, map[string]any{"installZsh": "false"}) + if err != nil { + t.Fatal(err) + } + if got := string(SerializeEnvFile(merged)); got != "INSTALLZSH='false'\n" { + t.Errorf("env file = %q", got) + } + for _, bad := range []any{"True", "yes", "", float64(1), nil, []any{"true"}} { + if _, _, err := MergeOptions(meta, map[string]any{"installZsh": bad}); err == nil || !strings.Contains(err.Error(), "expects boolean") { + t.Errorf("%#v: err = %v, want an expects-boolean error", bad, err) + } + } + if _, warns, err := MergeOptions(meta, map[string]any{"installZsh": true}); err != nil || len(warns) != 0 { + t.Errorf("true: warns=%v err=%v, want none", warns, err) + } +} + +func TestMergeOptions_CoercionIsIdempotent(t *testing.T) { + // SameOptions re-merges already merged options; a second merge must + // neither change the value nor warn again. + meta := config.FeatureMetadata{ + ID: "x", + Options: map[string]config.FeatureOption{ + "packages": {Type: "string"}, + "flag": {Type: "boolean"}, + }, + } + first, _, err := MergeOptions(meta, map[string]any{"packages": []any{"jq", float64(2)}, "flag": "true"}) + if err != nil { + t.Fatal(err) + } + second, warns, err := MergeOptions(meta, first) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(first, second) || len(warns) != 0 { + t.Errorf("second merge = %#v (warns %v), want %#v and no warnings", second, warns, first) + } +}