Skip to content

Commit

Permalink
Refactor legacy CLI invocation
Browse files Browse the repository at this point in the history
  • Loading branch information
pjcdawkins committed Jan 15, 2025
1 parent 9df870d commit 476403c
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 83 deletions.
40 changes: 7 additions & 33 deletions commands/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@ package commands

import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/platformsh/cli/internal/config"
"github.com/platformsh/cli/internal/legacy"
)

func newCompletionCommand(cnf *config.Config) *cobra.Command {
Expand All @@ -28,42 +23,21 @@ func newCompletionCommand(cnf *config.Config) *cobra.Command {
completionArgs = append(completionArgs, "--shell-type", args[0])
}
var b bytes.Buffer
c := &legacy.CLIWrapper{
Config: cnf,
Version: version,
CustomPharPath: viper.GetString("phar-path"),
Debug: viper.GetBool("debug"),
DebugLogFunc: debugLog,
DisableInteraction: viper.GetBool("no-interaction"),
Stdout: &b,
Stderr: cmd.ErrOrStderr(),
Stdin: cmd.InOrStdin(),
}

if err := c.Init(); err != nil {
debugLog(err.Error())
os.Exit(1)
return
}
c := makeLegacyCLIWrapper(cnf, &b, cmd.ErrOrStderr(), cmd.InOrStdin())

if err := c.Exec(cmd.Context(), completionArgs...); err != nil {
debugLog(err.Error())
exitCode := 1
var execErr *exec.ExitError
if errors.As(err, &execErr) {
exitCode = execErr.ExitCode()
}
os.Exit(exitCode)
return
exitWithError(err)
}

pharPath := c.PharPath()

completions := strings.ReplaceAll(
strings.ReplaceAll(
b.String(),
c.PharPath(),
pharPath,
cnf.Application.Executable,
),
path.Base(c.PharPath()),
filepath.Base(pharPath),
cnf.Application.Executable,
)
fmt.Fprintln(cmd.OutOrStdout(), "#compdef "+cnf.Application.Executable)
Expand Down
33 changes: 8 additions & 25 deletions commands/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/spf13/viper"

"github.com/platformsh/cli/internal/config"
"github.com/platformsh/cli/internal/legacy"
)

func newListCommand(cnf *config.Config) *cobra.Command {
Expand All @@ -18,39 +17,24 @@ func newListCommand(cnf *config.Config) *cobra.Command {
Short: "Lists commands",
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var b bytes.Buffer
c := &legacy.CLIWrapper{
Config: cnf,
Version: version,
CustomPharPath: viper.GetString("phar-path"),
Debug: viper.GetBool("debug"),
DebugLogFunc: debugLog,
DisableInteraction: viper.GetBool("no-interaction"),
Stdout: &b,
Stderr: cmd.ErrOrStderr(),
Stdin: cmd.InOrStdin(),
}
if err := c.Init(); err != nil {
exitWithError(cmd, err)
return
}

arguments := []string{"list", "--format=json"}
if viper.GetBool("all") {
arguments = append(arguments, "--all")
}
if len(args) > 0 {
arguments = append(arguments, args[0])
}

var b bytes.Buffer
c := makeLegacyCLIWrapper(cnf, &b, cmd.ErrOrStderr(), cmd.InOrStdin())

if err := c.Exec(cmd.Context(), arguments...); err != nil {
exitWithError(cmd, err)
return
exitWithError(err)
}

var list List
if err := json.Unmarshal(b.Bytes(), &list); err != nil {
exitWithError(cmd, err)
return
exitWithError(err)
}

// Override the application name and executable with our own config.
Expand Down Expand Up @@ -88,15 +72,14 @@ func newListCommand(cnf *config.Config) *cobra.Command {
c.Stdout = cmd.OutOrStdout()
arguments := []string{"list", "--format=" + format}
if err := c.Exec(cmd.Context(), arguments...); err != nil {
exitWithError(cmd, err)
exitWithError(err)
}
return
}

result, err := formatter.Format(&list, config.FromContext(cmd.Context()))
if err != nil {
exitWithError(cmd, err)
return
exitWithError(err)
}

fmt.Fprintln(cmd.OutOrStdout(), string(result))
Expand Down
41 changes: 18 additions & 23 deletions commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ func newRootCommand(cnf *config.Config, assets *vendorization.VendorAssets) *cob
}
},
Run: func(cmd *cobra.Command, _ []string) {
runLegacyCLI(cmd.Context(), cnf, cmd.OutOrStdout(), cmd.ErrOrStderr(), cmd.InOrStdin(), os.Args[1:])
c := makeLegacyCLIWrapper(cnf, cmd.OutOrStdout(), cmd.ErrOrStderr(), cmd.InOrStdin())
if err := c.Exec(cmd.Context(), os.Args[1:]...); err != nil {
exitWithError(err)
}
},
PersistentPostRun: func(cmd *cobra.Command, _ []string) {
checkShellConfigLeftovers(cmd.ErrOrStderr(), cnf)
Expand All @@ -103,7 +106,10 @@ func newRootCommand(cnf *config.Config, assets *vendorization.VendorAssets) *cob
args = []string{"help"}
}

