Skip to content

Commit

Permalink
cmd/atlas: allow attaching config token to context (ariga#2079)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m authored Sep 13, 2023
1 parent 1c8a05f commit cb00ab6
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 15 deletions.
5 changes: 5 additions & 0 deletions cmd/atlas/internal/cmdapi/cmdapi_oss.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,8 @@ func promptApply(cmd *cobra.Command,
}
return nil
}

// withTokenContext allows attaching token to the context.
func withTokenContext(ctx context.Context, _ string) (context.Context, error) {
return ctx, nil
}
2 changes: 1 addition & 1 deletion cmd/atlas/internal/cmdapi/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ If run with the "--dry-run" flag, atlas will not execute any SQL.`,
}
return migrateApplyRun(cmd, args, flags, &MigrateReport{}) // nop reporter
default:
project, envs, err := EnvByName(GlobalFlags.SelectedEnv, WithInput(GlobalFlags.Vars))
project, envs, err := EnvByName(cmd, GlobalFlags.SelectedEnv, WithInput(GlobalFlags.Vars))
if err != nil {
return err
}
Expand Down
12 changes: 11 additions & 1 deletion cmd/atlas/internal/cmdapi/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/spf13/cobra"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
Expand Down Expand Up @@ -335,7 +336,7 @@ func (e *Env) asMap() (map[string]string, error) {
}

// EnvByName parses and returns the project configuration with selected environments.
func EnvByName(name string, opts ...LoadOption) (*Project, []*Env, error) {
func EnvByName(cmd *cobra.Command, name string, opts ...LoadOption) (*Project, []*Env, error) {
u, err := url.Parse(GlobalFlags.ConfigURL)
if err != nil {
return nil, nil, err
Expand All @@ -354,6 +355,15 @@ func EnvByName(name string, opts ...LoadOption) (*Project, []*Env, error) {
if err != nil {
return nil, nil, err
}
// The project token predates 'atlas login' command. If exists,
// attach it to the context to indicate the user is authenticated.
if t := project.cfg.Token; t != "" {
ctx, err := withTokenContext(cmd.Context(), t)
if err != nil {
return nil, nil, err
}
cmd.SetContext(ctx)
}
if err := project.Lint.remainedLog(); err != nil {
return nil, nil, err
}
Expand Down
19 changes: 10 additions & 9 deletions cmd/atlas/internal/cmdapi/project_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"ariga.io/atlas/schemahcl"
"ariga.io/atlas/sql/schema"

"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
"github.com/zclconf/go-cty/cty"
)
Expand Down Expand Up @@ -100,7 +101,7 @@ env "multi" {
require.NoError(t, os.Setenv("ATLAS_TOKEN", "token_atlas"))
t.Cleanup(func() { require.NoError(t, os.Unsetenv("ATLAS_TOKEN")) })
t.Run("ok", func(t *testing.T) {
_, envs, err := EnvByName("local")
_, envs, err := EnvByName(&cobra.Command{}, "local")
require.NoError(t, err)
require.Len(t, envs, 1)
env := envs[0]
Expand Down Expand Up @@ -160,15 +161,15 @@ env "multi" {
require.EqualValues(t, []string{"local/app.hcl"}, sources)
})
t.Run("multi", func(t *testing.T) {
_, envs, err := EnvByName("multi")
_, envs, err := EnvByName(&cobra.Command{}, "multi")
require.NoError(t, err)
require.Len(t, envs, 1)
srcs, err := envs[0].Sources()
require.NoError(t, err)
require.EqualValues(t, []string{"./a.hcl", "./b.hcl"}, srcs)
})
t.Run("with input", func(t *testing.T) {
_, envs, err := EnvByName("local", WithInput(map[string]cty.Value{
_, envs, err := EnvByName(&cobra.Command{}, "local", WithInput(map[string]cty.Value{
"name": cty.StringVal("goodbye"),
}))
require.NoError(t, err)
Expand All @@ -180,12 +181,12 @@ env "multi" {
require.EqualValues(t, "goodbye", val)
})
t.Run("wrong env", func(t *testing.T) {
_, _, err = EnvByName("home")
_, _, err = EnvByName(&cobra.Command{}, "home")
require.EqualError(t, err, `env "home" not defined in project file`)
})
t.Run("wrong dir", func(t *testing.T) {
GlobalFlags.ConfigURL = defaultConfigPath
_, _, err = EnvByName("home")
_, _, err = EnvByName(&cobra.Command{}, "home")
require.ErrorContains(t, err, `no such file or directory`)
})
}
Expand All @@ -204,7 +205,7 @@ env {
err := os.WriteFile(path, []byte(h), 0600)
require.NoError(t, err)
GlobalFlags.ConfigURL = "file://" + path
_, envs, err := EnvByName("local")
_, envs, err := EnvByName(&cobra.Command{}, "local")
require.NoError(t, err)
require.Len(t, envs, 1)
require.Equal(t, "local", envs[0].Name)
Expand Down Expand Up @@ -244,7 +245,7 @@ diff {
err := os.WriteFile(path, []byte(h), 0600)
require.NoError(t, err)
GlobalFlags.ConfigURL = "file://" + path
project, envs, err := EnvByName("")
project, envs, err := EnvByName(&cobra.Command{}, "")
require.NoError(t, err)
require.Len(t, envs, 0)
require.Equal(t, 1, project.Lint.Latest)
Expand Down Expand Up @@ -280,13 +281,13 @@ env "dev" {
err := os.WriteFile(path, []byte(h), 0600)
require.NoError(t, err)
GlobalFlags.ConfigURL = "file://" + path
_, envs, err := EnvByName("unnamed")
_, envs, err := EnvByName(&cobra.Command{}, "unnamed")
require.NoError(t, err)
require.Len(t, envs, 1)
require.Equal(t, "unnamed", envs[0].Name)
require.Equal(t, "b", envs[0].Format.Schema.Diff)
require.Equal(t, "env: unnamed", envs[0].Format.Schema.Apply)
_, envs, err = EnvByName("dev")
_, envs, err = EnvByName(&cobra.Command{}, "dev")
require.NoError(t, err)
require.Len(t, envs, 2)
for _, e := range envs {
Expand Down
6 changes: 3 additions & 3 deletions cmd/atlas/internal/cmdapi/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ migration.`,
}
return schemaApplyRun(cmd, flags, env)
default:
_, envs, err := EnvByName(GlobalFlags.SelectedEnv, WithInput(GlobalFlags.Vars))
_, envs, err := EnvByName(cmd, GlobalFlags.SelectedEnv, WithInput(GlobalFlags.Vars))
if err != nil {
return err
}
Expand Down Expand Up @@ -570,7 +570,7 @@ func selectEnv(cmd *cobra.Command) (*Env, error) {
switch name := GlobalFlags.SelectedEnv; {
// A config file was passed without an env.
case name == "" && cmd.Flags().Changed(flagConfig):
p, envs, err := EnvByName(name, WithInput(GlobalFlags.Vars))
p, envs, err := EnvByName(cmd, name, WithInput(GlobalFlags.Vars))
if err != nil {
return nil, err
}
Expand All @@ -583,7 +583,7 @@ func selectEnv(cmd *cobra.Command) (*Env, error) {
return &Env{Lint: &Lint{}, Migration: &Migration{}}, nil
// Env was passed.
default:
_, envs, err := EnvByName(name, WithInput(GlobalFlags.Vars))
_, envs, err := EnvByName(cmd, name, WithInput(GlobalFlags.Vars))
if err != nil {
return nil, err
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/atlas/internal/cmdext/cmdext.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ func TemplateDir(ctx *hcl.EvalContext, block *hclsyntax.Block) (cty.Value, error
// defined and executed on schemahcl Eval functions.
type AtlasConfig struct {
Client *cloudapi.Client // Client attached to Atlas Cloud.
Token string // User token.
Project string // Optional project.
}

Expand All @@ -424,7 +425,7 @@ type AtlasConfig struct {
// cloud {
// token = data.runtimevar.token // User token.
// url = var.cloud_url // Optional URL.
// project = var.project // Optional project. If set, cloud reporting is enabled.
// project = var.project // Optional project. Defaults to DefaultProjectName.
// }
// }
func (c *AtlasConfig) InitBlock() schemahcl.Option {
Expand All @@ -442,6 +443,7 @@ func (c *AtlasConfig) InitBlock() schemahcl.Option {
if args.Cloud.Project == "" {
args.Cloud.Project = cloudapi.DefaultProjectName
}
c.Token = args.Cloud.Token
c.Project = args.Cloud.Project
c.Client = cloudapi.New(args.Cloud.URL, args.Cloud.Token)
cloud := cty.ObjectVal(map[string]cty.Value{
Expand Down
1 change: 1 addition & 0 deletions cmd/atlas/internal/cmdext/cmdext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,7 @@ cloud_keys = keys(atlas.cloud)
require.Equal(t, []string{"client", "project"}, v.CloudKeys, "token and url should not be exported")
// Config options should be populated from the init block.
require.NotNil(t, cfg.Client)
require.Equal(t, "token", cfg.Token)
require.Equal(t, "atlasgo.io", cfg.Project)

err = state.EvalBytes([]byte(`
Expand Down

0 comments on commit cb00ab6

Please sign in to comment.