github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/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  	StackOrchestrator Orchestrator
    14  	AdditionalFields  map[string]interface{}
    15  }
    16  
    17  // MarshalJSON implements custom JSON marshalling
    18  func (dc DockerContext) MarshalJSON() ([]byte, error) {
    19  	s := map[string]interface{}{}
    20  	if dc.Description != "" {
    21  		s["Description"] = dc.Description
    22  	}
    23  	if dc.StackOrchestrator != "" {
    24  		s["StackOrchestrator"] = dc.StackOrchestrator
    25  	}
    26  	if dc.AdditionalFields != nil {
    27  		for k, v := range dc.AdditionalFields {
    28  			s[k] = v
    29  		}
    30  	}
    31  	return json.Marshal(s)
    32  }
    33  
    34  // UnmarshalJSON implements custom JSON marshalling
    35  func (dc *DockerContext) UnmarshalJSON(payload []byte) error {
    36  	var data map[string]interface{}
    37  	if err := json.Unmarshal(payload, &data); err != nil {
    38  		return err
    39  	}
    40  	for k, v := range data {
    41  		switch k {
    42  		case "Description":
    43  			dc.Description = v.(string)
    44  		case "StackOrchestrator":
    45  			dc.StackOrchestrator = Orchestrator(v.(string))
    46  		default:
    47  			if dc.AdditionalFields == nil {
    48  				dc.AdditionalFields = make(map[string]interface{})
    49  			}
    50  			dc.AdditionalFields[k] = v
    51  		}
    52  	}
    53  	return nil
    54  }
    55  
    56  // GetDockerContext extracts metadata from stored context metadata
    57  func GetDockerContext(storeMetadata store.Metadata) (DockerContext, error) {
    58  	if storeMetadata.Metadata == nil {
    59  		// can happen if we save endpoints before assigning a context metadata
    60  		// it is totally valid, and we should return a default initialized value
    61  		return DockerContext{}, nil
    62  	}
    63  	res, ok := storeMetadata.Metadata.(DockerContext)
    64  	if !ok {
    65  		return DockerContext{}, errors.New("context metadata is not a valid DockerContext")
    66  	}
    67  	return res, nil
    68  }