11package imagemeta
22
3+ import (
4+ "fmt"
5+ "regexp"
6+ "strconv"
7+ "strings"
8+ )
9+
310// MergedConfig holds the result of merging devcontainer.json config with
411// image metadata entries. Lifecycle hooks are accumulated as arrays.
512type MergedConfig struct {
@@ -55,31 +62,35 @@ func MergeConfiguration(entries []Entry) *MergedConfig {
5562 // Process entries in order. For lifecycle hooks, iterate all.
5663 // For scalars, the last non-empty value wins (iterate in reverse for scalars).
5764 for _ , e := range entries {
58- // Lifecycle hooks — always append
59- if e .OnCreateCommand != nil {
65+ // Lifecycle hooks — collect every truthy command (TS `if (command)`), so an
66+ // empty-string command is skipped rather than emitted as a spurious "" entry.
67+ if isNonEmptyCommand (e .OnCreateCommand ) {
6068 m .OnCreateCommands = append (m .OnCreateCommands , e .OnCreateCommand )
6169 }
62- if e .UpdateContentCommand != nil {
70+ if isNonEmptyCommand ( e .UpdateContentCommand ) {
6371 m .UpdateContentCommands = append (m .UpdateContentCommands , e .UpdateContentCommand )
6472 }
65- if e .PostCreateCommand != nil {
73+ if isNonEmptyCommand ( e .PostCreateCommand ) {
6674 m .PostCreateCommands = append (m .PostCreateCommands , e .PostCreateCommand )
6775 }
68- if e .PostStartCommand != nil {
76+ if isNonEmptyCommand ( e .PostStartCommand ) {
6977 m .PostStartCommands = append (m .PostStartCommands , e .PostStartCommand )
7078 }
71- if e .PostAttachCommand != nil {
79+ if isNonEmptyCommand ( e .PostAttachCommand ) {
7280 m .PostAttachCommands = append (m .PostAttachCommands , e .PostAttachCommand )
7381 }
7482
75- // Entrypoints — collect from features
83+ // Entrypoints — collect ALL non-empty entrypoints (TS collectOrUndefined has
84+ // NO de-dup): two features that register the same entrypoint script must both
85+ // run, so appendUnique would wrongly drop one.
7686 if e .Entrypoint != "" {
77- m .Entrypoints = appendUnique (m .Entrypoints , [] string { e .Entrypoint } )
87+ m .Entrypoints = append (m .Entrypoints , e .Entrypoint )
7888 }
7989
8090 // Arrays — union
8191 m .CapAdd = appendUnique (m .CapAdd , e .CapAdd )
8292 m .SecurityOpt = appendUnique (m .SecurityOpt , e .SecurityOpt )
93+ // forwardPorts/mounts accumulate here and are de-duplicated after the loop.
8394 m .ForwardPorts = append (m .ForwardPorts , e .ForwardPorts ... )
8495 m .Mounts = append (m .Mounts , e .Mounts ... )
8596
@@ -138,9 +149,6 @@ func MergeConfiguration(entries []Entry) *MergedConfig {
138149 if m .OtherPortsAttributes == nil && e .OtherPortsAttributes != nil {
139150 m .OtherPortsAttributes = e .OtherPortsAttributes
140151 }
141- if m .HostRequirements == nil && e .HostRequirements != nil {
142- m .HostRequirements = e .HostRequirements
143- }
144152 if len (m .RunArgs ) == 0 && len (e .RunArgs ) > 0 {
145153 m .RunArgs = append ([]string {}, e .RunArgs ... )
146154 }
@@ -152,9 +160,231 @@ func MergeConfiguration(entries []Entry) *MergedConfig {
152160 }
153161 }
154162
163+ // mounts: keep the LAST mount per target (TS mergeMounts de-dupes by target),
164+ // so a later feature/config mount overrides an earlier one to the same path.
165+ m .Mounts = dedupeMountsByTarget (m .Mounts )
166+ // forwardPorts: de-dupe, treating the number N and the string "localhost:N" as
167+ // the same port (TS mergeForwardPorts normalizes then Set-de-dupes).
168+ m .ForwardPorts = dedupeForwardPorts (m .ForwardPorts )
169+ // hostRequirements: per-field max across all entries (TS mergeHostRequirements),
170+ // not last-wins of the whole object.
171+ m .HostRequirements = mergeHostRequirements (entries )
172+
155173 return m
156174}
157175
176+ // isNonEmptyCommand reports whether a lifecycle command is "truthy" the way TS
177+ // treats it: a nil or empty-string command is skipped; arrays/objects are kept.
178+ func isNonEmptyCommand (cmd interface {}) bool {
179+ return cmd != nil && cmd != ""
180+ }
181+
182+ // mountTarget returns the container-side target of a mount (object or string
183+ // spec), used as the de-dup key. A string with no target= key is its own key so
184+ // distinct strings never collide.
185+ func mountTarget (mnt interface {}) string {
186+ switch v := mnt .(type ) {
187+ case map [string ]interface {}:
188+ t , _ := v ["target" ].(string )
189+ return t
190+ case string :
191+ for _ , part := range strings .Split (v , "," ) {
192+ k , val , ok := strings .Cut (part , "=" )
193+ if ! ok {
194+ continue
195+ }
196+ switch strings .TrimSpace (k ) {
197+ case "target" , "destination" , "dst" :
198+ return val
199+ }
200+ }
201+ return v
202+ }
203+ return ""
204+ }
205+
206+ func dedupeMountsByTarget (mounts []interface {}) []interface {} {
207+ if len (mounts ) == 0 {
208+ return mounts
209+ }
210+ lastIdx := make (map [string ]int , len (mounts ))
211+ for i , mnt := range mounts {
212+ lastIdx [mountTarget (mnt )] = i
213+ }
214+ out := make ([]interface {}, 0 , len (mounts ))
215+ for i , mnt := range mounts {
216+ if lastIdx [mountTarget (mnt )] == i {
217+ out = append (out , mnt )
218+ }
219+ }
220+ return out
221+ }
222+
223+ // forwardPortNumber returns (N, true) for a numeric port (number or numeric
224+ // string is NOT treated as a number by TS — only actual JSON numbers are).
225+ func forwardPortNumber (p interface {}) (int , bool ) {
226+ switch v := p .(type ) {
227+ case float64 :
228+ return int (v ), true
229+ case int :
230+ return v , true
231+ case int64 :
232+ return int (v ), true
233+ }
234+ return 0 , false
235+ }
236+
237+ var localhostPortRe = regexp .MustCompile (`^localhost:\d+$` )
238+
239+ func dedupeForwardPorts (ports []interface {}) []interface {} {
240+ if len (ports ) == 0 {
241+ return ports
242+ }
243+ seen := make (map [string ]bool , len (ports ))
244+ var keys []string
245+ for _ , p := range ports {
246+ key := ""
247+ if n , ok := forwardPortNumber (p ); ok {
248+ key = fmt .Sprintf ("localhost:%d" , n )
249+ } else {
250+ key = fmt .Sprintf ("%v" , p )
251+ }
252+ if ! seen [key ] {
253+ seen [key ] = true
254+ keys = append (keys , key )
255+ }
256+ }
257+ // Denormalize: a "localhost:N" key becomes the number N; anything else stays a
258+ // string — matching TS's final .map(port => /localhost:\d+/.test ? parseInt : port).
259+ out := make ([]interface {}, 0 , len (keys ))
260+ for _ , k := range keys {
261+ if localhostPortRe .MatchString (k ) {
262+ var n int
263+ fmt .Sscanf (k , "localhost:%d" , & n )
264+ out = append (out , float64 (n ))
265+ } else {
266+ out = append (out , k )
267+ }
268+ }
269+ return out
270+ }
271+
272+ var byteSizeRe = regexp .MustCompile (`^(\d+)([tgmk]b)?$` )
273+
274+ // parseBytes mirrors the TS parseBytes: "8gb" -> 8589934592, unrecognized -> 0.
275+ func parseBytes (s string ) int64 {
276+ mm := byteSizeRe .FindStringSubmatch (s )
277+ if mm == nil {
278+ return 0
279+ }
280+ n , _ := strconv .ParseInt (mm [1 ], 10 , 64 )
281+ unit := int64 (1 )
282+ if mm [2 ] != "" {
283+ switch mm [2 ][0 ] {
284+ case 't' :
285+ unit = 1 << 40
286+ case 'g' :
287+ unit = 1 << 30
288+ case 'm' :
289+ unit = 1 << 20
290+ case 'k' :
291+ unit = 1 << 10
292+ }
293+ }
294+ return n * unit
295+ }
296+
297+ func hrFloat (v interface {}) float64 {
298+ switch n := v .(type ) {
299+ case float64 :
300+ return n
301+ case int :
302+ return float64 (n )
303+ case int64 :
304+ return float64 (n )
305+ }
306+ return 0
307+ }
308+
309+ func hrString (v interface {}) string {
310+ if s , ok := v .(string ); ok {
311+ return s
312+ }
313+ return "0"
314+ }
315+
316+ // mergeHostRequirements takes the per-field max of cpus/memory/storage and merges
317+ // gpu across all entries, matching TS mergeHostRequirements. Returns nil when no
318+ // entry sets any requirement.
319+ func mergeHostRequirements (entries []Entry ) interface {} {
320+ var cpus float64
321+ var memory , storage int64
322+ var gpu interface {}
323+ for _ , e := range entries {
324+ hr , ok := e .HostRequirements .(map [string ]interface {})
325+ if ! ok {
326+ continue
327+ }
328+ if c := hrFloat (hr ["cpus" ]); c > cpus {
329+ cpus = c
330+ }
331+ if b := parseBytes (hrString (hr ["memory" ])); b > memory {
332+ memory = b
333+ }
334+ if b := parseBytes (hrString (hr ["storage" ])); b > storage {
335+ storage = b
336+ }
337+ gpu = mergeGPURequirements (gpu , hr ["gpu" ])
338+ }
339+ if cpus == 0 && memory == 0 && storage == 0 && gpu == nil {
340+ return nil
341+ }
342+ res := map [string ]interface {}{"cpus" : cpus }
343+ if memory != 0 {
344+ res ["memory" ] = strconv .FormatInt (memory , 10 )
345+ }
346+ if storage != 0 {
347+ res ["storage" ] = strconv .FormatInt (storage , 10 )
348+ }
349+ if gpu != nil {
350+ res ["gpu" ] = gpu
351+ }
352+ return res
353+ }
354+
355+ // mergeGPURequirements ports TS mergeGpuRequirements: undefined/false yields the
356+ // other; two "optional" stay "optional"; otherwise take the per-field max of the
357+ // object forms (a non-object contributes {}).
358+ func mergeGPURequirements (a , b interface {}) interface {} {
359+ if a == nil || a == false {
360+ return b
361+ }
362+ if b == nil || b == false {
363+ return a
364+ }
365+ if a == "optional" && b == "optional" {
366+ return "optional"
367+ }
368+ ao , _ := a .(map [string ]interface {})
369+ bo , _ := b .(map [string ]interface {})
370+ cores := hrFloat (ao ["cores" ])
371+ if c := hrFloat (bo ["cores" ]); c > cores {
372+ cores = c
373+ }
374+ mem := parseBytes (hrString (ao ["memory" ]))
375+ if m := parseBytes (hrString (bo ["memory" ])); m > mem {
376+ mem = m
377+ }
378+ res := map [string ]interface {}{}
379+ if cores != 0 {
380+ res ["cores" ] = cores
381+ }
382+ if mem != 0 {
383+ res ["memory" ] = strconv .FormatInt (mem , 10 )
384+ }
385+ return res
386+ }
387+
158388// appendUnique appends items from src to dst, skipping duplicates.
159389func appendUnique (dst , src []string ) []string {
160390 seen := make (map [string ]bool , len (dst ))
0 commit comments