1
// Copyright 2013 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
13
"launchpad.net/gnuflag"
14
"launchpad.net/juju-core/cmd"
15
"launchpad.net/juju-core/environs/config"
18
const CurrentEnvironmentFilename = "current-environment"
20
// The purpose of EnvCommandBase is to provide a default member and flag
21
// setting for commands that deal across different environments.
22
type EnvCommandBase struct {
27
func getCurrentEnvironmentFilePath() string {
28
return filepath.Join(config.JujuHome(), CurrentEnvironmentFilename)
31
// Read the file $JUJU_HOME/current-environment and return the value stored
32
// there. If the file doesn't exist, or there is a problem reading the file,
33
// an empty string is returned.
34
func readCurrentEnvironment() string {
35
current, err := ioutil.ReadFile(getCurrentEnvironmentFilePath())
36
// The file not being there, or not readable isn't really an error for us
37
// here. We treat it as "can't tell, so you get the default".
41
return strings.TrimSpace(string(current))
44
// Write the envName to the file $JUJU_HOME/current-environment file.
45
func writeCurrentEnvironment(envName string) error {
46
path := getCurrentEnvironmentFilePath()
47
err := ioutil.WriteFile(path, []byte(envName+"\n"), 0644)
49
return fmt.Errorf("unable to write to the environment file: %q, %s", path, err)
54
// There is simple ordering for the default environment. Firstly check the
55
// JUJU_ENV environment variable. If that is set, it gets used. If it isn't
56
// set, look in the $JUJU_HOME/current-environment file.
57
func getDefaultEnvironment() string {
58
defaultEnv := os.Getenv("JUJU_ENV")
62
return readCurrentEnvironment()
65
func (c *EnvCommandBase) SetFlags(f *gnuflag.FlagSet) {
66
defaultEnv := getDefaultEnvironment()
67
f.StringVar(&c.EnvName, "e", defaultEnv, "juju environment to operate in")
68
f.StringVar(&c.EnvName, "environment", defaultEnv, "")