Skip to content

Commit a8d28a4

Browse files
committed
refactor: streamline variable substitution methods and enhance template rendering
1 parent 6c697e4 commit a8d28a4

7 files changed

Lines changed: 120 additions & 37 deletions

File tree

‎internal/cli/collection_commands.go‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -685,17 +685,18 @@ func generateDocs(projectFolder, registry, namespace, githubOwner, githubRepo, c
685685
urlToConfig = fmt.Sprintf("https://github.com/%s/%s/blob/main/%s/%s/%s", githubOwner, githubRepo, basePathTrimmed, f, metadataFile)
686686
}
687687

688-
readme := template
689-
readme = strings.Replace(readme, "#{Id}", id, 1)
690-
readme = strings.Replace(readme, "#{Name}", name, 1)
691-
readme = strings.Replace(readme, "#{Description}", desc, 1)
692-
readme = strings.Replace(readme, "#{OptionsTable}", generateOptionsMarkdown(std, meta), 1)
693-
readme = strings.Replace(readme, "#{Notes}", notes, 1)
694-
readme = strings.Replace(readme, "#{RepoUrl}", urlToConfig, 1)
695-
readme = strings.Replace(readme, "#{Registry}", registry, 1)
696-
readme = strings.Replace(readme, "#{Namespace}", namespace, 1)
697-
readme = strings.Replace(readme, "#{Version}", version, 1)
698-
readme = strings.Replace(readme, "#{Customizations}", generateCustomizationsMarkdown(meta), 1)
688+
readme := renderDocsTemplate(template, map[string]string{
689+
"Id": id,
690+
"Name": name,
691+
"Description": desc,
692+
"OptionsTable": generateOptionsMarkdown(std, meta),
693+
"Notes": notes,
694+
"RepoUrl": urlToConfig,
695+
"Registry": registry,
696+
"Namespace": namespace,
697+
"Version": version,
698+
"Customizations": generateCustomizationsMarkdown(meta),
699+
})
699700

