Skip to content
This repository has been archived by the owner on Dec 26, 2023. It is now read-only.

Commit

Permalink
Merge pull request #96 from rafiramadhana/89-cmd-to-select-current-co…
Browse files Browse the repository at this point in the history
…ntext

Add use-context command
  • Loading branch information
vieiralucas authored Sep 20, 2023
2 parents 26c3541 + 3f94a83 commit 5055275
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
17 changes: 17 additions & 0 deletions .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,23 @@ jobs:
layerform config set-context test-cloud -t cloud --url https://demo.layerform.dev --email [email protected] --password strongpass
layerform config set-context test-local -t local --dir test
- name: layerform config use-context
run: |
# fails if command succeeds
! layerform config use-context test-does-not-exist # context does not exist
# switch context to test-s3
layerform config use-context test-s3
layerform config get-contexts | tee usecontext
! grep -E '^\*\s+test-local' usecontext
grep -E '^\*\s+test-s3' usecontext
# switch context to test-local
layerform config use-context test-local
layerform config get-contexts | tee usecontext
grep -E '^\*\s+test-local' usecontext
! grep -E '^\*\s+test-s3' usecontext
- name: Configure
run: |
layerform configure --file examples/local/layerform.json
Expand Down
56 changes: 56 additions & 0 deletions cmd/cli/use_context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package cli

import (
"fmt"
"os"

"github.com/pkg/errors"
"github.com/spf13/cobra"

"github.com/ergomake/layerform/internal/lfconfig"
)

func init() {
configCmd.AddCommand(configUseContextCmd)
}

var configUseContextCmd = &cobra.Command{
Use: "use-context <name>",
Short: "Use a context entry from layerform config file",
Long: `Use a context entry from layerform config file.
Using a name that does not exist will return error.`,
Example: `# Use a context
layerform config use-context local-example`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
name := args[0]

cfg, err := lfconfig.Load("")
if err != nil && !errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(os.Stderr, "%s\n", errors.Wrap(err, "fail to open config file"))
os.Exit(1)
}

_, ok := cfg.Contexts[name]
if !ok {
fmt.Fprintf(
os.Stderr,
"no context exists with the name \"%s\".\n",
name,
)
os.Exit(1)
}

cfg.CurrentContext = name

err = cfg.Save()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", errors.Wrap(err, "fail to save config file"))
os.Exit(1)
}

fmt.Fprintf(os.Stdout, "Switched to context \"%s\".\n", name)
},
SilenceErrors: true,
}

0 comments on commit 5055275

Please sign in to comment.