Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve copying of PHP and legacy CLI files #94

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
PHP_VERSION = 8.2.26
PHP_VERSION = 8.2.27
LEGACY_CLI_VERSION = 4.22.0

GORELEASER_ID ?= platform
Expand Down Expand Up @@ -49,14 +49,21 @@ internal/legacy/archives/php_linux_$(GOARCH):
--progress=plain \
ext/static-php-cli/docker

PHP_WINDOWS_REMOTE_FILENAME := "php-$(PHP_VERSION)-nts-Win32-vs16-x64.zip"
internal/legacy/archives/php_windows.zip:
mkdir -p internal/legacy/archives
wget https://windows.php.net/downloads/releases/php-$(PHP_VERSION)-nts-Win32-vs16-x64.zip -O internal/legacy/archives/php_windows.zip
( \
set -e ;\
mkdir -p internal/legacy/archives ;\
cd internal/legacy/archives ;\
curl -f "https://windows.php.net/downloads/releases/$(PHP_WINDOWS_REMOTE_FILENAME)" > php_windows.zip ;\
curl -f https://windows.php.net/downloads/releases/sha256sum.txt | grep "$(PHP_WINDOWS_REMOTE_FILENAME)" | sed s/"$(PHP_WINDOWS_REMOTE_FILENAME)"/"php_windows.zip"/g > php_windows.zip.sha256 ;\
sha256sum -c php_windows.zip.sha256 ;\
)

.PHONY: internal/legacy/archives/cacert.pem
internal/legacy/archives/cacert.pem:
mkdir -p internal/legacy/archives
wget https://curl.se/ca/cacert.pem -O internal/legacy/archives/cacert.pem
curl https://curl.se/ca/cacert.pem > internal/legacy/archives/cacert.pem

php: $(PHP_BINARY_PATH)

Expand Down
41 changes: 9 additions & 32 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,24 @@ 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(),
}
c := makeLegacyCLIWrapper(cnf, &b, cmd.ErrOrStderr(), cmd.InOrStdin())

if err := c.Init(); err != nil {
debugLog(err.Error())
os.Exit(1)
return
if err := c.Exec(cmd.Context(), completionArgs...); err != nil {
exitWithError(err)
}

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
pharPath, err := c.PharPath()
if err != nil {
exitWithError(err)
}

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
46 changes: 18 additions & 28 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,13 +106,13 @@ 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))
cmd.PersistentFlags().String("phar-path", "",
fmt.Sprintf("Uses a local .phar file for the Legacy %s", cnf.Application.Name),
)
cmd.PersistentFlags().Bool("debug", false, "Enable debug logging")
cmd.PersistentFlags().Bool("no-interaction", false, "Enable non-interactive mode")
cmd.PersistentFlags().BoolP("verbose", "v", false, "Enable verbose output")
Expand Down Expand Up @@ -239,40 +242,27 @@ 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)
}
if !viper.GetBool("quiet") {
fmt.Fprintln(color.Error, color.RedString(err.Error()))
}
os.Exit(exitCode)
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"),
Debug: viper.GetBool("debug"),
DebugLogFunc: debugLog,
DisableInteraction: viper.GetBool("no-interaction"),
Stdout: stdout,
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)
}
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/stretchr/testify v1.9.0
github.com/wk8/go-ordered-map/v2 v2.1.8
golang.org/x/crypto v0.31.0
golang.org/x/sync v0.10.0
gopkg.in/yaml.v3 v3.0.1
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down
1 change: 1 addition & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func FromYAML(b []byte) (*Config, error) {
return nil, fmt.Errorf("invalid config: %w", err)
}
c.applyDynamicDefaults()
c.raw = b
return c, nil
}

Expand Down
22 changes: 17 additions & 5 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/platformsh/cli/internal/config"
)
Expand All @@ -25,6 +26,14 @@ func TestFromYAML(t *testing.T) {
cnf, err := config.FromYAML([]byte(validConfig))
assert.NoError(t, err)

tempDir := t.TempDir()
require.NoError(t, os.Setenv(cnf.Application.EnvPrefix+"HOME", tempDir))
require.NoError(t, os.Setenv(cnf.Application.EnvPrefix+"TMP", filepath.Join(tempDir, "tmp")))
t.Cleanup(func() {
_ = os.Unsetenv(cnf.Application.EnvPrefix + "HOME")
_ = os.Unsetenv(cnf.Application.EnvPrefix + "TMP")
})

// Test defaults
assert.Equal(t, "state.json", cnf.Application.UserStateFile)
assert.Equal(t, true, cnf.Updates.Check)
Expand All @@ -33,13 +42,16 @@ func TestFromYAML(t *testing.T) {
assert.Equal(t, "example-cli-tmp", cnf.Application.TempSubDir)
assert.Equal(t, "platform", cnf.Service.ProjectConfigFlavor)

homeDir, err := cnf.HomeDir()
require.NoError(t, err)
assert.Equal(t, tempDir, homeDir)

writableDir, err := cnf.WritableUserDir()
assert.NoError(t, err)
assert.Equal(t, filepath.Join(homeDir, cnf.Application.WritableUserDir), writableDir)

if homeDir, err := os.UserHomeDir(); err == nil {
assert.Equal(t, filepath.Join(homeDir, cnf.Application.WritableUserDir), writableDir)
} else {
assert.Equal(t, filepath.Join(os.TempDir(), cnf.Application.TempSubDir), writableDir)
}
d, err := cnf.TempDir()
assert.NoError(t, err)
assert.Equal(t, filepath.Join(tempDir, "tmp", cnf.Application.TempSubDir), d)
})
}
Loading
Loading