700701
if header := generateDocsHeader(meta); header != "" {
701702
readme = header + readme
@@ -710,6 +711,14 @@ func generateDocs(projectFolder, registry, namespace, githubOwner, githubRepo, c
710711
return nil
711712
}
712713

714+
func renderDocsTemplate(template string, values map[string]string) string {
715+
pairs := make([]string, 0, len(values)*2)
716+
for name, value := range values {
717+
pairs = append(pairs, "#{"+name+"}", value)
718+
}
719+
return strings.NewReplacer(pairs...).Replace(template)
720+
}
721+
713722
// generateOptionsMarkdown renders the options table with columns and row order
714723
// matching TS: "| Options Id | Description | Type | Default Value |" in the JSON's
715724
// insertion order. Returns "" only when the metadata has no "options" key.

‎internal/cli/collection_commands_test.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,16 @@ import (
77
"testing"
88
)
99

10+
func TestRenderDocsTemplate(t *testing.T) {
11+
got := renderDocsTemplate("#{Name} / #{Name} / #{Unknown}", map[string]string{
12+
"Name": "tool",
13+
})
14+
want := "tool / tool / #{Unknown}"
15+
if got != want {
16+
t.Errorf("renderDocsTemplate() = %q, want %q", got, want)
17+
}
18+
}
19+
1020
// writeFeature writes a devcontainer-feature.json into <dir>/<name>/.
1121
func writeFeature(t *testing.T, base, name, json string) {
1222
t.Helper()

‎internal/cli/mounts.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,20 +104,20 @@ func composeVolumeSpecsFromMetadata(entries []interface{}, devcontainerID string
104104
func mountFromMetadata(entry interface{}, devcontainerID string) (dockermount.Mount, error) {
105105
switch raw := entry.(type) {
106106
case string:
107-
spec := strings.ReplaceAll(raw, "${devcontainerId}", devcontainerID)
107+
spec := config.SubstituteDevContainerIDString(devcontainerID, raw)
108108
return docker.ParseMountSpec(spec)
109109
case map[string]interface{}:
110110
target, _ := raw["target"].(string)
111111
// ${devcontainerId} must resolve in target too, not only source — the
112112
// string form substitutes the whole spec, so the object form has to match
113113
// (e.g. target "/cache/${devcontainerId}").
114-
target = strings.ReplaceAll(target, "${devcontainerId}", devcontainerID)
114+
target = config.SubstituteDevContainerIDString(devcontainerID, target)
115115
if target == "" {
116116
return dockermount.Mount{}, fmt.Errorf("mount requires a target/destination")
117117
}
118118

119119
source, _ := raw["source"].(string)
120-
source = strings.ReplaceAll(source, "${devcontainerId}", devcontainerID)
120+
source = config.SubstituteDevContainerIDString(devcontainerID, source)
121121
mountType, _ := raw["type"].(string)
122122
if mountType == "" {
123123
mountType = string(dockermount.TypeBind)

‎internal/config/varsub.go‎

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@ type HostSubContext struct {
2424

2525
// SubstituteHost resolves ${localEnv:X}, ${localWorkspaceFolder}, etc.
2626
func SubstituteHost(ctx HostSubContext, value interface{}) interface{} {
27+
replace := hostReplacer(ctx)
28+
return substituteRecursive(replace, value)
29+
}
30+
31+
// SubstituteHostString is the typed string variant of SubstituteHost.
32+
func SubstituteHostString(ctx HostSubContext, value string) string {
33+
return resolveString(hostReplacer(ctx), value)
34+
}
35+
36+
func hostReplacer(ctx HostSubContext) replaceFn {
2737
env := ctx.Env
2838
if ctx.Platform == "win32" {
2939
env = normalizeEnvKeys(env)
@@ -37,9 +47,9 @@ func SubstituteHost(ctx HostSubContext, value interface{}) interface{} {
3747
}, ctx.ContainerWorkspaceFolder)
3848
}
3949

40-
return substituteRecursive(func(match, variable string, args []string) string {
50+
return func(match, variable string, args []string) string {
4151
return replaceHostVar(isWin, env, ctx, match, variable, args)
42-
}, value)
52+
}
4353
}
4454

4555
// SubstituteDevContainerID resolves ${devcontainerId} from id-labels.
@@ -50,9 +60,33 @@ func SubstituteDevContainerID(idLabels map[string]string, value interface{}) int
5060
if cachedID == "" && idLabels != nil {
5161
cachedID = ComputeDevContainerID(idLabels)
5262
}
53-
if cachedID != "" {
54-
return cachedID
55-
}
63+
return substituteDevContainerID(match, cachedID)
64+
}
65+
return match
66+
}, value)
67+
}
68+
69+
// SubstituteDevContainerIDString resolves ${devcontainerId} when the ID has
70+
// already been computed. Keeping the parsing here prevents callers from
71+
// implementing variable substitution with ad-hoc string replacements.
72+
func SubstituteDevContainerIDString(devcontainerID, value string) string {
73+
return resolveString(func(match, variable string, _ []string) string {
74+
if variable == "devcontainerId" {
75+
return substituteDevContainerID(match, devcontainerID)
76+
}
77+
return match
78+
}, value)
79+
}
80+
81+
// SubstituteTemplateOptions resolves ${templateOption:name} using the supplied
82+
// option values. Unknown options remain unchanged.
83+
func SubstituteTemplateOptions(options map[string]string, value string) string {
84+
return resolveString(func(match, variable string, args []string) string {
85+
if variable != "templateOption" || len(args) == 0 {
86+
return match
87+
}
88+
if replacement, ok := options[strings.TrimSpace(args[0])]; ok {
89+
return replacement
5690
}
5791
return match
5892
}, value)
@@ -99,6 +133,13 @@ func ComputeDevContainerID(idLabels map[string]string) string {
99133

100134
type replaceFn func(match, variable string, args []string) string
101135

136+
func substituteDevContainerID(match, devcontainerID string) string {
137+
if devcontainerID == "" {
138+
return match
139+
}
140+
return devcontainerID
141+
}
142+
102143
func substituteRecursive(replace replaceFn, value interface{}) interface{} {
103144
switch v := value.(type) {
104145
case string:

‎internal/config/varsub_test.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,37 @@ func TestSubstituteDevContainerID_SortedKeys(t *testing.T) {
120120
}
121121
}
122122

123+
func TestSubstituteDevContainerIDString(t *testing.T) {
124+
tests := []struct {
125+
name string
126+
id string
127+
value string
128+
want string
129+
}{
130+
{"multiple", "abc123", "cache-${devcontainerId}/${devcontainerId}", "cache-abc123/abc123"},
131+
{"unknown preserved", "abc123", "${unknown}:${devcontainerId}", "${unknown}:abc123"},
132+
{"similar name preserved", "abc123", "${devcontainerIdExtra}", "${devcontainerIdExtra}"},
133+
{"empty id preserved", "", "cache-${devcontainerId}", "cache-${devcontainerId}"},
134+
}
135+
136+
for _, tt := range tests {
137+
t.Run(tt.name, func(t *testing.T) {
138+
if got := SubstituteDevContainerIDString(tt.id, tt.value); got != tt.want {
139+
t.Errorf("SubstituteDevContainerIDString(%q, %q) = %q, want %q", tt.id, tt.value, got, tt.want)
140+
}
141+
})
142+
}
143+
}
144+
145+
func TestSubstituteTemplateOptions(t *testing.T) {
146+
options := map[string]string{"image": "ubuntu", "greeting": "hello"}
147+
value := "${templateOption:image}:${templateOption: greeting }:${unknown}"
148+
want := "ubuntu:hello:${unknown}"
149+
if got := SubstituteTemplateOptions(options, value); got != want {
150+
t.Errorf("SubstituteTemplateOptions() = %q, want %q", got, want)
151+
}
152+
}
153+
123154
func TestSubstituteContainer(t *testing.T) {
124155
containerEnv := map[string]string{
125156
"PATH": "/usr/bin:/usr/local/bin",

‎internal/lifecycle/initialize.go‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"fmt"
66
"os"
77
"os/exec"
8-
"path/filepath"
98
"strings"
109
"sync"
1110

@@ -73,9 +72,14 @@ func RunInitializeCommand(ctx context.Context, logger log.Logger, cmd *config.Li
7372
}
7473

7574
func substituteLocalVars(s string, workspaceFolder string) string {
76-
s = strings.ReplaceAll(s, "${localWorkspaceFolder}", workspaceFolder)
77-
s = strings.ReplaceAll(s, "${localWorkspaceFolderBasename}", filepath.Base(workspaceFolder))
78-
return s
75+
platform := ""
76+
if config.IsWindows() {
77+
platform = "win32"
78+
}
79+
return config.SubstituteHostString(config.HostSubContext{
80+
Platform: platform,
81+
LocalWorkspaceFolder: workspaceFolder,
82+
}, s)
7983
}
8084

8185
func runHostCommand(ctx context.Context, command string, workDir string) error {

‎internal/templates/apply.go‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import (
66
"fmt"
77
"os"
88
"path/filepath"
9-
"regexp"
109
"strings"
1110

11+
"github.com/devcontainers/cli/internal/config"
1212
"github.com/devcontainers/cli/internal/log"
1313
"github.com/devcontainers/cli/internal/oci"
1414
"github.com/devcontainers/cli/internal/pfs"
@@ -291,19 +291,7 @@ func applyOptionDefaults(fsys pfs.FS, extractDir string, userOptions map[string]
291291
return merged
292292
}
293293

294-
var templateOptionRegex = regexp.MustCompile(`\$\{templateOption:\s*(\w+)\s*\}`)
295-
296294
// substituteTemplateOptions replaces ${templateOption:name} with the provided values.
297295
func substituteTemplateOptions(content string, options map[string]string) string {
298-
return templateOptionRegex.ReplaceAllStringFunc(content, func(match string) string {
299-
sub := templateOptionRegex.FindStringSubmatch(match)
300-
if len(sub) < 2 {
301-
return match
302-
}
303-
name := sub[1]
304-
if val, ok := options[name]; ok {
305-
return val
306-
}
307-
return match
308-
})
296+
return config.SubstituteTemplateOptions(options, content)
309297
}

0 commit comments

Comments
 (0)