runLegacyCLI(cmd.Context(), cnf, cmd.OutOrStdout(), cmd.ErrOrStderr(), cmd.InOrStdin(), args)
c := makeLegacyCLIWrapper(cnf, cmd.OutOrStdout(), cmd.ErrOrStderr(), cmd.InOrStdin())
if err := c.Exec(cmd.Context(), args...); err != nil {
exitWithError(err)
}
})

cmd.PersistentFlags().BoolP("version", "V", false, fmt.Sprintf("Displays the %s version", cnf.Application.Name))
Expand Down Expand Up @@ -239,18 +245,21 @@ func debugLog(format string, v ...any) {
fmt.Fprintf(color.Error, prefix+" "+strings.TrimSpace(format)+"\n", v...)
}

func exitWithError(cmd *cobra.Command, err error) {
cmd.PrintErrln(color.RedString(err.Error()))
exitCode := 1
func exitWithError(err error) {
var execErr *exec.ExitError
if errors.As(err, &execErr) {
exitCode = execErr.ExitCode()
exitCode := execErr.ExitCode()
debugLog(err.Error())
os.Exit(exitCode)
}
os.Exit(exitCode)
if !viper.GetBool("quiet") {
fmt.Fprintln(color.Error, color.RedString(err.Error()))
}
os.Exit(1)
}

func runLegacyCLI(ctx context.Context, cnf *config.Config, stdout, stderr io.Writer, stdin io.Reader, args []string) {
c := &legacy.CLIWrapper{
func makeLegacyCLIWrapper(cnf *config.Config, stdout, stderr io.Writer, stdin io.Reader) *legacy.CLIWrapper {
return &legacy.CLIWrapper{
Config: cnf,
Version: version,
CustomPharPath: viper.GetString("phar-path"),
Expand All @@ -261,18 +270,4 @@ func runLegacyCLI(ctx context.Context, cnf *config.Config, stdout, stderr io.Wri
Stderr: stderr,
Stdin: stdin,
}
if err := c.Init(); err != nil {
fmt.Fprintln(stderr, color.RedString(err.Error()))
os.Exit(1)
}

if err := c.Exec(ctx, args...); err != nil {
debugLog("%s\n", color.RedString(err.Error()))
exitCode := 1
var execErr *exec.ExitError
if errors.As(err, &execErr) {
exitCode = execErr.ExitCode()
}
os.Exit(exitCode)
}
}
15 changes: 13 additions & 2 deletions internal/legacy/legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ type CLIWrapper struct {
Debug bool
DisableInteraction bool
DebugLogFunc func(string, ...any)

initialized bool
}

func (c *CLIWrapper) debug(msg string, args ...any) {
Expand All @@ -89,8 +91,12 @@ func (c *CLIWrapper) cacheDir() string {
return path.Join(os.TempDir(), fmt.Sprintf("%s-%s-%s", c.Config.Application.Slug, PHPVersion, LegacyCLIVersion))
}

// Init the CLI wrapper, creating a temporary directory and copying over files
func (c *CLIWrapper) Init() error {
// init initializes the CLI wrapper, creating a temporary directory and copying over files.
func (c *CLIWrapper) init() error {
if c.initialized {
return nil
}

if _, err := os.Stat(c.cacheDir()); os.IsNotExist(err) {
c.debug("Cache directory does not exist, creating: %s", c.cacheDir())
if err := os.Mkdir(c.cacheDir(), 0o700); err != nil {
Expand Down Expand Up @@ -141,11 +147,16 @@ func (c *CLIWrapper) Init() error {
}
}

c.initialized = true
return nil
}

// Exec a legacy CLI command with the given arguments
func (c *CLIWrapper) Exec(ctx context.Context, args ...string) error {
if err := c.init(); err != nil {
return err
}

cmd := c.makeCmd(ctx, args)
if c.Stdin != nil {
cmd.Stdin = c.Stdin
Expand Down

0 comments on commit 476403c

Please sign in to comment.