github.com/thajeztah/cli@v0.0.0-20240223162942-dc6bfac81a8b/cli/command/context.go (about) 1 // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: 2 //go:build go1.19 3 4 package command 5 6 import ( 7 "encoding/json" 8 "errors" 9 10 "github.com/docker/cli/cli/context/store" 11 ) 12 13 // DockerContext is a typed representation of what we put in Context metadata 14 type DockerContext struct { 15 Description string 16 AdditionalFields map[string]any 17 } 18 19 // MarshalJSON implements custom JSON marshalling 20 func (dc DockerContext) MarshalJSON() ([]byte, error) { 21 s := map[string]any{} 22 if dc.Description != "" { 23 s["Description"] = dc.Description 24 } 25 if dc.AdditionalFields != nil { 26 for k, v := range dc.AdditionalFields { 27 s[k] = v 28 } 29 } 30 return json.Marshal(s) 31 } 32 33 // UnmarshalJSON implements custom JSON marshalling 34 func (dc *DockerContext) UnmarshalJSON(payload []byte) error { 35 var data map[string]any 36 if err := json.Unmarshal(payload, &data); err != nil { 37 return err 38 } 39 for k, v := range data { 40 switch k { 41 case "Description": 42 dc.Description = v.(string) 43 default: 44 if dc.AdditionalFields == nil { 45 dc.AdditionalFields = make(map[string]any) 46 } 47 dc.AdditionalFields[k] = v 48 } 49 } 50 return nil 51 } 52 53 // GetDockerContext extracts metadata from stored context metadata 54 func GetDockerContext(storeMetadata store.Metadata) (DockerContext, error) { 55 if storeMetadata.Metadata == nil { 56 // can happen if we save endpoints before assigning a context metadata 57 // it is totally valid, and we should return a default initialized value 58 return DockerContext{}, nil 59 } 60 res, ok := storeMetadata.Metadata.(DockerContext) 61 if !ok { 62 return DockerContext{}, errors.New("context metadata is not a valid DockerContext") 63 } 64 if storeMetadata.Name == DefaultContextName { 65 res.Description = "Current DOCKER_HOST based configuration" 66 } 67 return res, nil 68 }