github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/juju/environment/unset.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package environment
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/juju/cmd"
    11  
    12  	"github.com/juju/juju/cmd/envcmd"
    13  	"github.com/juju/juju/cmd/juju/block"
    14  )
    15  
    16  type UnsetCommand struct {
    17  	envcmd.EnvCommandBase
    18  	api  UnsetEnvironmentAPI
    19  	keys []string
    20  }
    21  
    22  const unsetEnvHelpDoc = `
    23  Reset one or more the environment configuration attributes to its default
    24  value in a running Juju instance.  Attributes without defaults are removed,
    25  and attempting to remove a required attribute with no default will result
    26  in an error.
    27  
    28  Multiple attributes may be removed at once; keys should be space-separated.
    29  `
    30  
    31  func (c *UnsetCommand) Info() *cmd.Info {
    32  	return &cmd.Info{
    33  		Name:    "unset",
    34  		Args:    "<environment key> ...",
    35  		Purpose: "unset environment values",
    36  		Doc:     strings.TrimSpace(unsetEnvHelpDoc),
    37  	}
    38  }
    39  
    40  func (c *UnsetCommand) Init(args []string) (err error) {
    41  	if len(args) == 0 {
    42  		return fmt.Errorf("no keys specified")
    43  	}
    44  	c.keys = args
    45  	return nil
    46  }
    47  
    48  type UnsetEnvironmentAPI interface {
    49  	Close() error
    50  	EnvironmentGet() (map[string]interface{}, error)
    51  	EnvironmentUnset(keys ...string) error
    52  }
    53  
    54  func (c *UnsetCommand) getAPI() (UnsetEnvironmentAPI, error) {
    55  	if c.api != nil {
    56  		return c.api, nil
    57  	}
    58  	return c.NewAPIClient()
    59  }
    60  
    61  func (c *UnsetCommand) Run(ctx *cmd.Context) error {
    62  	client, err := c.getAPI()
    63  	if err != nil {
    64  		return err
    65  	}
    66  	defer client.Close()
    67  
    68  	// extra call to the API to retrieve env config
    69  	envAttrs, err := client.EnvironmentGet()
    70  	if err != nil {
    71  		return err
    72  	}
    73  	for _, key := range c.keys {
    74  		// check if the key exists in the existing env config
    75  		// and warn the user if the key is not defined in
    76  		// the existing config
    77  		if _, exists := envAttrs[key]; !exists {
    78  			logger.Warningf("key %q is not defined in the current environment configuration: possible misspelling", key)
    79  		}
    80  
    81  	}
    82  	return block.ProcessBlockedError(client.EnvironmentUnset(c.keys...), block.BlockChange)
    83  }