github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/context.go (about)

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