Skip to content

Commit c27793b

Browse files
aledbfclaude
andcommitted
fix(imagemeta): write the metadata label as JSON.stringify does
TS writes devcontainer.metadata with JSON.stringify: &, < and > as they are, and each entry's properties in the order its pick produced them (id and pickFeatureProperties for a Feature, pickConfigProperties for the configuration). Go escaped &<> and wrote Entry's field order. Object values keep sorted keys, a decoded Go map having no order; that remaining byte-level difference is recorded in docs/DIVERGENCES.md and in the ts-oracle goldens, which now also hold pick-ordered cases that match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4e91831 commit c27793b

4 files changed

Lines changed: 208 additions & 6 deletions

File tree

‎docs/DIVERGENCES.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,15 @@ touches a compared surface, reflected in the parity matrix.
5858
reads only the first pair and takes `B`. Variable expansion, stage lookup and the final
5959
stage name otherwise follow the reference (recorded in
6060
`internal/{docker,cli}/testdata/ts-oracle/dockerfile.json`).
61+
- **The `devcontainer.metadata` label writes object values with their keys sorted.** The
62+
label is TS's `JSON.stringify` of the entries: each entry's properties in TS's pick
63+
order (`pickFeatureProperties` for a Feature, `pickConfigProperties` for the
64+
configuration) and `&`, `<`, `>` unescaped, as in TS. Within a property's object value
65+
(a mount object, `customizations`, `portsAttributes`, …) the keys are sorted, because a
66+
decoded Go map keeps no order, where TS keeps the order they were written in; an entry
67+
given in another order (a base image's label written by another tool) is likewise
68+
rewritten in pick order. The parsed metadata is the same; only the label's bytes differ
69+
(`internal/imagemeta/testdata/ts-oracle/imagemeta.json` records both cases).
6170

6271
## Firm decisions & scope
6372

‎internal/imagemeta/metadata.go‎

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
package imagemeta
33

44
import (
5+
"bytes"
56
"encoding/json"
7+
"fmt"
8+
"slices"
69

710
"github.com/devcontainers/cli/internal/log"
811
)
@@ -41,6 +44,64 @@ type Entry struct {
4144
Entrypoint string `json:"entrypoint,omitempty"`
4245
}
4346

47+
// featureEntryKeys is the order TS writes a Feature's entry in: id, then
48+
// pickFeatureProperties.
49+
var featureEntryKeys = []string{
50+
"id", "onCreateCommand", "updateContentCommand", "postCreateCommand", "postStartCommand", "postAttachCommand",
51+
"init", "privileged", "capAdd", "securityOpt", "entrypoint", "mounts", "customizations",
52+
}
53+
54+
// configEntryKeys is the order TS writes the configuration's entry in
55+
// (pickConfigProperties); entrypoint, which only a Feature's entry has, last.
56+
var configEntryKeys = []string{
57+
"onCreateCommand", "updateContentCommand", "postCreateCommand", "postStartCommand", "postAttachCommand",
58+
"waitFor", "customizations", "mounts", "containerEnv", "containerUser", "init", "privileged", "capAdd",
59+
"securityOpt", "remoteUser", "userEnvProbe", "remoteEnv", "overrideCommand", "portsAttributes",
60+
"otherPortsAttributes", "forwardPorts", "shutdownAction", "updateRemoteUserUID", "hostRequirements",
61+
"entrypoint",
62+
}
63+
64+
// MarshalJSON writes the entry's properties in the order TS writes them: a
65+
// Feature's entry (one with an id) in pickFeatureProperties order, then the
66+
// other properties in configEntryKeys order; any other entry in
67+
// pickConfigProperties order (configEntryKeys names every property but id).
68+
// Object values are written with their keys sorted (a Go map keeps no order).
69+
// &, < and > are not escaped, as JSON.stringify does not escape them.
70+
func (e Entry) MarshalJSON() ([]byte, error) {
71+
type plain Entry
72+
var data bytes.Buffer
73+
enc := json.NewEncoder(&data)
74+
enc.SetEscapeHTML(false)
75+
if err := enc.Encode(plain(e)); err != nil {
76+
return nil, err
77+
}
78+
var fields map[string]json.RawMessage
79+
if err := json.Unmarshal(data.Bytes(), &fields); err != nil {
80+
return nil, err
81+
}
82+
order := configEntryKeys
83+
if e.ID != "" {
84+
order = append(slices.Clone(featureEntryKeys), configEntryKeys...)
85+
}
86+
var out bytes.Buffer
87+
out.WriteByte('{')
88+
written := 0
89+
for _, k := range order {
90+
v, ok := fields[k]
91+
if !ok {
92+
continue
93+
}
94+
delete(fields, k) // a Feature's order names some keys twice
95+
if written > 0 {
96+
out.WriteByte(',')
97+
}
98+
fmt.Fprintf(&out, "%q:%s", k, v)
99+
written++
100+
}
101+
out.WriteByte('}')
102+
return out.Bytes(), nil
103+
}
104+
44105
// ReadMetadataFromLabels extracts metadata entries from Docker image/container labels.
45106
func ReadMetadataFromLabels(labels map[string]string, logger log.Logger) []Entry {
46107
raw, ok := labels[MetadataLabel]
@@ -74,7 +135,10 @@ func GenerateMetadataLabel(entries []Entry) string {
74135
}
75136
// 0.88 (#1199): always write the devcontainer.metadata label as a JSON array,
76137
// even for a single entry — tools that expect an array (e.g. Zed) fail on a
77-
// bare object.
78-
data, _ := json.Marshal(entries)
79-
return string(data)
138+
// bare object. JSON.stringify leaves &, < and > as they are.
139+
var data bytes.Buffer
140+
enc := json.NewEncoder(&data)
141+
enc.SetEscapeHTML(false)
142+
_ = enc.Encode(entries) // an Entry holds JSON values only
143+
return string(bytes.TrimSuffix(data.Bytes(), []byte("\n")))
80144
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package imagemeta
2+
3+
import (
4+
"reflect"
5+
"slices"
6+
"strings"
7+
"testing"
8+
)
9+
10+
// The label is JSON.stringify of the entries: &, < and > are written as they
11+
// are, and each entry's properties in TS's pick order.
12+
func TestGenerateMetadataLabelWritesWhatJSONStringifyWrites(t *testing.T) {
13+
init := true
14+
got := GenerateMetadataLabel([]Entry{
15+
{ID: "f", Entrypoint: "/e.sh", Init: &init, OnCreateCommand: "a && b"},
16+
{RemoteUser: "u", PostCreateCommand: "echo <x> > /y", ContainerEnv: map[string]string{"A": "1"}},
17+
})
18+
want := `[{"id":"f","onCreateCommand":"a && b","init":true,"entrypoint":"/e.sh"},{"postCreateCommand":"echo <x> > /y","containerEnv":{"A":"1"},"remoteUser":"u"}]`
19+
if got != want {
20+
t.Errorf("label = %s\nwant %s", got, want)
21+
}
22+
if got := GenerateMetadataLabel([]Entry{{}}); got != "" {
23+
t.Errorf("label without entries = %q, want none", got)
24+
}
25+
}
26+
27+
// configEntryKeys orders every property of an Entry but id, so MarshalJSON
28+
// writes all of them.
29+
func TestEntryKeyOrdersNameEveryProperty(t *testing.T) {
30+
typ := reflect.TypeFor[Entry]()
31+
for i := range typ.NumField() {
32+
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
33+
if name != "id" && !slices.Contains(configEntryKeys, name) {
34+
t.Errorf("property %q is in no key order", name)
35+
}
36+
}
37+
if !slices.Contains(featureEntryKeys, "id") {
38+
t.Error("featureEntryKeys has no id")
39+
}
40+
}

‎internal/imagemeta/testdata/ts-oracle/imagemeta.json‎

Lines changed: 92 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1360,11 +1360,47 @@
13601360
}
13611361
]
13621362
],
1363-
"divergence": "unresolved: TS writes a Feature entry's keys in pickFeatureProperties order (id, lifecycle hooks, init, ...) and a config entry's in pickConfigProperties order; Go writes Entry's field order (internal/imagemeta/metadata.go, not changed here)",
1363+
"divergence": "docs/DIVERGENCES.md: the label writes an entry's object values (here a mount) with their keys sorted, a Go map keeping no order",
13641364
"result": "LABEL devcontainer.metadata=\"[ \\\n{\\\"id\\\":\\\"ghcr.io/devcontainers/features/node:1\\\",\\\"onCreateCommand\\\":\\\"a\\\",\\\"init\\\":true,\\\"privileged\\\":false,\\\"capAdd\\\":[\\\"SYS_PTRACE\\\"],\\\"securityOpt\\\":[\\\"seccomp=unconfined\\\"],\\\"entrypoint\\\":\\\"/e.sh\\\",\\\"mounts\\\":[{\\\"type\\\":\\\"volume\\\",\\\"source\\\":\\\"v\\\",\\\"target\\\":\\\"/v\\\"}],\\\"customizations\\\":{\\\"vscode\\\":{\\\"extensions\\\":[\\\"x\\\"]}}} \\\n]\""
13651365
},
13661366
{
1367-
"name": "config entry in pick order",
1367+
"name": "feature entry in pick order, nested keys sorted",
1368+
"fn": "getDevcontainerMetadataLabel",
1369+
"args": [
1370+
[
1371+
{
1372+
"id": "ghcr.io/devcontainers/features/node:1",
1373+
"onCreateCommand": "a",
1374+
"init": true,
1375+
"privileged": false,
1376+
"capAdd": [
1377+
"SYS_PTRACE"
1378+
],
1379+
"securityOpt": [
1380+
"seccomp=unconfined"
1381+
],
1382+
"entrypoint": "/e.sh",
1383+
"mounts": [
1384+
{
1385+
"source": "v",
1386+
"target": "/v",
1387+
"type": "volume"
1388+
}
1389+
],
1390+
"customizations": {
1391+
"vscode": {
1392+
"extensions": [
1393+
"x"
1394+
]
1395+
}
1396+
}
1397+
}
1398+
]
1399+
],
1400+
"result": "LABEL devcontainer.metadata=\"[ \\\n{\\\"id\\\":\\\"ghcr.io/devcontainers/features/node:1\\\",\\\"onCreateCommand\\\":\\\"a\\\",\\\"init\\\":true,\\\"privileged\\\":false,\\\"capAdd\\\":[\\\"SYS_PTRACE\\\"],\\\"securityOpt\\\":[\\\"seccomp=unconfined\\\"],\\\"entrypoint\\\":\\\"/e.sh\\\",\\\"mounts\\\":[{\\\"source\\\":\\\"v\\\",\\\"target\\\":\\\"/v\\\",\\\"type\\\":\\\"volume\\\"}],\\\"customizations\\\":{\\\"vscode\\\":{\\\"extensions\\\":[\\\"x\\\"]}}} \\\n]\""
1401+
},
1402+
{
1403+
"name": "config entry out of pick order",
13681404
"fn": "getDevcontainerMetadataLabel",
13691405
"args": [
13701406
[
@@ -1414,9 +1450,62 @@
14141450
}
14151451
]
14161452
],
1417-
"divergence": "unresolved: TS writes a Feature entry's keys in pickFeatureProperties order (id, lifecycle hooks, init, ...) and a config entry's in pickConfigProperties order; Go writes Entry's field order (internal/imagemeta/metadata.go, not changed here)",
1453+
"divergence": "docs/DIVERGENCES.md: the label writes an entry's properties in TS's pick order, not in the order of the object given (an Entry keeps none)",
14181454
"result": "LABEL devcontainer.metadata=\"[ \\\n{\\\"postCreateCommand\\\":\\\"p\\\",\\\"waitFor\\\":\\\"onCreateCommand\\\",\\\"customizations\\\":{\\\"vscode\\\":{}},\\\"mounts\\\":[\\\"type=bind,src=/a,dst=/b\\\"],\\\"containerEnv\\\":{\\\"A\\\":\\\"1\\\"},\\\"containerUser\\\":\\\"c\\\",\\\"init\\\":true,\\\"privileged\\\":true,\\\"remoteUser\\\":\\\"r\\\",\\\"remoteEnv\\\":{\\\"B\\\":\\\"2\\\"},\\\"overrideCommand\\\":false,\\\"portsAttributes\\\":{\\\"3000\\\":{\\\"label\\\":\\\"x\\\"}},\\\"otherPortsAttributes\\\":{\\\"onAutoForward\\\":\\\"ignore\\\"},\\\"forwardPorts\\\":[3000],\\\"shutdownAction\\\":\\\"none\\\",\\\"updateRemoteUserUID\\\":true,\\\"hostRequirements\\\":{\\\"cpus\\\":2},\\\"userEnvProbe\\\":\\\"none\\\",\\\"capAdd\\\":[\\\"NET_ADMIN\\\"],\\\"securityOpt\\\":[\\\"label=disable\\\"]} \\\n]\""
14191455
},
1456+
{
1457+
"name": "config entry in pick order",
1458+
"fn": "getDevcontainerMetadataLabel",
1459+
"args": [
1460+
[
1461+
{
1462+
"postCreateCommand": "p",
1463+
"waitFor": "onCreateCommand",
1464+
"customizations": {
1465+
"vscode": {}
1466+
},
1467+
"mounts": [
1468+
"type=bind,src=/a,dst=/b"
1469+
],
1470+
"containerEnv": {
1471+
"A": "1"
1472+
},
1473+
"containerUser": "c",
1474+
"init": true,
1475+
"privileged": true,
1476+
"capAdd": [
1477+
"NET_ADMIN"
1478+
],
1479+
"securityOpt": [
1480+
"label=disable"
1481+
],
1482+
"remoteUser": "r",
1483+
"userEnvProbe": "none",
1484+
"remoteEnv": {
1485+
"B": "2"
1486+
},
1487+
"overrideCommand": false,
1488+
"portsAttributes": {
1489+
"3000": {
1490+
"label": "x"
1491+
}
1492+
},
1493+
"otherPortsAttributes": {
1494+
"onAutoForward": "ignore"
1495+
},
1496+
"forwardPorts": [
1497+
3000
1498+
],
1499+
"shutdownAction": "none",
1500+
"updateRemoteUserUID": true,
1501+
"hostRequirements": {
1502+
"cpus": 2
1503+
}
1504+
}
1505+
]
1506+
],
1507+
"result": "LABEL devcontainer.metadata=\"[ \\\n{\\\"postCreateCommand\\\":\\\"p\\\",\\\"waitFor\\\":\\\"onCreateCommand\\\",\\\"customizations\\\":{\\\"vscode\\\":{}},\\\"mounts\\\":[\\\"type=bind,src=/a,dst=/b\\\"],\\\"containerEnv\\\":{\\\"A\\\":\\\"1\\\"},\\\"containerUser\\\":\\\"c\\\",\\\"init\\\":true,\\\"privileged\\\":true,\\\"capAdd\\\":[\\\"NET_ADMIN\\\"],\\\"securityOpt\\\":[\\\"label=disable\\\"],\\\"remoteUser\\\":\\\"r\\\",\\\"userEnvProbe\\\":\\\"none\\\",\\\"remoteEnv\\\":{\\\"B\\\":\\\"2\\\"},\\\"overrideCommand\\\":false,\\\"portsAttributes\\\":{\\\"3000\\\":{\\\"label\\\":\\\"x\\\"}},\\\"otherPortsAttributes\\\":{\\\"onAutoForward\\\":\\\"ignore\\\"},\\\"forwardPorts\\\":[3000],\\\"shutdownAction\\\":\\\"none\\\",\\\"updateRemoteUserUID\\\":true,\\\"hostRequirements\\\":{\\\"cpus\\\":2}} \\\n]\""
1508+
},
14201509
{
14211510
"name": "getEntPasswd 'root'",
14221511
"fn": "getEntPasswdShellCommand",

0 commit comments

Comments
 (0)