Exemple #1
0
func (*SwitchSimpleSuite) TestSettingWritesFile(c *C) {
	defer testing.MakeFakeHome(c, testing.MultipleEnvConfig).Restore()
	context, err := testing.RunCommand(c, &SwitchCommand{}, []string{"erewhemos-2"})
	c.Assert(err, IsNil)
	c.Assert(testing.Stdout(context), Equals, "Changed default environment from \"erewhemos\" to \"erewhemos-2\"\n")
	c.Assert(cmd.ReadCurrentEnvironment(), Equals, "erewhemos-2")
}
Exemple #2
0
func (c *SwitchCommand) Run(ctx *cmd.Context) error {
	// Switch is an alternative way of dealing with environments than using
	// the JUJU_ENV environment setting, and as such, doesn't play too well.
	// If JUJU_ENV is set we should report that as the current environment,
	// and not allow switching when it is set.
	jujuEnv := os.Getenv("JUJU_ENV")
	if jujuEnv != "" {
		if c.EnvName == "" {
			fmt.Fprintf(ctx.Stdout, "Current environment: %q (from JUJU_ENV)\n", jujuEnv)
			return nil
		} else {
			return fmt.Errorf("Cannot switch when JUJU_ENV is overriding the environment (set to %q)", jujuEnv)
		}
	}

	// Passing through the empty string reads the default environments.yaml file.
	environments, err := environs.ReadEnvirons("")
	if err != nil {
		return errors.New("couldn't read the environment.")
	}
	names := environments.Names()
	sort.Strings(names)

	currentEnv := cmd.ReadCurrentEnvironment()
	if currentEnv == "" {
		currentEnv = environments.Default
	}

	// In order to have only a set environment name quoted, make a small function
	env := func() string {
		if currentEnv == "" {
			return "<not specified>"
		}
		return fmt.Sprintf("%q", currentEnv)
	}

	if c.EnvName == "" || c.EnvName == currentEnv {
		fmt.Fprintf(ctx.Stdout, "Current environment: %s\n", env())
	} else {
		// Check to make sure that the specified environment
		if !validEnvironmentName(c.EnvName, names) {
			return fmt.Errorf("%q is not a name of an existing defined environment", c.EnvName)
		}
		if err := cmd.WriteCurrentEnvironment(c.EnvName); err != nil {
			return err
		}
		fmt.Fprintf(ctx.Stdout, "Changed default environment from %s to %q\n", env(), c.EnvName)
	}
	if c.List {
		fmt.Fprintf(ctx.Stdout, "\nEnvironments:\n")
		for _, name := range names {
			fmt.Fprintf(ctx.Stdout, "\t%s\n", name)
		}
	}

	return nil
}
func (s *EnvironmentCommandSuite) TestReadCurrentEnvironmentSet(c *C) {
	err := cmd.WriteCurrentEnvironment("fubar")
	c.Assert(err, IsNil)
	env := cmd.ReadCurrentEnvironment()
	c.Assert(env, Equals, "fubar")
}
func (s *EnvironmentCommandSuite) TestReadCurrentEnvironmentUnset(c *C) {
	env := cmd.ReadCurrentEnvironment()
	c.Assert(env, Equals, "")
}