Beispiel #1
0
func (*SwitchSimpleSuite) TestSettingWritesFile(c *gc.C) {
	defer testing.MakeFakeHome(c, testing.MultipleEnvConfig).Restore()
	context, err := testing.RunCommand(c, &SwitchCommand{}, []string{"erewhemos-2"})
	c.Assert(err, gc.IsNil)
	c.Assert(testing.Stdout(context), gc.Equals, "erewhemos -> erewhemos-2\n")
	c.Assert(envcmd.ReadCurrentEnvironment(), gc.Equals, "erewhemos-2")
}
func (s *EnvironmentCommandSuite) TestReadCurrentEnvironmentSet(c *gc.C) {
	err := envcmd.WriteCurrentEnvironment("fubar")
	c.Assert(err, gc.IsNil)
	env := envcmd.ReadCurrentEnvironment()
	c.Assert(env, gc.Equals, "fubar")
}
Beispiel #3
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.

	// 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)

	if c.List {
		// List all environments.
		if c.EnvName != "" {
			return errors.New("cannot switch and list at the same time")
		}
		for _, name := range names {
			fmt.Fprintf(ctx.Stdout, "%s\n", name)
		}
		return nil
	}

	jujuEnv := os.Getenv("JUJU_ENV")
	if jujuEnv != "" {
		if c.EnvName == "" {
			fmt.Fprintf(ctx.Stdout, "%s\n", jujuEnv)
			return nil
		} else {
			return fmt.Errorf("cannot switch when JUJU_ENV is overriding the environment (set to %q)", jujuEnv)
		}
	}

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

	// Handle the different operation modes.
	switch {
	case c.EnvName == "" && currentEnv == "":
		// Nothing specified and nothing to switch to.
		return errors.New("no currently specified environment")
	case c.EnvName == "":
		// Simply print the current environment.
		fmt.Fprintf(ctx.Stdout, "%s\n", currentEnv)
	default:
		// Switch the environment.
		if !validEnvironmentName(c.EnvName, names) {
			return fmt.Errorf("%q is not a name of an existing defined environment", c.EnvName)
		}
		if err := envcmd.WriteCurrentEnvironment(c.EnvName); err != nil {
			return err
		}
		if currentEnv == "" {
			fmt.Fprintf(ctx.Stdout, "-> %s\n", c.EnvName)
		} else {
			fmt.Fprintf(ctx.Stdout, "%s -> %s\n", currentEnv, c.EnvName)
		}
	}
	return nil
}
func (s *EnvironmentCommandSuite) TestReadCurrentEnvironmentUnset(c *gc.C) {
	env := envcmd.ReadCurrentEnvironment()
	c.Assert(env, gc.Equals, "")
}