Skip to content

Commit

Permalink
refactor vault-cli
Browse files Browse the repository at this point in the history
  • Loading branch information
Dominik Przybyl committed Nov 17, 2024
1 parent 8a7590f commit 5ed306f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 26 deletions.
4 changes: 1 addition & 3 deletions cmd/aem/vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"github.com/spf13/cobra"
"github.com/wttech/aemc/pkg"
"os"
)

func (c *CLI) vaultCmd() *cobra.Command {
Expand All @@ -12,8 +11,7 @@ func (c *CLI) vaultCmd() *cobra.Command {
Short: "Executes Vault commands",
Run: func(cmd *cobra.Command, args []string) {
vaultCli := pkg.NewVaultCli(c.aem)
vaultCliArgs := os.Args[1:]
if err := vaultCli.CommandShell(vaultCliArgs); err != nil {
if err := vaultCli.CommandShell(args); err != nil {
c.Error(err)
return
}
Expand Down
31 changes: 8 additions & 23 deletions pkg/vault_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/wttech/aemc/pkg/common/httpx"
"github.com/wttech/aemc/pkg/common/osx"
"github.com/wttech/aemc/pkg/common/pathx"
"io"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -41,10 +40,13 @@ func (v VaultCli) dir() string {
return filepath.Join(v.aem.baseOpts.ToolDir, "vault-cli")
}

func (v VaultCli) execDir() string {
func (v VaultCli) execFile() string {
vaultDir, _, _ := strings.Cut(filepath.Base(v.DownloadURL), "-bin")
execDir, _ := filepath.Abs(filepath.Join(v.dir(), vaultDir, "bin"))
return execDir
execDir := filepath.Join(v.dir(), vaultDir, "bin")
if osx.IsWindows() {
return pathx.Canonical(execDir + "/vlt.bat")
}
return pathx.Canonical(execDir + "/vlt")
}

func (v VaultCli) lock() osx.Lock[VaultCliLock] {
Expand Down Expand Up @@ -100,28 +102,11 @@ func (v VaultCli) CommandShell(args []string) error {
if err := v.Prepare(); err != nil {
return fmt.Errorf("cannot prepare Vault before running command: %w", err)
}
cmd := execx.CommandShell(args)
cmd.Dir = v.execDir()
vcw := &VaultCliWriter{writer: v.aem.output, status: 0}
v.aem.SetOutput(vcw)
vaultCliArgs := append([]string{v.execFile()}, args...)
cmd := execx.CommandShell(vaultCliArgs)
v.aem.CommandOutput(cmd)
if err := cmd.Run(); err != nil {
return fmt.Errorf("cannot run Vault command: %w", err)
}
if vcw.status != 0 {
return fmt.Errorf("")
}
return nil
}

type VaultCliWriter struct {
writer io.Writer
status int
}

func (vcw *VaultCliWriter) Write(p []byte) (int, error) {
if strings.Contains(string(p), "[ERROR]") {
vcw.status = 1
}
return vcw.writer.Write(p)
}

0 comments on commit 5ed306f

Please sign in to comment.