2022-12-15 20:28:14 +00:00
|
|
|
package mutator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2023-05-16 16:35:39 +00:00
|
|
|
"github.com/databricks/cli/bundle"
|
2022-12-15 20:28:14 +00:00
|
|
|
"golang.org/x/exp/maps"
|
|
|
|
)
|
|
|
|
|
|
|
|
type selectDefaultEnvironment struct{}
|
|
|
|
|
|
|
|
// SelectDefaultEnvironment merges the default environment into the root configuration.
|
|
|
|
func SelectDefaultEnvironment() bundle.Mutator {
|
|
|
|
return &selectDefaultEnvironment{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *selectDefaultEnvironment) Name() string {
|
|
|
|
return "SelectDefaultEnvironment"
|
|
|
|
}
|
|
|
|
|
2023-05-24 12:45:19 +00:00
|
|
|
func (m *selectDefaultEnvironment) Apply(ctx context.Context, b *bundle.Bundle) error {
|
2022-12-15 20:28:14 +00:00
|
|
|
if len(b.Config.Environments) == 0 {
|
2023-05-24 12:45:19 +00:00
|
|
|
return fmt.Errorf("no environments defined")
|
2022-12-15 20:28:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// One environment means there's only one default.
|
|
|
|
names := maps.Keys(b.Config.Environments)
|
|
|
|
if len(names) == 1 {
|
2023-05-24 12:45:19 +00:00
|
|
|
return SelectEnvironment(names[0]).Apply(ctx, b)
|
2022-12-15 20:28:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Multiple environments means we look for the `default` flag.
|
|
|
|
var defaults []string
|
2022-12-22 14:31:32 +00:00
|
|
|
for name, env := range b.Config.Environments {
|
|
|
|
if env != nil && env.Default {
|
2022-12-15 20:28:14 +00:00
|
|
|
defaults = append(defaults, name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// It is invalid to have multiple environments with the `default` flag set.
|
|
|
|
if len(defaults) > 1 {
|
2023-05-24 12:45:19 +00:00
|
|
|
return fmt.Errorf("multiple environments are marked as default (%s)", strings.Join(defaults, ", "))
|
2022-12-15 20:28:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// If no environment has the `default` flag set, ask the user to specify one.
|
|
|
|
if len(defaults) == 0 {
|
2023-05-24 12:45:19 +00:00
|
|
|
return fmt.Errorf("please specify environment")
|
2022-12-15 20:28:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// One default remaining.
|
2023-05-24 12:45:19 +00:00
|
|
|
return SelectEnvironment(defaults[0]).Apply(ctx, b)
|
2022-12-15 20:28:14 +00:00
|
|
|
}
|