From 1ffee820aefeff27bb386441b21134a780ff2057 Mon Sep 17 00:00:00 2001 From: darkweak Date: Fri, 21 Apr 2023 15:50:27 +0200 Subject: [PATCH] feat(chore): add golangci-lint --- .github/workflows/releaser.yml | 5 + .golangci.yml | 16 + book/checkout.go | 58 +-- book/clone.go | 6 +- book/reqs.go | 4 +- commands/book_check_reqs.go | 3 +- commands/book_checkout.go | 7 +- commands/init_templating.go | 13 +- commands/init_templating_php.go | 17 +- commands/local_check_requirements.go | 11 +- commands/local_check_security.go | 4 +- commands/local_new.go | 49 ++- commands/local_proxy_domain_attach.go | 7 +- commands/local_proxy_domain_detach.go | 5 +- commands/local_proxy_start.go | 21 +- commands/local_proxy_stop.go | 3 +- commands/local_run.go | 8 +- commands/local_server_ca_install.go | 6 +- commands/local_server_ca_uninstall.go | 4 +- commands/local_server_log.go | 5 +- commands/local_server_prod.go | 2 +- commands/local_server_start.go | 54 +-- commands/local_server_status.go | 5 +- commands/local_server_stop.go | 5 +- commands/local_var_expose.go | 5 +- commands/openers.go | 25 +- commands/platformsh.go | 7 +- commands/platformsh_hooks.go | 5 +- commands/project_init.go | 11 +- commands/root.go | 9 +- commands/var_export.go | 4 +- envs/docker.go | 481 +++++++++++++------------ envs/envs.go | 3 +- envs/local.go | 7 +- envs/local_test.go | 10 +- envs/local_tunnel.go | 12 +- envs/url.go | 6 +- git/branches.go | 4 +- git/exec.go | 2 +- git/init.go | 10 +- git/remote.go | 2 +- humanlog/handler.go | 2 +- humanlog/symfony.go | 2 +- inotify/inotify.go | 7 +- local/fcgi_client/fcgiclient.go | 15 +- local/http/http.go | 4 +- local/http/push.go | 2 +- local/http/response_proxy.go | 3 +- local/logs/tailer.go | 13 +- local/php/composer.go | 25 +- local/php/executor.go | 36 +- local/php/executor_posix.go | 4 +- local/php/executor_test.go | 35 +- local/php/executor_windows.go | 8 +- local/php/php_server.go | 25 +- local/php/platformsh.go | 16 +- local/php/toolbar.go | 16 +- local/pid/pidfile.go | 35 +- local/pid/pidfile_other.go | 10 +- local/platformsh/applications.go | 3 +- local/platformsh/generator/commands.go | 7 +- local/platformsh/generator/config.go | 46 +-- local/platformsh/project.go | 3 +- local/process/port.go | 6 +- local/process/process.go | 2 +- local/process/process_other.go | 4 +- local/project/config.go | 11 +- local/project/project.go | 5 +- local/proxy/cert_store.go | 3 +- local/proxy/config.go | 11 +- local/proxy/proxy.go | 24 +- local/proxy/proxy_test.go | 24 +- local/runner.go | 18 +- local/sum.go | 2 +- main.go | 8 +- reexec/process_windows.go | 2 +- reexec/reexec.go | 17 +- updater/updater.go | 13 +- 78 files changed, 720 insertions(+), 668 deletions(-) create mode 100644 .golangci.yml diff --git a/.github/workflows/releaser.yml b/.github/workflows/releaser.yml index 0bbc8f95..dd69c03a 100644 --- a/.github/workflows/releaser.yml +++ b/.github/workflows/releaser.yml @@ -64,6 +64,11 @@ jobs: echo '"go generate" changed some Go generated code, run "symfony cloud:self-update" then "go generate ./" locally and make a Pull Request with the changes' git diff exit 1 + - + name: Run golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + only-new-issues: true - name: Test run: go test -v ./... diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..d68ee449 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,16 @@ +run: + timeout: 30s + issues-exit-code: 1 + +linters: + enable: + - gci + - wrapcheck + +linters-settings: + wrapcheck: + ignorePackageGlobs: + # We already make sure your own packages wrap errors properly + - github.com/symfony-cli/* + errcheck: + ignore: github.com/symfony-cli/terminal:^(Ep|P)rint diff --git a/book/checkout.go b/book/checkout.go index b9288399..fd323d43 100644 --- a/book/checkout.go +++ b/book/checkout.go @@ -35,7 +35,7 @@ import ( func (b *Book) Checkout(step string) error { // FIXME: keep vendor/ node_modules/ around before git clean, but them back as they will be updated the right way, less Internet traffic // FIXME: if the checkout is to a later step, no need to remove the DB, we can just migrate it - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) step = strings.Replace(step, ".", "-", -1) tag := fmt.Sprintf("step-%s", step) branch := "work-" + tag @@ -80,21 +80,21 @@ func (b *Book) Checkout(step string) error { printBanner("[GIT] Removing Git ignored files (vendor, cache, ...)", b.Debug) if err := executeCommand([]string{"git", "clean", "-d", "-f", "-x"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[GIT] Resetting Git staged files", b.Debug) if err := executeCommand([]string{"git", "reset", "HEAD", "."}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[GIT] Removing un-tracked Git files", b.Debug) if err := executeCommand([]string{"git", "checkout", "."}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[WEB] Adding .env.local", b.Debug) emptyFile, err := os.Create(filepath.Join(b.Dir, ".env.local")) if err != nil { - return err + return errors.WithStack(err) } emptyFile.Close() if !b.Debug { @@ -110,40 +110,44 @@ func (b *Book) Checkout(step string) error { printBanner("[WEB] Stopping Docker Containers", b.Debug) if hasDocker { if err := executeCommand(append(dockerComposeBin(), "down", "--remove-orphans"), b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") } printBanner("[WEB] Stopping the Local Web Server", b.Debug) - executeCommand([]string{"symfony", "server:stop"}, b.Debug, true, nil) + if err := executeCommand([]string{"symfony", "server:stop"}, b.Debug, true, nil); err != nil { + return errors.Wrap(err, "cannot stop the symfony server") + } printBanner("[WEB] Stopping the Platform.sh tunnel", b.Debug) if err := executeCommand([]string{"symfony", "tunnel:close", "-y"}, b.Debug, true, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[GIT] Checking out the step", b.Debug) if err := executeCommand([]string{"git", "checkout", "-B", branch, tag}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[SPA] Stopping the Local Web Server", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "spa")); err == nil { - executeCommand([]string{"symfony", "server:stop", "--dir", filepath.Join(b.Dir, "spa")}, b.Debug, true, nil) + if err := executeCommand([]string{"symfony", "server:stop", "--dir", filepath.Join(b.Dir, "spa")}, b.Debug, true, nil); err != nil { + return errors.Wrap(err, "cannot stop the symfony server") + } } else { terminal.Println("Skipped for this step") } printBanner("[WEB] Installing Composer dependencies (might take some time)", b.Debug) if err := executeCommand([]string{"symfony", "composer", "install"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[WEB] Adding .env.local", b.Debug) if emptyFile, err = os.Create(filepath.Join(b.Dir, ".env.local")); err != nil { - return err + return errors.WithStack(err) } emptyFile.Close() if !b.Debug { @@ -153,7 +157,7 @@ func (b *Book) Checkout(step string) error { printBanner("[WEB] Starting Docker Compose", b.Debug) if hasDocker { if err := executeCommand(append(dockerComposeBin(), "up", "-d"), b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[WEB] Waiting for the Containers to be ready", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "src", "MessageHandler", "CommentMessageHandler.php")); err == nil { @@ -179,7 +183,7 @@ func (b *Book) Checkout(step string) error { } if hasMigrations { if err := executeCommand([]string{"symfony", "console", "doctrine:migrations:migrate", "-n"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -188,7 +192,7 @@ func (b *Book) Checkout(step string) error { printBanner("[WEB] Inserting Fixtures", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "src", "DataFixtures")); err == nil { if err := executeCommand([]string{"symfony", "console", "doctrine:fixtures:load", "-n"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -202,7 +206,7 @@ func (b *Book) Checkout(step string) error { args = []string{"yarn", "install"} } if err := executeCommand(args, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -215,7 +219,7 @@ func (b *Book) Checkout(step string) error { args = []string{"yarn", "encore", "dev"} } if err := executeCommand(args, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -223,13 +227,13 @@ func (b *Book) Checkout(step string) error { printBanner("[WEB] Starting the Local Web Server", b.Debug) if err := executeCommand([]string{"symfony", "server:start", "-d"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } printBanner("[WEB] Starting Message Consumer", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "src", "MessageHandler", "CommentMessageHandler.php")); err == nil { if err := executeCommand([]string{"symfony", "run", "-d", "--watch", "config,src,templates,vendor", "symfony", "console", "messenger:consume", "async", "-vv"}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -237,16 +241,16 @@ func (b *Book) Checkout(step string) error { printBanner("[SPA] Installing Node dependencies (might take some time)", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "spa")); err == nil { - os.Chdir(filepath.Join(b.Dir, "spa")) + _ = os.Chdir(filepath.Join(b.Dir, "spa")) args := []string{"npm", "install"} if _, err := os.Stat(filepath.Join(b.Dir, "yarn.lock")); err == nil { // old version of the book using Yarn instead of npm args = []string{"yarn", "install"} } if err := executeCommand(args, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) } else { terminal.Println("Skipped for this step") } @@ -264,16 +268,16 @@ func (b *Book) Checkout(step string) error { if endpoint.String() == "" { return errors.Errorf("unable to get the URL of the local web server:\n%s\n%s", stderr.String(), endpoint.String()) } - os.Chdir(filepath.Join(b.Dir, "spa")) + _ = os.Chdir(filepath.Join(b.Dir, "spa")) env := append(os.Environ(), "API_ENDPOINT="+endpoint.String()) args := []string{"npx", "encore", "dev"} if _, err := os.Stat(filepath.Join(b.Dir, "yarn.lock")); err == nil { args = []string{"yarn", "encore", "dev"} } if err := executeCommand(args, b.Debug, false, env); err != nil { - return err + return errors.WithStack(err) } - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) } else { terminal.Println("Skipped for this step") } @@ -281,7 +285,7 @@ func (b *Book) Checkout(step string) error { printBanner("[SPA] Starting the Local Web Server", b.Debug) if _, err := os.Stat(filepath.Join(b.Dir, "spa")); err == nil { if err := executeCommand([]string{"symfony", "server:start", "-d", "--passthru", "index.html", "--dir", filepath.Join(b.Dir, "spa")}, b.Debug, false, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -322,7 +326,7 @@ func executeCommand(args []string, debug, skipErrors bool, env []string) error { terminal.Println("[ KO ]") } terminal.Print(buf.String()) - return err + return errors.WithStack(err) } if !debug { terminal.Println("[ OK ]") diff --git a/book/clone.go b/book/clone.go index 84f3c116..9907183a 100644 --- a/book/clone.go +++ b/book/clone.go @@ -33,7 +33,7 @@ func (b *Book) Clone(version string) error { ui.Section("Checking Book Requirements") ready, err := CheckRequirements() if err != nil { - return err + return errors.WithStack(err) } terminal.Println("") if !ready { @@ -50,7 +50,7 @@ func (b *Book) Clone(version string) error { } terminal.Println("") - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) // checkout the first step by default ui.Section("Getting Ready for the First Step of the Book") if err := b.Checkout("3"); err != nil { @@ -59,7 +59,7 @@ func (b *Book) Clone(version string) error { terminal.Println("Re-run the command with --debug to get more information about the error") terminal.Println("") } - return err + return errors.WithStack(err) } return nil } diff --git a/book/reqs.go b/book/reqs.go index 7cc8a9de..dd1ccb1e 100644 --- a/book/reqs.go +++ b/book/reqs.go @@ -65,12 +65,12 @@ func CheckRequirements() (bool, error) { // PHP minv, err := version.NewVersion("8.1.0") if err != nil { - return false, err + return false, errors.WithStack(err) } store := phpstore.New(util.GetHomeDir(), true, nil) wd, err := os.Getwd() if err != nil { - return false, err + return false, errors.WithStack(err) } v, _, _, _ := store.BestVersionForDir(wd) if v == nil { diff --git a/commands/book_check_reqs.go b/commands/book_check_reqs.go index 5eba2d1b..dc9b4c2a 100644 --- a/commands/book_check_reqs.go +++ b/commands/book_check_reqs.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/book" "github.com/symfony-cli/terminal" @@ -35,7 +36,7 @@ var bookCheckReqsCmd = &console.Command{ ready, err := book.CheckRequirements() if err != nil { - return err + return errors.WithStack(err) } terminal.Println("") if ready { diff --git a/commands/book_checkout.go b/commands/book_checkout.go index 833c6b66..6a7bcd12 100644 --- a/commands/book_checkout.go +++ b/commands/book_checkout.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/book" "github.com/symfony-cli/terminal" @@ -40,7 +41,7 @@ var bookCheckoutCmd = &console.Command{ Action: func(c *console.Context) error { dir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } book := &book.Book{ @@ -50,7 +51,7 @@ var bookCheckoutCmd = &console.Command{ } if !c.Bool("force") { if err := book.CheckRepository(); err != nil { - return err + return errors.WithStack(err) } } if err := book.Checkout(c.Args().Get("step")); err != nil { @@ -59,7 +60,7 @@ var bookCheckoutCmd = &console.Command{ terminal.Println("Re-run the command with --debug to get more information about the error") terminal.Println("") } - return err + return errors.WithStack(err) } return nil }, diff --git a/commands/init_templating.go b/commands/init_templating.go index 859cd50a..711fabb0 100644 --- a/commands/init_templating.go +++ b/commands/init_templating.go @@ -22,7 +22,6 @@ package commands import ( "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -194,19 +193,19 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri ) if isFile { - templateConfigBytes, err = ioutil.ReadFile(chosenTemplateName) + templateConfigBytes, err = os.ReadFile(chosenTemplateName) } else { var resp *http.Response resp, err = http.Get(chosenTemplateName) if err != nil { - return nil, err + return nil, errors.WithStack(err) } if resp.StatusCode >= 400 { return nil, errors.Errorf("Got HTTP status code >= 400: %s", resp.Status) } defer resp.Body.Close() - templateConfigBytes, err = ioutil.ReadAll(resp.Body) + templateConfigBytes, err = io.ReadAll(resp.Body) } if err != nil { @@ -219,7 +218,7 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri terminal.Logger.Info().Msg("Using template " + chosenTemplateName) } else { - files, err := ioutil.ReadDir(directory) + files, err := os.ReadDir(directory) if err != nil { return nil, errors.Wrap(err, "could not read configuration templates") } @@ -240,7 +239,7 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri continue } - templateConfigBytes, err := ioutil.ReadFile(filepath.Join(directory, file.Name())) + templateConfigBytes, err := os.ReadFile(filepath.Join(directory, file.Name())) if err != nil { if isTemplateChosen { return nil, errors.Wrap(err, "could not apply configuration template") @@ -275,7 +274,7 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri return nil, errors.New("no matching template found") } - phpini, err := ioutil.ReadFile(filepath.Join(directory, "php.ini")) + phpini, err := os.ReadFile(filepath.Join(directory, "php.ini")) if err != nil { return nil, errors.New("unable to find the php.ini template") } diff --git a/commands/init_templating_php.go b/commands/init_templating_php.go index 5b57399f..6182da7f 100644 --- a/commands/init_templating_php.go +++ b/commands/init_templating_php.go @@ -22,10 +22,11 @@ package commands import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" + "github.com/pkg/errors" "github.com/symfony-cli/terminal" ) @@ -158,18 +159,18 @@ type composerLock struct { } func parseComposerLock(directory string) (*composerLock, error) { - b, err := ioutil.ReadFile(filepath.Join(directory, "composer.lock")) + b, err := os.ReadFile(filepath.Join(directory, "composer.lock")) if err != nil { - return nil, err + return nil, errors.WithStack(err) } var lock composerLock if err := json.Unmarshal(b, &lock); err != nil { - return nil, err + return nil, errors.WithStack(err) } - return &lock, err + return &lock, errors.WithStack(err) } type composerJSON struct { @@ -181,14 +182,14 @@ type composerJSON struct { } func parseComposerJSON(directory string) (*composerJSON, error) { - b, err := ioutil.ReadFile(filepath.Join(directory, "composer.json")) + b, err := os.ReadFile(filepath.Join(directory, "composer.json")) if err != nil { - return nil, err + return nil, errors.WithStack(err) } var composerJSON composerJSON if err := json.Unmarshal(b, &composerJSON); err != nil { - return nil, err + return nil, errors.WithStack(err) } return &composerJSON, nil diff --git a/commands/local_check_requirements.go b/commands/local_check_requirements.go index 6671a9ce..5d085e71 100644 --- a/commands/local_check_requirements.go +++ b/commands/local_check_requirements.go @@ -21,10 +21,10 @@ package commands import ( _ "embed" - "io/ioutil" "os" "path/filepath" + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/php" "github.com/symfony-cli/symfony-cli/util" @@ -33,6 +33,7 @@ import ( // To generate, run in symfony/requirements-checker // php bin/release.php > data/check-requirements.php +// //go:embed data/check-requirements.php var phpChecker []byte @@ -50,21 +51,21 @@ var localRequirementsCheckCmd = &console.Command{ var err error path, err = os.Getwd() if err != nil { - return err + return errors.WithStack(err) } } cacheDir := filepath.Join(util.GetHomeDir(), "cache") if _, err := os.Stat(cacheDir); err != nil { if err := os.MkdirAll(cacheDir, 0755); err != nil { - return err + return errors.WithStack(err) } } cachePath := filepath.Join(cacheDir, "check.php") defer os.Remove(cachePath) - if err := ioutil.WriteFile(cachePath, phpChecker, 0600); err != nil { - return err + if err := os.WriteFile(cachePath, phpChecker, 0600); err != nil { + return errors.WithStack(err) } args := []string{"php", cachePath} diff --git a/commands/local_check_security.go b/commands/local_check_security.go index 8c88775b..e8a35b4b 100644 --- a/commands/local_check_security.go +++ b/commands/local_check_security.go @@ -69,7 +69,9 @@ a specific "composer.lock" file.`, if err != nil { return console.Exit(fmt.Sprintf("unable to output the results: %s", err), 127) } - terminal.Stdout.Write(output) + if _, err := terminal.Stdout.Write(output); err != nil { + return console.Exit(fmt.Sprintf("unable to output the results: %s", err), 127) + } if os.Getenv("GITHUB_WORKSPACE") != "" { gOutFile := os.Getenv("GITHUB_OUTPUT") diff --git a/commands/local_new.go b/commands/local_new.go index e94fafc4..12b33514 100644 --- a/commands/local_new.go +++ b/commands/local_new.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "os/exec" @@ -141,49 +140,49 @@ var localNewCmd = &console.Command{ minorPHPVersion, err := forcePHPVersion(c.String("php"), dir) if err != nil { - return err + return errors.WithStack(err) } if err := createProjectWithComposer(c, dir, symfonyVersion); err != nil { - return err + return errors.WithStack(err) } if "" != c.String("php") && !c.Bool("cloud") { if err := createPhpVersionFile(c.String("php"), dir); err != nil { - return err + return errors.WithStack(err) } } if !c.Bool("no-git") { if _, err := exec.LookPath("git"); err == nil { if err := initProjectGit(c, s, dir); err != nil { - return err + return errors.WithStack(err) } } } if c.Bool("webapp") { if err := runComposer(c, dir, []string{"require", "webapp"}, c.Bool("debug")); err != nil { - return err + return errors.WithStack(err) } buf, err := git.AddAndCommit(dir, []string{"."}, "Add webapp packages", c.Bool("debug")) if err != nil { fmt.Print(buf.String()) - return err + return errors.WithStack(err) } } if c.Bool("cloud") { if err := runComposer(c, dir, []string{"require", "platformsh"}, c.Bool("debug")); err != nil { - return err + return errors.WithStack(err) } buf, err := git.AddAndCommit(dir, []string{"."}, "Add more packages", c.Bool("debug")) if err != nil { fmt.Print(buf.String()) - return err + return errors.WithStack(err) } if err := initCloud(c, s, minorPHPVersion, dir); err != nil { - return err + return errors.WithStack(err) } } @@ -200,7 +199,7 @@ var localNewCmd = &console.Command{ func isEmpty(dir string) (bool, error) { f, err := os.Open(dir) if err != nil { - return false, err + return false, errors.WithStack(err) } defer f.Close() @@ -208,7 +207,7 @@ func isEmpty(dir string) (bool, error) { if err == io.EOF { return true, nil } - return false, err + return false, errors.WithStack(err) } func initCloud(c *console.Context, s *terminal.Spinner, minorPHPVersion, dir string) error { @@ -216,27 +215,27 @@ func initCloud(c *console.Context, s *terminal.Spinner, minorPHPVersion, dir str cloudServices, err := parseCloudServices(dir, c.StringSlice("service")) if err != nil { - return err + return errors.WithStack(err) } // FIXME: display or hide output based on debug flag _, err = createRequiredFilesProject(dir, "app", "", minorPHPVersion, cloudServices, c.Bool("dump"), c.Bool("force")) if err != nil { - return err + return errors.WithStack(err) } buf, err := git.AddAndCommit(dir, []string{"."}, "Add Platform.sh configuration", c.Bool("debug")) if err != nil { fmt.Print(buf.String()) } - return err + return errors.WithStack(err) } func parseCloudServices(dir string, services []string) ([]*CloudService, error) { // from CLI flag cloudServices, err := parseCLIServices(services) if err != nil { - return nil, err + return nil, errors.WithStack(err) } // from Docker Compose configuration @@ -323,13 +322,13 @@ func initProjectGit(c *console.Context, s *terminal.Spinner, dir string) error { // onboarding simpler. if buf, err := git.Init(dir, c.Bool("cloud"), c.Bool("debug")); err != nil { fmt.Print(buf.String()) - return err + return errors.WithStack(err) } buf, err := git.AddAndCommit(dir, []string{"."}, "Add initial set of files", c.Bool("debug")) if err != nil { fmt.Print(buf.String()) } - return err + return errors.WithStack(err) } func createProjectWithComposer(c *console.Context, dir, version string) error { @@ -340,7 +339,7 @@ func createProjectWithComposer(c *console.Context, dir, version string) error { var err error version, err = getSpecialVersion(version) if err != nil { - return err + return errors.WithStack(err) } } @@ -385,7 +384,7 @@ func runComposer(c *console.Context, dir string, args []string, debug bool) erro if err := php.Composer(dir, args, env, out, err, os.Stderr, terminal.Logger); err.ExitCode() != 0 { terminal.Println(buf.String()) - return err + return errors.WithStack(err) } return nil } @@ -393,18 +392,18 @@ func runComposer(c *console.Context, dir string, args []string, debug bool) erro func getSpecialVersion(version string) (string, error) { resp, err := http.Get("https://symfony.com/all-versions.json") if err != nil { - return "", err + return "", errors.WithStack(err) } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { - return "", err + return "", errors.WithStack(err) } var versions map[string]interface{} if err := json.Unmarshal(body, &versions); err != nil { - return "", err + return "", errors.WithStack(err) } v := versions[version].(string) @@ -420,7 +419,7 @@ func forcePHPVersion(v, dir string) (string, error) { if v == "" { minor, _, _, err := store.BestVersionForDir(dir) if err != nil { - return "", err + return "", errors.WithStack(err) } return strings.Join(strings.Split(minor.Version, ".")[0:2], "."), nil } diff --git a/commands/local_proxy_domain_attach.go b/commands/local_proxy_domain_attach.go index ea37acf7..c65fc5b9 100644 --- a/commands/local_proxy_domain_attach.go +++ b/commands/local_proxy_domain_attach.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/proxy" "github.com/symfony-cli/symfony-cli/util" @@ -40,16 +41,16 @@ var localProxyAttachDomainCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } homeDir := util.GetHomeDir() config, err := proxy.Load(homeDir) if err != nil { - return err + return errors.WithStack(err) } if err := config.AddDirDomains(projectDir, c.Args().Tail()); err != nil { - return err + return errors.WithStack(err) } terminal.Println("The proxy is now configured with the following domains for this directory:") for _, domain := range config.GetDomains(projectDir) { diff --git a/commands/local_proxy_domain_detach.go b/commands/local_proxy_domain_detach.go index 45783544..71d6d6d3 100644 --- a/commands/local_proxy_domain_detach.go +++ b/commands/local_proxy_domain_detach.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/proxy" "github.com/symfony-cli/symfony-cli/util" @@ -38,11 +39,11 @@ var localProxyDetachDomainCmd = &console.Command{ homeDir := util.GetHomeDir() config, err := proxy.Load(homeDir) if err != nil { - return err + return errors.WithStack(err) } domains := c.Args().Tail() if err := config.RemoveDirDomains(domains); err != nil { - return err + return errors.WithStack(err) } terminal.Println("The following domains are not defined anymore on the proxy:") for _, domain := range domains { diff --git a/commands/local_proxy_start.go b/commands/local_proxy_start.go index f3952b14..8b00bbea 100644 --- a/commands/local_proxy_start.go +++ b/commands/local_proxy_start.go @@ -68,7 +68,7 @@ var localProxyStartCmd = &console.Command{ } if err := reexec.Background(varDir); err != nil { if _, isExitCoder := err.(console.ExitCoder); isExitCoder { - return err + return errors.WithStack(err) } terminal.Printfln("Impossible to go to the background: %s", err) terminal.Println("Continue in foreground") @@ -90,7 +90,7 @@ var localProxyStartCmd = &console.Command{ } if ca != nil { if err := ca.LoadCA(); err != nil { - return err + return errors.WithStack(err) } if ca.IsExpired() { ui.Warning(fmt.Sprintf(`Your local CA is expired, run "%s %s --renew" first to renew it`, c.App.HelpName, localServerCAInstallCmd.FullName())) @@ -112,18 +112,17 @@ var localProxyStartCmd = &console.Command{ if err != nil { return errors.WithStack(err) } - var lw io.Writer - lw = f + lw := f logger := zerolog.New(decorateLogger(lw, c.Bool("no-humanize"))).With().Timestamp().Logger() config, err := proxy.Load(homeDir) if err != nil { - return err + return errors.WithStack(err) } if c.IsSet("host") { config.Host = c.String("host") - config.Save() + _ = config.Save() } spinner := terminal.NewSpinner(terminal.Stderr) @@ -146,7 +145,7 @@ var localProxyStartCmd = &console.Command{ case err := <-errChan: if err != nil { timer.Stop() - return err + return errors.WithStack(err) } case <-timer.C: spinner.Stop() @@ -154,14 +153,16 @@ var localProxyStartCmd = &console.Command{ } if err := pidFile.Write(os.Getpid(), config.Port, "http"); err != nil { - return err + return errors.WithStack(err) } if !c.Bool("foreground") && reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) - reexec.NotifyForeground(reexec.UP) + _ = reexec.NotifyForeground(reexec.UP) } else { - defer pidFile.Remove() + defer func() { + _ = pidFile.Remove() + }() } shutdownCh := make(chan bool, 1) diff --git a/commands/local_proxy_stop.go b/commands/local_proxy_stop.go index 17600669..c9f5096a 100644 --- a/commands/local_proxy_stop.go +++ b/commands/local_proxy_stop.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/pid" "github.com/symfony-cli/terminal" @@ -38,7 +39,7 @@ var localProxyStopCmd = &console.Command{ return nil } if err := p.Stop(); err != nil { - return err + return errors.WithStack(err) } ui.Success("Stopped the proxy server successfully") return nil diff --git a/commands/local_run.go b/commands/local_run.go index 6a89f769..f73d0cab 100644 --- a/commands/local_run.go +++ b/commands/local_run.go @@ -55,7 +55,7 @@ var localRunCmd = &console.Command{ } projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } mode := local.RunnerModeOnce @@ -70,13 +70,13 @@ var localRunCmd = &console.Command{ pidFile.Watched = directories runner, err := local.NewRunner(pidFile, mode) if err != nil { - return err + return errors.WithStack(err) } runner.BuildCmdHook = func(cmd *exec.Cmd) error { env, err := envs.GetEnv(pidFile.Dir, terminal.IsDebug()) if err != nil { - return err + return errors.WithStack(err) } cmd.Env = append(cmd.Env, envs.AsSlice(env)...) @@ -90,7 +90,7 @@ var localRunCmd = &console.Command{ return nil } - return err + return errors.WithStack(err) } return nil diff --git a/commands/local_server_ca_install.go b/commands/local_server_ca_install.go index f29a1b2d..97ea05e4 100644 --- a/commands/local_server_ca_install.go +++ b/commands/local_server_ca_install.go @@ -45,7 +45,7 @@ var localServerCAInstallCmd = &console.Command{ certsDir := filepath.Join(homeDir, "certs") ca, err := cert.NewCA(certsDir) if err != nil { - return err + return errors.WithStack(err) } newCA := false renew := c.Bool("renew") @@ -61,8 +61,8 @@ var localServerCAInstallCmd = &console.Command{ return errors.Wrap(err, "failed to load the local Certificate Authority") } if renew && !newCA { - ca.Uninstall() - os.RemoveAll(certsDir) + _ = ca.Uninstall() + _ = os.RemoveAll(certsDir) renew = false goto retry diff --git a/commands/local_server_ca_uninstall.go b/commands/local_server_ca_uninstall.go index bdcf2b7e..f133bfdd 100644 --- a/commands/local_server_ca_uninstall.go +++ b/commands/local_server_ca_uninstall.go @@ -49,8 +49,8 @@ var localServerCAUninstallCmd = &console.Command{ if err = ca.LoadCA(); err != nil { return errors.Wrap(err, "failed to load the local Certificate Authority") } - ca.Uninstall() - os.RemoveAll(certsDir) + _ = ca.Uninstall() + _ = os.RemoveAll(certsDir) ui.Success("The local Certificate Authority has been uninstalled") return nil }, diff --git a/commands/local_server_log.go b/commands/local_server_log.go index 14ebcf10..bb800256 100644 --- a/commands/local_server_log.go +++ b/commands/local_server_log.go @@ -20,6 +20,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/logs" "github.com/symfony-cli/symfony-cli/local/pid" @@ -47,7 +48,7 @@ var localServerLogCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } tailer := logs.Tailer{ @@ -61,7 +62,7 @@ var localServerLogCmd = &console.Command{ } if err := tailer.Watch(pid.New(projectDir, nil)); err != nil { - return err + return errors.WithStack(err) } return tailer.Tail(terminal.Stderr) diff --git a/commands/local_server_prod.go b/commands/local_server_prod.go index 4ef563c1..0eedc139 100644 --- a/commands/local_server_prod.go +++ b/commands/local_server_prod.go @@ -39,7 +39,7 @@ var localServerProdCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } beacon := filepath.Join(projectDir, ".prod") if c.Bool("off") { diff --git a/commands/local_server_start.go b/commands/local_server_start.go index 7cfd022d..8a821483 100644 --- a/commands/local_server_start.go +++ b/commands/local_server_start.go @@ -84,7 +84,7 @@ var localServerStartCmd = &console.Command{ ui := terminal.SymfonyStyle(terminal.Stdout, terminal.Stdin) projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } pidFile := pid.New(projectDir, nil) pidFile.CustomName = "Web Server" @@ -93,7 +93,7 @@ var localServerStartCmd = &console.Command{ return errors.WithStack(printWebServerStatus(projectDir)) } if err := cleanupWebServerFiles(projectDir, pidFile); err != nil { - return err + return errors.WithStack(err) } homeDir := util.GetHomeDir() @@ -112,7 +112,7 @@ var localServerStartCmd = &console.Command{ return console.Exit("", 1) } - reexec.NotifyForeground("config") + _ = reexec.NotifyForeground("config") config, fileConfig, err := project.NewConfigFromContext(c, projectDir) if err != nil { return errors.WithStack(err) @@ -126,7 +126,7 @@ var localServerStartCmd = &console.Command{ } if err := reexec.Background(varDir); err != nil { if _, isExitCoder := err.(console.ExitCoder); isExitCoder { - return err + return errors.WithStack(err) } terminal.Eprintln("Impossible to go to the background") terminal.Eprintln("Continue in foreground") @@ -137,7 +137,7 @@ var localServerStartCmd = &console.Command{ } } - reexec.NotifyForeground("proxy") + _ = reexec.NotifyForeground("proxy") proxyConfig, err := proxy.Load(homeDir) if err != nil { return errors.WithStack(err) @@ -148,7 +148,7 @@ var localServerStartCmd = &console.Command{ } } - reexec.NotifyForeground("tls") + _ = reexec.NotifyForeground("tls") if !config.NoTLS && config.PKCS12 == "" { ca, err := cert.NewCA(filepath.Join(homeDir, "certs")) if err != nil { @@ -186,12 +186,12 @@ var localServerStartCmd = &console.Command{ lw, err := pidFile.LogWriter() if err != nil { - return err + return errors.WithStack(err) } config.Logger = zerolog.New(lw).With().Str("source", "server").Timestamp().Logger() p, err := project.New(config) if err != nil { - return err + return errors.WithStack(err) } ctx, cancel := context.WithCancel(context.Background()) @@ -206,14 +206,14 @@ var localServerStartCmd = &console.Command{ errChan := make(chan error, 1) if !reexec.IsChild() { - tailer.Watch(pidFile) + _ = tailer.Watch(pidFile) } if p.PHPServer != nil { - reexec.NotifyForeground("php") + _ = reexec.NotifyForeground("php") phpPidFile, phpStartCallback, err := p.PHPServer.Start(ctx, pidFile) if err != nil { - return err + return errors.WithStack(err) } // We retrieve a reader on logs as soon as possible to be able to @@ -221,7 +221,7 @@ var localServerStartCmd = &console.Command{ // later as the log file will already be deleted. logs, err := phpPidFile.LogReader() if err != nil { - return err + return errors.WithStack(err) } if !reexec.IsChild() { @@ -254,22 +254,22 @@ var localServerStartCmd = &console.Command{ ui.Error(buf.String()) if err != nil { - return err + return errors.WithStack(err) } return nil case err := <-phpPidFile.WaitForPid(): // PHP started, we can close logs and go ahead logs.Close() if err != nil { - return err + return errors.WithStack(err) } } } - reexec.NotifyForeground("http") + _ = reexec.NotifyForeground("http") port, err := p.HTTP.Start(errChan) if err != nil { - return err + return errors.WithStack(err) } scheme := "https" @@ -291,24 +291,26 @@ var localServerStartCmd = &console.Command{ select { case err := <-errChan: if err != cmux.ErrListenerClosed && err != http.ErrServerClosed { - return err + return errors.WithStack(err) } default: if err := pidFile.Write(os.Getpid(), port, scheme); err != nil { - return err + return errors.WithStack(err) } - reexec.NotifyForeground("listening") + _ = reexec.NotifyForeground("listening") ui.Warning(localWebServerProdWarningMsg) ui.Success(msg) } if !reexec.IsChild() { - go tailer.Tail(terminal.Stderr) + go func() { + _ = tailer.Tail(terminal.Stderr) + }() } if fileConfig != nil { - reexec.NotifyForeground("workers") + _ = reexec.NotifyForeground("workers") for name, worker := range fileConfig.Workers { pidFile := pid.New(projectDir, worker.Cmd) if pidFile.IsRunning() { @@ -347,19 +349,19 @@ var localServerStartCmd = &console.Command{ } } - reexec.NotifyForeground(reexec.UP) + _ = reexec.NotifyForeground(reexec.UP) if reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) } select { case err := <-errChan: - return err + return errors.WithStack(err) case <-shutdownCh: terminal.Eprintln("") terminal.Eprintln("Shutting down!") if err := cleanupWebServerFiles(projectDir, pidFile); err != nil { - return err + return errors.WithStack(err) } terminal.Eprintln("") ui.Success("Stopped all processes successfully") @@ -377,10 +379,10 @@ func cleanupWebServerFiles(projectDir string, pidFile *pid.PidFile) error { } } if err := g.Wait(); err != nil { - return err + return errors.WithStack(err) } if err := pidFile.Remove(); err != nil { - return err + return errors.WithStack(err) } return nil } diff --git a/commands/local_server_status.go b/commands/local_server_status.go index 13936caf..5c6fa7a0 100644 --- a/commands/local_server_status.go +++ b/commands/local_server_status.go @@ -23,6 +23,7 @@ import ( "fmt" "strings" + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/phpstore" "github.com/symfony-cli/symfony-cli/envs" @@ -43,7 +44,7 @@ var localServerStatusCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } return printWebServerStatus(projectDir) @@ -98,7 +99,7 @@ func printWebServerStatus(projectDir string) error { terminal.Println("Environment Variables") data, err := envs.GetEnv(projectDir, terminal.IsDebug()) if err != nil { - return err + return errors.WithStack(err) } env := envs.AsMap(data) envVars := `None` diff --git a/commands/local_server_stop.go b/commands/local_server_stop.go index 39708f1e..d5349f95 100644 --- a/commands/local_server_stop.go +++ b/commands/local_server_stop.go @@ -22,6 +22,7 @@ package commands import ( "fmt" + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/pid" "github.com/symfony-cli/terminal" @@ -39,7 +40,7 @@ var localServerStopCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } ui := terminal.SymfonyStyle(terminal.Stdout, terminal.Stdin) webserver := pid.New(projectDir, nil) @@ -59,7 +60,7 @@ var localServerStopCmd = &console.Command{ terminal.Println("") if err := g.Wait(); err != nil { - return err + return errors.WithStack(err) } if running == 0 { ui.Success("The web server is not running") diff --git a/commands/local_var_expose.go b/commands/local_var_expose.go index 18b9f0e1..cb534a3c 100644 --- a/commands/local_var_expose.go +++ b/commands/local_var_expose.go @@ -22,6 +22,7 @@ package commands import ( "os" + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/envs" "github.com/symfony-cli/symfony-cli/local/platformsh" @@ -42,13 +43,13 @@ var localVariableExposeFromTunnelCmd = &console.Command{ if dir == "" { var err error if dir, err = os.Getwd(); err != nil { - return err + return errors.WithStack(err) } } project, err := platformsh.ProjectFromDir(dir, false) if err != nil { - return err + return errors.WithStack(err) } tunnel := envs.Tunnel{Project: project} diff --git a/commands/openers.go b/commands/openers.go index 7e51e8a3..af80d076 100644 --- a/commands/openers.go +++ b/commands/openers.go @@ -23,6 +23,7 @@ import ( "fmt" "strings" + "github.com/pkg/errors" "github.com/skratchdot/open-golang/open" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/envs" @@ -32,16 +33,6 @@ import ( "github.com/symfony-cli/terminal" ) -var openDocCmd = &console.Command{ - Category: "open", - Name: "docs", - Usage: "Open the online Web documentation", - Action: func(c *console.Context) error { - abstractOpenCmd("https://symfony.com/doc/cloud") - return nil - }, -} - var projectLocalOpenCmd = &console.Command{ Category: "open", Name: "local", @@ -56,7 +47,7 @@ var projectLocalOpenCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } pidFile := pid.New(projectDir, nil) if !pidFile.IsRunning() { @@ -88,11 +79,11 @@ var projectLocalMailCatcherOpenCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } env, err := envs.NewLocal(projectDir, terminal.IsDebug()) if err != nil { - return err + return errors.WithStack(err) } url, exists := env.FindServiceUrl("mailer") if !exists { @@ -113,11 +104,11 @@ var projectLocalRabbitMQManagementOpenCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } env, err := envs.NewLocal(projectDir, terminal.IsDebug()) if err != nil { - return err + return errors.WithStack(err) } url, exists := env.FindServiceUrl("amqp") if !exists { @@ -141,11 +132,11 @@ var projectLocalServiceOpenCmd = &console.Command{ Action: func(c *console.Context) error { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } env, err := envs.NewLocal(projectDir, terminal.IsDebug()) if err != nil { - return err + return errors.WithStack(err) } service := c.Args().Get("service") url, exists := env.FindServiceUrl(service) diff --git a/commands/platformsh.go b/commands/platformsh.go index e880eb57..382f4eab 100644 --- a/commands/platformsh.go +++ b/commands/platformsh.go @@ -28,6 +28,7 @@ import ( "strings" "github.com/mitchellh/go-homedir" + "github.com/pkg/errors" "github.com/rs/zerolog" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/local/php" @@ -44,7 +45,7 @@ type platformshCLI struct { func NewPlatformShCLI() (*platformshCLI, error) { home, err := homedir.Dir() if err != nil { - return nil, err + return nil, errors.WithStack(err) } p := &platformshCLI{ path: filepath.Join(home, ".platformsh", "bin", "platform"), @@ -95,7 +96,7 @@ func (p *platformshCLI) proxyPSHCmd(commandName string) console.ActionFunc { if !util.InCloud() { home, err := homedir.Dir() if err != nil { - return err + return errors.WithStack(err) } if err := php.InstallPlatformPhar(home); err != nil { return console.Exit(err.Error(), 1) @@ -104,7 +105,7 @@ func (p *platformshCLI) proxyPSHCmd(commandName string) console.ActionFunc { if hook, ok := platformshBeforeHooks["cloud:"+commandName]; ok && !console.IsHelp(c) { if err := hook(c); err != nil { - return err + return errors.WithStack(err) } } diff --git a/commands/platformsh_hooks.go b/commands/platformsh_hooks.go index ea5d3ef9..030b79d2 100644 --- a/commands/platformsh_hooks.go +++ b/commands/platformsh_hooks.go @@ -1,6 +1,7 @@ package commands import ( + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/envs" "github.com/symfony-cli/symfony-cli/local/platformsh" @@ -18,11 +19,11 @@ var platformshBeforeHooks = map[string]console.BeforeFunc{ if projectID == "" { projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } project, err = platformsh.ProjectFromDir(projectDir, false) if err != nil { - return err + return errors.WithStack(err) } if app != "" { project.App = app diff --git a/commands/project_init.go b/commands/project_init.go index ffcbd4c0..27717ff0 100644 --- a/commands/project_init.go +++ b/commands/project_init.go @@ -26,6 +26,7 @@ import ( "path/filepath" "strings" + "github.com/pkg/errors" "github.com/symfony-cli/console" "github.com/symfony-cli/symfony-cli/git" "github.com/symfony-cli/terminal" @@ -57,17 +58,17 @@ Templates used by this tool are fetched from ` + templatesGitRepository + `. projectDir, err := getProjectDir(c.String("dir")) if err != nil { - return err + return errors.WithStack(err) } minorPHPVersion, err := forcePHPVersion(c.String("php"), projectDir) if err != nil { - return err + return errors.WithStack(err) } if buf, err := gitInit(projectDir); err != nil { fmt.Print(buf.String()) - return err + return errors.WithStack(err) } slug := c.String("slug") if slug == "" { @@ -76,12 +77,12 @@ Templates used by this tool are fetched from ` + templatesGitRepository + `. cloudServices, err := parseCloudServices(projectDir, c.StringSlice("service")) if err != nil { - return err + return errors.WithStack(err) } createdFiles, err := createRequiredFilesProject(projectDir, slug, c.String("template"), minorPHPVersion, cloudServices, c.Bool("dump"), c.Bool("force")) if err != nil { - return err + return errors.WithStack(err) } if c.Bool("dump") { diff --git a/commands/root.go b/commands/root.go index be211051..1d8d7b0f 100644 --- a/commands/root.go +++ b/commands/root.go @@ -107,7 +107,7 @@ func GetPSH() (*platformshCLI, error) { err = errors.Wrap(err, "Unable to setup Platform.sh CLI") } }) - return psh, err + return psh, errors.WithStack(err) } func InitAppFunc(c *console.Context) error { @@ -148,7 +148,7 @@ func WelcomeAction(c *console.Context) error { terminal.Println("") psh, err := GetPSH() if err != nil { - return err + return errors.WithStack(err) } displayCommandsHelp(c, append([]*console.Command{projectInitCmd}, psh.PSHMainCommands()...)) terminal.Println("") @@ -184,8 +184,9 @@ func getProjectDir(dir string) (string, error) { var err error if dir, err = filepath.Abs(dir); err != nil { - return "", err + return "", errors.WithStack(err) } - return filepath.EvalSymlinks(dir) + s, err := filepath.EvalSymlinks(dir) + return s, errors.WithStack(err) } diff --git a/commands/var_export.go b/commands/var_export.go index d17c0574..f6d19273 100644 --- a/commands/var_export.go +++ b/commands/var_export.go @@ -46,12 +46,12 @@ var variableExportCmd = &console.Command{ if dir == "" { var err error if dir, err = os.Getwd(); err != nil { - return err + return errors.WithStack(err) } } env, err := envs.GetEnv(dir, c.Bool("debug")) if err != nil { - return err + return errors.WithStack(err) } if name := c.Args().Get("name"); name != "" { diff --git a/envs/docker.go b/envs/docker.go index dbabdd05..d4dbf4d4 100644 --- a/envs/docker.go +++ b/envs/docker.go @@ -23,7 +23,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "net" "net/url" "os" @@ -197,266 +196,268 @@ func (l *Local) dockerServiceToRelationship(client *docker.Client, container typ } sort.Sort(exposedPorts) - for _, p := range exposedPorts { - rels := make(map[string]map[string]interface{}) - if p.PrivatePort == 1025 { - // recommended image: schickling/mailcatcher - for _, pw := range exposedPorts { - if pw.PrivatePort == 1080 || pw.PrivatePort == 8025 { - rels["-web"] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(pw.PublicPort), - "rel": "mailer", - "scheme": "http", - } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "mailer", - "scheme": "smtp", - } - return rels + + if len(exposedPorts) == 0 { + return nil + } + + p := exposedPorts[0] + rels := make(map[string]map[string]interface{}) + if p.PrivatePort == 1025 { + // recommended image: schickling/mailcatcher + for _, pw := range exposedPorts { + if pw.PrivatePort == 1080 || pw.PrivatePort == 8025 { + rels["-web"] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(pw.PublicPort), + "rel": "mailer", + "scheme": "http", } - } - } else if p.PrivatePort == 25 { - // recommended image: djfarrelly/maildev - for _, pw := range exposedPorts { - if pw.PrivatePort == 80 { - rels["-web"] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(pw.PublicPort), - "rel": "mailer", - "scheme": "http", - } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "mailer", - "scheme": "smtp", - } - return rels + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "mailer", + "scheme": "smtp", } + return rels } - } else if p.PrivatePort == 8707 || p.PrivatePort == 8307 { - // Blackfire - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "blackfire", - "scheme": "tcp", - } - return rels - } else if p.PrivatePort == 3306 { - username := "" - password := "" - path := "" - // MARIADB is used by bitnami/mariadb - for _, prefix := range []string{"MYSQL", "MARIADB"} { - for _, env := range c.Config.Env { - if strings.HasPrefix(env, prefix+"_ROOT_PASSWORD") && password == "" { - // *_PASSWORD has precedence over *_ROOT_PASSWORD - password = getEnvValue(env, prefix+"_ROOT_PASSWORD") - username = "root" - } else if strings.HasPrefix(env, prefix+"_USER") { - username = getEnvValue(env, prefix+"_USER") - } else if strings.HasPrefix(env, prefix+"_PASSWORD") { - password = getEnvValue(env, prefix+"_PASSWORD") - } else if strings.HasPrefix(env, prefix+"_DATABASE") { - path = getEnvValue(env, prefix+"_DATABASE") - } + } + } else if p.PrivatePort == 25 { + // recommended image: djfarrelly/maildev + for _, pw := range exposedPorts { + if pw.PrivatePort == 80 { + rels["-web"] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(pw.PublicPort), + "rel": "mailer", + "scheme": "http", } - } - if path == "" { - path = username - } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "username": username, - "password": password, - "path": path, - "port": formatDockerPort(p.PublicPort), - "query": map[string]bool{ - "is_master": true, - }, - "rel": "mysql", - "scheme": "mysql", - } - return rels - } else if p.PrivatePort == 5432 { - username := "" - password := "" - path := "" - for _, env := range c.Config.Env { - if strings.HasPrefix(env, "POSTGRES_USER") { - username = getEnvValue(env, "POSTGRES_USER") - } else if strings.HasPrefix(env, "POSTGRES_PASSWORD") { - password = getEnvValue(env, "POSTGRES_PASSWORD") - } else if strings.HasPrefix(env, "POSTGRES_DB") { - path = getEnvValue(env, "POSTGRES_DB") + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "mailer", + "scheme": "smtp", } + return rels } - if path == "" { - path = username - } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "username": username, - "password": password, - "path": path, - "port": formatDockerPort(p.PublicPort), - "query": map[string]bool{ - "is_master": true, - }, - "rel": "pgsql", - "scheme": "pgsql", - } - return rels - } else if p.PrivatePort == 6379 { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "redis", - "scheme": "redis", - } - return rels - } else if p.PrivatePort == 11211 { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "memcached", - "scheme": "memcached", - } - return rels - } else if p.PrivatePort == 5672 { - username := "guest" - password := "guest" + } + } else if p.PrivatePort == 8707 || p.PrivatePort == 8307 { + // Blackfire + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "blackfire", + "scheme": "tcp", + } + return rels + } else if p.PrivatePort == 3306 { + username := "" + password := "" + path := "" + // MARIADB is used by bitnami/mariadb + for _, prefix := range []string{"MYSQL", "MARIADB"} { for _, env := range c.Config.Env { - // that's our local convention - if strings.HasPrefix(env, "RABBITMQ_DEFAULT_USER") { - username = getEnvValue(env, "RABBITMQ_DEFAULT_USER") - } else if strings.HasPrefix(env, "RABBITMQ_DEFAULT_PASS") { - password = getEnvValue(env, "RABBITMQ_DEFAULT_PASS") - } - } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "username": username, - "password": password, - "rel": "amqp", - "scheme": "amqp", - } - // management plugin? - for _, pw := range exposedPorts { - if pw.PrivatePort == 15672 { - rels["-management"] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(pw.PublicPort), - "rel": "amqp", - "scheme": "http", - } - break + if strings.HasPrefix(env, prefix+"_ROOT_PASSWORD") && password == "" { + // *_PASSWORD has precedence over *_ROOT_PASSWORD + password = getEnvValue(env, prefix+"_ROOT_PASSWORD") + username = "root" + } else if strings.HasPrefix(env, prefix+"_USER") { + username = getEnvValue(env, prefix+"_USER") + } else if strings.HasPrefix(env, prefix+"_PASSWORD") { + password = getEnvValue(env, prefix+"_PASSWORD") + } else if strings.HasPrefix(env, prefix+"_DATABASE") { + path = getEnvValue(env, prefix+"_DATABASE") } } - return rels - } else if p.PrivatePort == 9200 { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "path": "/", - "rel": "elasticsearch", - "scheme": "http", + } + if path == "" { + path = username + } + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "username": username, + "password": password, + "path": path, + "port": formatDockerPort(p.PublicPort), + "query": map[string]bool{ + "is_master": true, + }, + "rel": "mysql", + "scheme": "mysql", + } + return rels + } else if p.PrivatePort == 5432 { + username := "" + password := "" + path := "" + for _, env := range c.Config.Env { + if strings.HasPrefix(env, "POSTGRES_USER") { + username = getEnvValue(env, "POSTGRES_USER") + } else if strings.HasPrefix(env, "POSTGRES_PASSWORD") { + password = getEnvValue(env, "POSTGRES_PASSWORD") + } else if strings.HasPrefix(env, "POSTGRES_DB") { + path = getEnvValue(env, "POSTGRES_DB") } - return rels - } else if p.PrivatePort == 5601 { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "path": "/", - "rel": "kibana", - "scheme": "http", + } + if path == "" { + path = username + } + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "username": username, + "password": password, + "path": path, + "port": formatDockerPort(p.PublicPort), + "query": map[string]bool{ + "is_master": true, + }, + "rel": "pgsql", + "scheme": "pgsql", + } + return rels + } else if p.PrivatePort == 6379 { + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "redis", + "scheme": "redis", + } + return rels + } else if p.PrivatePort == 11211 { + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "memcached", + "scheme": "memcached", + } + return rels + } else if p.PrivatePort == 5672 { + username := "guest" + password := "guest" + for _, env := range c.Config.Env { + // that's our local convention + if strings.HasPrefix(env, "RABBITMQ_DEFAULT_USER") { + username = getEnvValue(env, "RABBITMQ_DEFAULT_USER") + } else if strings.HasPrefix(env, "RABBITMQ_DEFAULT_PASS") { + password = getEnvValue(env, "RABBITMQ_DEFAULT_PASS") } - return rels - } else if p.PrivatePort == 27017 { - username := "" - password := "" - path := "" - for _, env := range c.Config.Env { - // that's our local convention - if strings.HasPrefix(env, "MONGO_DATABASE") { - path = getEnvValue(env, "MONGO_DATABASE") - } else if strings.HasPrefix(env, "MONGO_INITDB_DATABASE") { - path = getEnvValue(env, "MONGO_INITDB_DATABASE") - } else if strings.HasPrefix(env, "MONGO_INITDB_ROOT_USERNAME") { - username = getEnvValue(env, "MONGO_INITDB_ROOT_USERNAME") - } else if strings.HasPrefix(env, "MONGO_INITDB_ROOT_PASSWORD") { - password = getEnvValue(env, "MONGO_INITDB_ROOT_PASSWORD") + } + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "username": username, + "password": password, + "rel": "amqp", + "scheme": "amqp", + } + // management plugin? + for _, pw := range exposedPorts { + if pw.PrivatePort == 15672 { + rels["-management"] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(pw.PublicPort), + "rel": "amqp", + "scheme": "http", } + break } - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "username": username, - "password": password, - "path": path, - "port": formatDockerPort(p.PublicPort), - "rel": "mongodb", - "scheme": "mongodb", - } - return rels - } else if p.PrivatePort == 9092 { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "kafka", - "scheme": "kafka", - } - return rels - } else if p.PrivatePort == 80 && container.Image == "dunglas/mercure" { - rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "mercure", - "scheme": "http", + } + return rels + } else if p.PrivatePort == 9200 { + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "path": "/", + "rel": "elasticsearch", + "scheme": "http", + } + return rels + } else if p.PrivatePort == 5601 { + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "path": "/", + "rel": "kibana", + "scheme": "http", + } + return rels + } else if p.PrivatePort == 27017 { + username := "" + password := "" + path := "" + for _, env := range c.Config.Env { + // that's our local convention + if strings.HasPrefix(env, "MONGO_DATABASE") { + path = getEnvValue(env, "MONGO_DATABASE") + } else if strings.HasPrefix(env, "MONGO_INITDB_DATABASE") { + path = getEnvValue(env, "MONGO_INITDB_DATABASE") + } else if strings.HasPrefix(env, "MONGO_INITDB_ROOT_USERNAME") { + username = getEnvValue(env, "MONGO_INITDB_ROOT_USERNAME") + } else if strings.HasPrefix(env, "MONGO_INITDB_ROOT_PASSWORD") { + password = getEnvValue(env, "MONGO_INITDB_ROOT_PASSWORD") } - return rels } - - if l.Debug { - fmt.Fprintln(os.Stderr, " exposing port") + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "username": username, + "password": password, + "path": path, + "port": formatDockerPort(p.PublicPort), + "rel": "mongodb", + "scheme": "mongodb", } - + return rels + } else if p.PrivatePort == 9092 { rels[""] = map[string]interface{}{ - "host": host, - "ip": host, - "port": formatDockerPort(p.PublicPort), - "rel": "simple", + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "kafka", + "scheme": "kafka", } - // Official HTTP(s) ports or well know alternatives - if p.PrivatePort == 80 || p.PrivatePort == 8008 || p.PrivatePort == 8080 || p.PrivatePort == 8081 { - rels[""]["scheme"] = "http" - } else if p.PrivatePort == 443 || p.PrivatePort == 8443 { - rels[""]["scheme"] = "https" + return rels + } else if p.PrivatePort == 80 && container.Image == "dunglas/mercure" { + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "mercure", + "scheme": "http", } return rels } - return nil + if l.Debug { + fmt.Fprintln(os.Stderr, " exposing port") + } + + rels[""] = map[string]interface{}{ + "host": host, + "ip": host, + "port": formatDockerPort(p.PublicPort), + "rel": "simple", + } + // Official HTTP(s) ports or well know alternatives + if p.PrivatePort == 80 || p.PrivatePort == 8008 || p.PrivatePort == 8080 || p.PrivatePort == 8081 { + rels[""]["scheme"] = "http" + } else if p.PrivatePort == 443 || p.PrivatePort == 8443 { + rels[""]["scheme"] = "https" + } + return rels } func formatDockerPort(port uint16) string { @@ -487,7 +488,7 @@ func (l *Local) getComposeProjectName() string { // COMPOSE_PROJECT_NAME can be set in a .env file if _, err := os.Stat(filepath.Join(composeDir, ".env")); err == nil { - if contents, err := ioutil.ReadFile(filepath.Join(composeDir, ".env")); err == nil { + if contents, err := os.ReadFile(filepath.Join(composeDir, ".env")); err == nil { for _, line := range bytes.Split(contents, []byte("\n")) { if bytes.HasPrefix(line, []byte("COMPOSE_PROJECT_NAME=")) { return string(line[len("COMPOSE_PROJECT_NAME="):]) diff --git a/envs/envs.go b/envs/envs.go index 76e5f9c8..e32c134c 100644 --- a/envs/envs.go +++ b/envs/envs.go @@ -22,7 +22,6 @@ package envs import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -90,7 +89,7 @@ func AsMap(env Environment) map[string]string { // appID returns the Symfony project's ID from composer.json func appID(path string) string { - content, err := ioutil.ReadFile(filepath.Join(path, "composer.json")) + content, err := os.ReadFile(filepath.Join(path, "composer.json")) if err != nil { return "" } diff --git a/envs/local.go b/envs/local.go index ca2dfd3d..39174946 100644 --- a/envs/local.go +++ b/envs/local.go @@ -254,15 +254,14 @@ func (l *Local) webServer() Envs { host := fmt.Sprintf("127.0.0.1:%s", port) if proxyConf, err := proxy.Load(util.GetHomeDir()); err == nil { - for _, domain := range proxyConf.GetDomains(l.Dir) { - // we get the first one only - host = domain + domains := proxyConf.GetDomains(l.Dir) + if len(domains) > 0 { + host = domains[0] if pidFile.Scheme == "http" { port = "80" } else { port = "443" } - break } } diff --git a/envs/local_test.go b/envs/local_test.go index d3d635a3..dd942d04 100644 --- a/envs/local_test.go +++ b/envs/local_test.go @@ -43,9 +43,9 @@ func (s *LocalSuite) TestExtra(c *C) { func (s *LocalSuite) TestTunnelFilePath(c *C) { l := &Local{Dir: "testdata/project"} - os.Rename("testdata/project/git", "testdata/project/.git") + _ = os.Rename("testdata/project/git", "testdata/project/.git") defer func() { - os.Rename("testdata/project/.git", "testdata/project/git") + _ = os.Rename("testdata/project/.git", "testdata/project/git") }() project, err := platformsh.ProjectFromDir(l.Dir, false) if err != nil { @@ -56,8 +56,10 @@ func (s *LocalSuite) TestTunnelFilePath(c *C) { } func (s *LocalSuite) TestRelationships(c *C) { - os.Rename("testdata/project/git", "testdata/project/.git") - defer os.Rename("testdata/project/.git", "testdata/project/git") + _ = os.Rename("testdata/project/git", "testdata/project/.git") + defer func() { + _ = os.Rename("testdata/project/.git", "testdata/project/git") + }() homedir.Reset() os.Setenv("HOME", "testdata/project") defer homedir.Reset() diff --git a/envs/local_tunnel.go b/envs/local_tunnel.go index 452bb820..8d1cd7f3 100644 --- a/envs/local_tunnel.go +++ b/envs/local_tunnel.go @@ -23,7 +23,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -31,6 +30,7 @@ import ( "strconv" "github.com/mitchellh/go-homedir" + "github.com/pkg/errors" "github.com/symfony-cli/symfony-cli/local/platformsh" "github.com/symfony-cli/symfony-cli/util" ) @@ -58,7 +58,7 @@ func (l *Local) relationshipsFromTunnel() Relationships { userHomeDir = "" } tunnelFile := filepath.Join(userHomeDir, ".platformsh", "tunnel-info.json") - data, err := ioutil.ReadFile(tunnelFile) + data, err := os.ReadFile(tunnelFile) if err != nil { if l.Debug { fmt.Fprintf(os.Stderr, "WARNING: unable to read relationships from %s: %s\n", tunnelFile, err) @@ -98,7 +98,7 @@ func (l *Local) relationshipsFromTunnel() Relationships { return nil } -var pathCleaningRegex = regexp.MustCompile("[^a-zA-Z0-9-\\.]+") +var pathCleaningRegex = regexp.MustCompile(`[^a-zA-Z0-9-\.]+`) type Tunnel struct { Project *platformsh.Project @@ -117,13 +117,13 @@ func (t *Tunnel) Expose(expose bool) error { path := t.path() if expose { if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { - return err + return errors.WithStack(err) } file, err := os.Create(path) if err != nil { - return err + return errors.WithStack(err) } - return file.Close() + return errors.WithStack(file.Close()) } os.Remove(path) diff --git a/envs/url.go b/envs/url.go index 6bcdf419..b4f94762 100644 --- a/envs/url.go +++ b/envs/url.go @@ -37,7 +37,7 @@ func (s *URLSlice) UnmarshalJSON(b []byte) error { var keys []string if err := errors.WithStack(json.Unmarshal(b, &v)); err != nil { - return err + return errors.WithStack(err) } d := json.NewDecoder(bytes.NewReader(b)) @@ -59,7 +59,7 @@ func (s *URLSlice) UnmarshalJSON(b []byte) error { } keys = append(keys, t.(string)) if err := errors.WithStack(skipValue(d)); err != nil { - return err + return errors.WithStack(err) } } @@ -87,7 +87,7 @@ func skipValue(d *json.Decoder) error { if err == end { break } - return err + return errors.WithStack(err) } } case json.Delim(']'), json.Delim('}'): diff --git a/git/branches.go b/git/branches.go index 38846609..a7da5daa 100644 --- a/git/branches.go +++ b/git/branches.go @@ -21,6 +21,8 @@ package git import ( "strings" + + "github.com/pkg/errors" ) func GetCurrentBranch(cwd string) string { @@ -37,5 +39,5 @@ func GetCurrentBranch(cwd string) string { func ResetHard(cwd, reference string) error { _, err := execGitQuiet(cwd, "reset", "--hard", reference) - return err + return errors.WithStack(err) } diff --git a/git/exec.go b/git/exec.go index b04dde67..3ec35b6d 100644 --- a/git/exec.go +++ b/git/exec.go @@ -36,7 +36,7 @@ func execGitQuiet(cwd string, args ...string) (*bytes.Buffer, error) { func execGit(cwd string, args ...string) error { _, err := doExecGit(cwd, args, false) - return err + return errors.WithStack(err) } func doExecGit(cwd string, args []string, quiet bool) (*bytes.Buffer, error) { diff --git a/git/init.go b/git/init.go index ac312e38..76eaeb6d 100644 --- a/git/init.go +++ b/git/init.go @@ -19,11 +19,15 @@ package git -import "bytes" +import ( + "bytes" + + "github.com/pkg/errors" +) func Init(dir string, forceMainGitBranchName, debug bool) (*bytes.Buffer, error) { if content, err := doExecGit(dir, []string{"init"}, !debug); err != nil { - return content, err + return content, errors.WithStack(err) } if forceMainGitBranchName { return doExecGit(dir, []string{"checkout", "-b", "main"}, !debug) @@ -38,7 +42,7 @@ func AddAndCommit(dir string, files []string, msg string, debug bool) (*bytes.Bu } for _, cmd := range cmds { if content, err := doExecGit(dir, cmd, !debug); err != nil { - return content, err + return content, errors.WithStack(err) } } return nil, nil diff --git a/git/remote.go b/git/remote.go index d319034b..7edca7a2 100644 --- a/git/remote.go +++ b/git/remote.go @@ -36,7 +36,7 @@ func Fetch(cwd, remote, branch string) error { _, err := execGitQuiet(cwd, args...) - return err + return errors.WithStack(err) } func Clone(url, dir string) error { diff --git a/humanlog/handler.go b/humanlog/handler.go index f3511946..d446f91b 100644 --- a/humanlog/handler.go +++ b/humanlog/handler.go @@ -215,7 +215,7 @@ func unmarshal(data []byte) (*line, error) { raw := make(map[string]interface{}) err := errors.WithStack(json.Unmarshal(data, &raw)) if err != nil { - return nil, err + return nil, errors.WithStack(err) } line := &line{ fields: make(map[string]string), diff --git a/humanlog/symfony.go b/humanlog/symfony.go index 790ae425..53e79fcf 100644 --- a/humanlog/symfony.go +++ b/humanlog/symfony.go @@ -31,7 +31,7 @@ import ( // [2018-11-19 12:52:00] console.DEBUG: www {"xxx":"yyy","code":1} [] // or [2019-11-13T07:16:50.260544+01:00] console.DEBUG: www {"xxx":"yyy","code":1} [] -var symfonyLogLineRegexp = regexp.MustCompile("^\\[(\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}\\:\\d{2}\\:\\d{2}|\\d{4}\\-\\d{2}\\-\\d{2}T\\d{2}\\:\\d{2}\\:\\d{2}\\.\\d+\\+\\d{2}\\:\\d{2})\\] ([^\\.]+)\\.([^\\:]+)\\: (.+) (\\[.*?\\]|{.*?}) (\\[.*?\\]|{.*?})\\s*$") +var symfonyLogLineRegexp = regexp.MustCompile(`^\[(\d{4}\-\d{2}\-\d{2} \d{2}\:\d{2}\:\d{2}|\d{4}\-\d{2}\-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d+\+\d{2}\:\d{2})\] ([^\.]+)\.([^\:]+)\: (.+) (\[.*?\]|{.*?}) (\[.*?\]|{.*?})\s*$`) func convertSymfonyLog(in []byte) (*line, error) { allMatches := symfonyLogLineRegexp.FindAllSubmatch(in, -1) diff --git a/inotify/inotify.go b/inotify/inotify.go index 68394c3b..ed6fd0d1 100644 --- a/inotify/inotify.go +++ b/inotify/inotify.go @@ -19,7 +19,10 @@ package inotify -import "github.com/syncthing/notify" +import ( + "github.com/pkg/errors" + "github.com/syncthing/notify" +) // Create, Remove, Write and Rename are the only event values guaranteed to be // present on all platforms. @@ -40,5 +43,5 @@ func Stop(c chan<- EventInfo) { } func simpleWatch(path string, c chan<- EventInfo, events ...notify.Event) error { - return notify.Watch(path, c, events...) + return errors.Wrap(notify.Watch(path, c, events...), "Error on watch") } diff --git a/local/fcgi_client/fcgiclient.go b/local/fcgi_client/fcgiclient.go index d9bdc565..4027ed9b 100644 --- a/local/fcgi_client/fcgiclient.go +++ b/local/fcgi_client/fcgiclient.go @@ -10,7 +10,6 @@ import ( "bytes" "encoding/binary" "io" - "io/ioutil" "mime/multipart" "net" "net/http" @@ -256,7 +255,7 @@ func (w *bufWriter) Close() error { w.closer.Close() return errors.WithStack(err) } - return w.closer.Close() + return errors.WithStack(w.closer.Close()) } func newWriter(c *FCGIClient, recType uint8) *bufWriter { @@ -337,7 +336,7 @@ func (f *FCGIClient) Do(p map[string]string, req io.Reader) (r io.Reader, err er body := newWriter(f, FCGI_STDIN) if req != nil { - io.Copy(body, req) + _, _ = io.Copy(body, req) } body.Close() @@ -362,7 +361,7 @@ func (f *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res if err == io.EOF { err = io.ErrUnexpectedEOF } - return nil, err + return nil, errors.WithStack(err) } resp.Header = http.Header(mimeHeader) // TODO: fixTransferEncoding? @@ -372,13 +371,13 @@ func (f *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res // status err = errors.WithStack(extractStatus(resp)) if err != nil { - return nil, err + return nil, errors.WithStack(err) } if chunked(resp.TransferEncoding) { - resp.Body = ioutil.NopCloser(httputil.NewChunkedReader(rb)) + resp.Body = io.NopCloser(httputil.NewChunkedReader(rb)) } else { - resp.Body = ioutil.NopCloser(rb) + resp.Body = io.NopCloser(rb) } return } @@ -434,7 +433,7 @@ func (f *FCGIClient) PostFile(p map[string]string, data url.Values, file map[str for key, val := range file { fd, e := os.Open(val) if e != nil { - return nil, e + return nil, errors.WithStack(e) } defer fd.Close() diff --git a/local/http/http.go b/local/http/http.go index 2f1a419f..cddc7ce6 100644 --- a/local/http/http.go +++ b/local/http/http.go @@ -227,7 +227,7 @@ func (s *Server) Handler(w http.ResponseWriter, r *http.Request) { if s.Callback == nil { w.WriteHeader(http.StatusNotFound) - w.Write([]byte(html.WrapHTML("Page not found", html.CreateErrorTerminal("# Page not found"), ""))) + _, _ = w.Write([]byte(html.WrapHTML("Page not found", html.CreateErrorTerminal("# Page not found"), ""))) return } env := map[string]string{ @@ -244,7 +244,7 @@ func (s *Server) Handler(w http.ResponseWriter, r *http.Request) { if err := s.Callback(w, r, env); err != nil { s.Logger.Error().Err(err).Msg("issue with server callback") w.WriteHeader(http.StatusBadGateway) - w.Write([]byte(html.WrapHTML(err.Error(), html.CreateErrorTerminal("# "+err.Error()), ""))) + _, _ = w.Write([]byte(html.WrapHTML(err.Error(), html.CreateErrorTerminal("# "+err.Error()), ""))) return } } diff --git a/local/http/push.go b/local/http/push.go index b28d01e6..dfacb13c 100644 --- a/local/http/push.go +++ b/local/http/push.go @@ -63,7 +63,7 @@ func (s *Server) servePreloadLinks(w http.ResponseWriter, r *http.Request) ([]st Method: http.MethodGet, Header: headers, })); err != nil { - return nil, err + return nil, errors.WithStack(err) } rs = append(rs, resource.uri) } diff --git a/local/http/response_proxy.go b/local/http/response_proxy.go index 0058d87d..476fcee9 100644 --- a/local/http/response_proxy.go +++ b/local/http/response_proxy.go @@ -75,7 +75,8 @@ func (p *ResponseWriterProxy) WriteHeader(code int) { // from https://github.com/mholt/caddy/pull/134 func (p *ResponseWriterProxy) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hj, ok := p.writer.(http.Hijacker); ok { - return hj.Hijack() + c, rw, err := hj.Hijack() + return c, rw, errors.WithStack(err) } return nil, nil, errors.New("I'm not a Hijacker") } diff --git a/local/logs/tailer.go b/local/logs/tailer.go index 365a7a53..0e881c31 100644 --- a/local/logs/tailer.go +++ b/local/logs/tailer.go @@ -98,7 +98,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { if !tailer.NoWorkerLogs { workerDir := pidFile.WorkerPidDir() if err := os.MkdirAll(workerDir, 0755); err != nil { - return err + return errors.Wrap(err, "unable to create the directory "+workerDir) } watcherChan := make(chan inotify.EventInfo, 1) if err := inotify.Watch(workerDir, watcherChan, inotify.Create); err != nil { @@ -142,7 +142,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { dir := filepath.Dir(applog) if err := os.MkdirAll(dir, 0755); err != nil { - return err + return errors.Wrap(err, "unable to create the applog directory "+dir) } if err := inotify.Watch(dir, watcherChan, inotify.Create); err != nil { return errors.Wrap(err, "unable to watch the applog directory") @@ -219,7 +219,7 @@ func (tailer *Tailer) Tail(w io.Writer) error { buf.Write(humanizer.Prettify([]byte(content))) buf.Write([]byte("\n")) } - w.Write(buf.Bytes()) + _, _ = w.Write(buf.Bytes()) } } @@ -250,16 +250,19 @@ func tailFile(filename string, follow bool, nblines int64) (*tail.Tail, error) { pos, _ = fls.LineFile(f).SeekLine(-nblines, io.SeekEnd) } f.Close() - return tail.TailFile(filename, tail.Config{ + + tail, err := tail.TailFile(filename, tail.Config{ Location: &tail.SeekInfo{ Offset: pos, - Whence: os.SEEK_SET, + Whence: io.SeekStart, }, ReOpen: follow, Follow: follow, Poll: true, Logger: tail.DiscardingLogger, }) + + return tail, errors.WithStack(err) } // find the application log file(s) (only Symfony is supported for now) diff --git a/local/php/composer.go b/local/php/composer.go index 3d2566cf..10b57f7e 100644 --- a/local/php/composer.go +++ b/local/php/composer.go @@ -27,7 +27,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -123,7 +122,7 @@ func composerVersion() int { if err != nil { return DefaultComposerVersion } - contents, err := ioutil.ReadFile(filepath.Join(cwd, "composer.lock")) + contents, err := os.ReadFile(filepath.Join(cwd, "composer.lock")) if err != nil { return DefaultComposerVersion } @@ -158,7 +157,7 @@ func findComposer(extraBin string) (string, error) { func downloadComposer(dir string) (string, error) { if err := os.MkdirAll(dir, 0755); err != nil { - return "", err + return "", errors.WithStack(err) } path := filepath.Join(dir, "composer.phar") if _, err := os.Stat(path); err == nil { @@ -167,11 +166,11 @@ func downloadComposer(dir string) (string, error) { sig, err := downloadComposerInstallerSignature() if err != nil { - return "", err + return "", errors.WithStack(err) } installer, err := downloadComposerInstaller() if err != nil { - return "", err + return "", errors.WithStack(err) } h := sha512.New384() h.Write(installer) @@ -182,7 +181,7 @@ func downloadComposer(dir string) (string, error) { return "", errors.New("signature was wrong when downloading Composer; please try again") } setupPath := filepath.Join(dir, "composer-setup.php") - ioutil.WriteFile(setupPath, installer, 0666) + _ = os.WriteFile(setupPath, installer, 0666) var stdout bytes.Buffer e := &Executor{ @@ -198,10 +197,10 @@ func downloadComposer(dir string) (string, error) { return "", errors.New("unable to setup Composer") } if err := os.Chmod(path, 0755); err != nil { - return "", err + return "", errors.WithStack(err) } if err := os.Remove(filepath.Join(dir, "composer-setup.php")); err != nil { - return "", err + return "", errors.WithStack(err) } return path, nil @@ -210,17 +209,19 @@ func downloadComposer(dir string) (string, error) { func downloadComposerInstaller() ([]byte, error) { resp, err := http.Get("https://getcomposer.org/installer") if err != nil { - return nil, err + return nil, errors.WithStack(err) } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) + return b, errors.WithStack(err) } func downloadComposerInstallerSignature() ([]byte, error) { resp, err := http.Get("https://composer.github.io/installer.sig") if err != nil { - return nil, err + return nil, errors.WithStack(err) } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) + return b, errors.WithStack(err) } diff --git a/local/php/executor.go b/local/php/executor.go index 28fc58f6..3cb7a605 100644 --- a/local/php/executor.go +++ b/local/php/executor.go @@ -80,7 +80,7 @@ func (e *Executor) lookupPHP(cliDir string, forceReload bool) (*phpstore.Version terminal.Eprintfln("WARNING %s", warning) } if err != nil { - return nil, "", true, err + return nil, "", true, errors.WithStack(err) } e.Logger.Debug().Str("source", "PHP").Msgf("Using PHP version %s (from %s)", v.Version, source) path := v.PHPPath @@ -173,7 +173,7 @@ func (e *Executor) Config(loadDotEnv bool) error { } if _, err := e.DetectScriptDir(); err != nil { - return err + return errors.WithStack(err) } vars := make(map[string]string) @@ -210,7 +210,7 @@ func (e *Executor) Config(loadDotEnv bool) error { if v, path, phpiniArgs, err = e.lookupPHP(cliDir, false); err != nil { // try again after reloading PHP versions if v, path, phpiniArgs, err = e.lookupPHP(cliDir, true); err != nil { - return err + return errors.WithStack(err) } } e.environ = append(e.environ, fmt.Sprintf("PHP_BINARY=%s", v.PHPPath)) @@ -223,40 +223,40 @@ func (e *Executor) Config(loadDotEnv bool) error { phpDir := filepath.Join(cliDir, "tmp", xid.New().String(), "bin") e.tempDir = phpDir if err := os.MkdirAll(phpDir, 0755); err != nil { - return err + return errors.WithStack(err) } // always symlink (copy on Windows) these binaries as they can be called internally (like pecl for instance) if v.PHPConfigPath != "" { if err := symlink(v.PHPConfigPath, filepath.Join(phpDir, "php-config")); err != nil { - return err + return errors.WithStack(err) } // we also alias a version with the prefix/suffix as required by pecl if filepath.Base(v.PHPConfigPath) != "php-config" { if err := symlink(v.PHPConfigPath, filepath.Join(phpDir, filepath.Base(v.PHPConfigPath))); err != nil { - return err + return errors.WithStack(err) } } } if v.PHPizePath != "" { if err := symlink(v.PHPizePath, filepath.Join(phpDir, "phpize")); err != nil { - return err + return errors.WithStack(err) } // we also alias a version with the prefix/suffix as required by pecl if filepath.Base(v.PHPizePath) != "phpize" { if err := symlink(v.PHPizePath, filepath.Join(phpDir, filepath.Base(v.PHPizePath))); err != nil { - return err + return errors.WithStack(err) } } } if v.PHPdbgPath != "" { if err := symlink(v.PHPdbgPath, filepath.Join(phpDir, "phpdbg")); err != nil { - return err + return errors.WithStack(err) } } // if the bin is not one of the previous created symlink, create the symlink now if _, err := os.Stat(filepath.Join(phpDir, e.BinName)); os.IsNotExist(err) { if err := symlink(path, filepath.Join(phpDir, e.BinName)); err != nil { - return err + return errors.WithStack(err) } } e.Paths = append([]string{filepath.Dir(path), phpDir}, e.Paths...) @@ -281,7 +281,7 @@ func (e *Executor) Config(loadDotEnv bool) error { // but as we change the path, we should update args[0] accordingly e.Args[0] = path - return err + return errors.WithStack(err) } // Find composer depending on the configuration @@ -357,7 +357,7 @@ func (e *Executor) Execute(loadDotEnv bool) int { close(waitCh) }() - sigChan := make(chan os.Signal) + sigChan := make(chan os.Signal, 1) signal.Notify(sigChan) defer signal.Stop(sigChan) @@ -394,7 +394,8 @@ func (e *Executor) Execute(loadDotEnv bool) int { func LookPath(file string) (string, error) { if util.InCloud() { // does not make sense to look for the php store, fall back - return exec.LookPath(file) + p, err := exec.LookPath(file) + return p, errors.WithStack(err) } phpStore := phpstore.New(util.GetHomeDir(), false, nil) wd, _ := os.Getwd() @@ -404,21 +405,24 @@ func LookPath(file string) (string, error) { } if v == nil { // unable to find the current PHP version, fall back - return exec.LookPath(file) + p, err := exec.LookPath(file) + return p, errors.WithStack(err) } path := filepath.Join(filepath.Dir(v.PHPPath), file) d, err := os.Stat(path) if err != nil { // file does not exist, fall back - return exec.LookPath(file) + p, err := exec.LookPath(file) + return p, errors.WithStack(err) } if m := d.Mode(); !m.IsDir() && m&0111 != 0 { // Yep! return path, nil } // found, but not executable, fall back - return exec.LookPath(file) + p, err := exec.LookPath(file) + return p, errors.WithStack(err) } // detectScriptDir tries to get the script directory from args diff --git a/local/php/executor_posix.go b/local/php/executor_posix.go index 9a28b8d7..10f72540 100644 --- a/local/php/executor_posix.go +++ b/local/php/executor_posix.go @@ -25,6 +25,8 @@ package php import ( "os" "syscall" + + "github.com/pkg/errors" ) func shouldSignalBeIgnored(sig os.Signal) bool { @@ -34,5 +36,5 @@ func shouldSignalBeIgnored(sig os.Signal) bool { } func symlink(oldname, newname string) error { - return os.Symlink(oldname, newname) + return errors.WithStack(os.Symlink(oldname, newname)) } diff --git a/local/php/executor_test.go b/local/php/executor_test.go index 52216ce7..19bbcbf5 100644 --- a/local/php/executor_test.go +++ b/local/php/executor_test.go @@ -23,7 +23,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -55,13 +54,13 @@ func testStdoutCapture(c *C, dst io.Writer) func() { go func() { defer close(doneCh) defer r.Close() - io.Copy(dst, r) + _, _ = io.Copy(dst, r) }() return func() { // Close the writer end of the pipe - w.Sync() - w.Close() + _ = w.Sync() + _ = w.Close() // Reset stdout os.Stdout = old @@ -125,8 +124,10 @@ func (s *ExecutorSuite) TestForwardExitCode(c *C) { defer homedir.Reset() oldwd, _ := os.Getwd() - defer os.Chdir(oldwd) - os.Chdir(filepath.Join(home, "project")) + defer func(path string) { + _ = os.Chdir(path) + }(oldwd) + _ = os.Chdir(filepath.Join(home, "project")) defer cleanupExecutorTempFiles() c.Assert((&Executor{BinName: "php", Args: []string{"php"}}).Execute(true), Equals, 5) @@ -144,11 +145,15 @@ func (s *ExecutorSuite) TestEnvInjection(c *C) { defer homedir.Reset() oldwd, _ := os.Getwd() - defer os.Chdir(oldwd) - os.Chdir(filepath.Join(home, "project")) - - os.Rename("git", ".git") - defer os.Rename(".git", "git") + defer func(path string) { + _ = os.Chdir(path) + }(oldwd) + _ = os.Chdir(filepath.Join(home, "project")) + + _ = os.Rename("git", ".git") + defer func() { + _ = os.Rename(".git", "git") + }() defer cleanupExecutorTempFiles() var output bytes.Buffer @@ -165,10 +170,12 @@ func (s *ExecutorSuite) TestEnvInjection(c *C) { // change the project name to get exposed env vars projectFile := filepath.Join(".platform", "local", "project.yaml") - contents, err := ioutil.ReadFile(projectFile) + contents, err := os.ReadFile(projectFile) c.Assert(err, IsNil) - defer ioutil.WriteFile(projectFile, contents, 0644) - ioutil.WriteFile(projectFile, bytes.Replace(contents, []byte("bew7pfa7t2ut2"), []byte("aew7pfa7t2ut2"), 1), 0644) + defer func(pf string, c []byte) { + _ = os.WriteFile(pf, c, 0644) + }(projectFile, contents) + _ = os.WriteFile(projectFile, bytes.Replace(contents, []byte("bew7pfa7t2ut2"), []byte("aew7pfa7t2ut2"), 1), 0644) output.Reset() outCloser = testStdoutCapture(c, &output) diff --git a/local/php/executor_windows.go b/local/php/executor_windows.go index f5145733..5694b83b 100644 --- a/local/php/executor_windows.go +++ b/local/php/executor_windows.go @@ -22,6 +22,8 @@ package php import ( "io" "os" + + "github.com/pkg/errors" ) func shouldSignalBeIgnored(sig os.Signal) bool { @@ -31,14 +33,14 @@ func shouldSignalBeIgnored(sig os.Signal) bool { func symlink(oldname, newname string) error { source, err := os.Open(oldname) if err != nil { - return err + return errors.WithStack(err) } defer source.Close() destination, err := os.Create(newname) if err != nil { - return err + return errors.WithStack(err) } defer destination.Close() _, err = io.Copy(destination, source) - return err + return errors.WithStack(err) } diff --git a/local/php/php_server.go b/local/php/php_server.go index 676e88a0..235c98e5 100644 --- a/local/php/php_server.go +++ b/local/php/php_server.go @@ -24,7 +24,6 @@ import ( "crypto/sha1" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -71,7 +70,7 @@ func NewServer(homeDir, projectDir, documentRoot, passthru string, logger zerolo logger.Warn().Str("source", "PHP").Msg(warning) } if err != nil { - return nil, err + return nil, errors.WithStack(err) } logger.Debug().Str("source", "PHP").Msgf("Using PHP version %s (from %s)", version.Version, source) return &Server{ @@ -90,7 +89,7 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, port, err := process.FindAvailablePort() if err != nil { p.logger.Debug().Err(err).Msg("unable to find an available port") - return nil, nil, err + return nil, nil, errors.WithStack(err) } p.addr = net.JoinHostPort("", strconv.Itoa(port)) workingDir := p.documentRoot @@ -99,7 +98,7 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, var args []string if p.Version.IsFPMServer() { fpmConfigFile := p.fpmConfigFile() - if err := ioutil.WriteFile(fpmConfigFile, []byte(p.defaultFPMConf()), 0644); err != nil { + if err := os.WriteFile(fpmConfigFile, []byte(p.defaultFPMConf()), 0644); err != nil { return nil, nil, errors.WithStack(err) } pathsToRemove = append(pathsToRemove, fpmConfigFile) @@ -124,7 +123,7 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, args = []string{p.Version.ServerPath(), "-b", strconv.Itoa(port), "-d", "error_log=" + errorLog} } else { routerPath := p.phpRouterFile() - if err := ioutil.WriteFile(routerPath, phprouter, 0644); err != nil { + if err := os.WriteFile(routerPath, phprouter, 0644); err != nil { return nil, nil, errors.WithStack(err) } pathsToRemove = append(pathsToRemove, routerPath) @@ -140,7 +139,7 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, p.proxy = httputil.NewSingleHostReverseProxy(target) p.proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { w.WriteHeader(http.StatusBadGateway) - w.Write([]byte(html.WrapHTML(err.Error(), html.CreateErrorTerminal("# "+err.Error()), ""))) + _, _ = w.Write([]byte(html.WrapHTML(err.Error(), html.CreateErrorTerminal("# "+err.Error()), ""))) } } @@ -162,14 +161,14 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, phpPidFile.Watched = e.PathsToWatch() runner, err := local.NewRunner(phpPidFile, local.RunnerModeLoopAttached) if err != nil { - return phpPidFile, nil, err + return phpPidFile, nil, errors.WithStack(err) } runner.AlwaysRestartOnExit = true runner.BuildCmdHook = func(cmd *exec.Cmd) error { cmd.Dir = workingDir if err = e.Config(false); err != nil { - return err + return errors.WithStack(err) } cmd.Env = append(cmd.Env, e.environ...) @@ -205,9 +204,9 @@ func (p *Server) Serve(w http.ResponseWriter, r *http.Request, env map[string]st for k, v := range env { envContent += fmt.Sprintf("$_ENV['%s'] = '%s';\n", addslashes.Replace(k), addslashes.Replace(v)) } - err := errors.WithStack(ioutil.WriteFile(envPath, []byte(envContent), 0644)) + err := errors.WithStack(os.WriteFile(envPath, []byte(envContent), 0644)) if err != nil { - return err + return errors.WithStack(err) } defer os.Remove(envPath) pw := httptest.NewRecorder() @@ -261,7 +260,7 @@ func (p *Server) writeResponse(w http.ResponseWriter, r *http.Request, env map[s if r.Method == http.MethodGet && r.Header.Get("x-requested-with") == "XMLHttpRequest" { var err error if resp.Body, err = p.tweakToolbar(resp.Body, env); err != nil { - return err + return errors.WithStack(err) } bodyModified = true } @@ -280,13 +279,13 @@ func (p *Server) writeResponse(w http.ResponseWriter, r *http.Request, env map[s } w.WriteHeader(resp.StatusCode) if r.Method != http.MethodHead { - io.Copy(w, resp.Body) + _, _ = io.Copy(w, resp.Body) } return nil } func name(dir string) string { h := sha1.New() - io.WriteString(h, dir) + _, _ = io.WriteString(h, dir) return fmt.Sprintf("%x", h.Sum(nil)) } diff --git a/local/php/platformsh.go b/local/php/platformsh.go index 689e9f52..bad0e892 100644 --- a/local/php/platformsh.go +++ b/local/php/platformsh.go @@ -2,7 +2,7 @@ package php import ( "bytes" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -18,14 +18,14 @@ func InstallPlatformPhar(home string) error { cacheDir := filepath.Join(os.TempDir(), ".symfony", "platformsh", "cache") if _, err := os.Stat(cacheDir); err != nil { if err := os.MkdirAll(cacheDir, 0755); err != nil { - return err + return errors.WithStack(err) } } var versionPath = filepath.Join(cacheDir, "internal_version") dir := filepath.Join(home, ".platformsh", "bin") if _, err := os.Stat(filepath.Join(dir, "platform")); err == nil { // check "API version" (we never upgrade automatically the psh CLI except if we need to if our code would not be compatible with old versions) - if v, err := ioutil.ReadFile(versionPath); err == nil && bytes.Equal(v, internalVersion) { + if v, err := os.ReadFile(versionPath); err == nil && bytes.Equal(v, internalVersion) { return nil } } @@ -36,16 +36,16 @@ func InstallPlatformPhar(home string) error { defer spinner.Stop() resp, err := http.Get("https://platform.sh/cli/installer") if err != nil { - return err + return errors.WithStack(err) } defer resp.Body.Close() - installer, err := ioutil.ReadAll(resp.Body) + installer, err := io.ReadAll(resp.Body) if err != nil { - return err + return errors.WithStack(err) } installerPath := filepath.Join(home, "platformsh-installer.php") - ioutil.WriteFile(installerPath, installer, 0666) + _ = os.WriteFile(installerPath, installer, 0666) defer os.Remove(installerPath) var stdout bytes.Buffer @@ -62,5 +62,5 @@ func InstallPlatformPhar(home string) error { return errors.Errorf("unable to setup platformsh CLI: %s", stdout.String()) } - return ioutil.WriteFile(versionPath, internalVersion, 0644) + return errors.WithStack(os.WriteFile(versionPath, internalVersion, 0644)) } diff --git a/local/php/toolbar.go b/local/php/toolbar.go index 9dca0dfc..24843160 100644 --- a/local/php/toolbar.go +++ b/local/php/toolbar.go @@ -22,14 +22,14 @@ package php import ( "bytes" "fmt" + "io" + "regexp" + "github.com/pkg/errors" "github.com/symfony-cli/symfony-cli/envs" "github.com/symfony-cli/terminal" "golang.org/x/text/cases" "golang.org/x/text/language" - "io" - "io/ioutil" - "regexp" ) func (p *Server) tweakToolbar(body io.ReadCloser, env map[string]string) (io.ReadCloser, error) { @@ -38,13 +38,13 @@ func (p *Server) tweakToolbar(body io.ReadCloser, env map[string]string) (io.Rea n, err := body.Read(bn) // if body is empty, return immediately if n == 0 && err == io.EOF { - return ioutil.NopCloser(bytes.NewReader([]byte{})), nil + return io.NopCloser(bytes.NewReader([]byte{})), nil } if n == len(bn) && err != nil { return nil, errors.WithStack(err) } if bn[0] != '\n' && bn[0] != '<' { - return ioutil.NopCloser(io.MultiReader(bytes.NewReader(bn), body)), nil + return io.NopCloser(io.MultiReader(bytes.NewReader(bn), body)), nil } toolbarHint := []byte("") @@ -57,7 +57,7 @@ func (p *Server) tweakToolbar(body io.ReadCloser, env map[string]string) (io.Rea return nil, errors.WithStack(err) } if n != len(toolbarHint) || !bytes.Equal(start, toolbarHint) { - return ioutil.NopCloser(io.MultiReader(bytes.NewReader(bn), bytes.NewReader(start), body)), nil + return io.NopCloser(io.MultiReader(bytes.NewReader(bn), bytes.NewReader(start), body)), nil } logoBg := "sf-toolbar-status-normal" @@ -111,7 +111,7 @@ func (p *Server) tweakToolbar(body io.ReadCloser, env map[string]string) (io.Rea } } - b, err := ioutil.ReadAll(body) + b, err := io.ReadAll(body) if err != nil { return body, errors.WithStack(err) } @@ -152,5 +152,5 @@ $1`) re := regexp.MustCompile(`(<(?:a|button)[^"]+?class="hide-button")`) b = re.ReplaceAll(b, content) - return ioutil.NopCloser(io.MultiReader(bytes.NewReader(bn), bytes.NewReader(start), bytes.NewReader(b))), nil + return io.NopCloser(io.MultiReader(bytes.NewReader(bn), bytes.NewReader(start), bytes.NewReader(b))), nil } diff --git a/local/pid/pidfile.go b/local/pid/pidfile.go index 9f3758ee..dead3b11 100644 --- a/local/pid/pidfile.go +++ b/local/pid/pidfile.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -72,13 +71,13 @@ func New(dir string, args []string) *PidFile { } func Load(path string) (*PidFile, error) { - contents, err := ioutil.ReadFile(path) + contents, err := os.ReadFile(path) if err != nil { - return nil, err + return nil, errors.WithStack(err) } var p *PidFile if err := json.Unmarshal(contents, &p); err != nil { - return nil, err + return nil, errors.WithStack(err) } p.path = path return p, nil @@ -151,7 +150,7 @@ func (p *PidFile) WaitForLogs() error { defer inotify.Stop(watcherChan) logFile := p.LogFile() if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil { - return err + return errors.WithStack(err) } if err := inotify.Watch(filepath.Dir(logFile), watcherChan, inotify.Create); err != nil { return errors.Wrap(err, "unable to watch log file") @@ -192,11 +191,11 @@ func (p *PidFile) WorkerPidDir() string { func (p *PidFile) LogReader() (io.ReadCloser, error) { logFile := p.LogFile() if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil { - return nil, err + return nil, errors.WithStack(err) } r, err := os.OpenFile(logFile, os.O_RDONLY|os.O_CREATE, 0666) if err != nil { - return nil, err + return nil, errors.WithStack(err) } return r, nil } @@ -204,11 +203,11 @@ func (p *PidFile) LogReader() (io.ReadCloser, error) { func (p *PidFile) LogWriter() (io.WriteCloser, error) { logFile := p.LogFile() if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil { - return nil, err + return nil, errors.WithStack(err) } w, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { - return nil, err + return nil, errors.WithStack(err) } return w, nil } @@ -247,15 +246,15 @@ func (p *PidFile) Write(pid, port int, scheme string) error { p.Scheme = scheme if err := os.MkdirAll(filepath.Dir(p.path), 0755); err != nil && !os.IsExist(err) { - return err + return errors.WithStack(err) } b, err := json.MarshalIndent(p, "", " ") if err != nil { - return err + return errors.WithStack(err) } - return ioutil.WriteFile(p.path, b, 0644) + return errors.WithStack(os.WriteFile(p.path, b, 0644)) } // Stop kills the current process @@ -263,7 +262,9 @@ func (p *PidFile) Stop() error { if p.Pid == 0 { return nil } - defer p.Remove() + defer func(process *PidFile) { + _ = process.Remove() + }(p) return kill(p.Pid) } @@ -315,13 +316,13 @@ func (p *PidFile) Name() string { func name(dir string) string { h := sha1.New() - io.WriteString(h, dir) + _, _ = io.WriteString(h, dir) return fmt.Sprintf("%x", h.Sum(nil)) } func doAll(dir string) []*PidFile { pidFiles := []*PidFile{} - filepath.Walk(dir, func(p string, f os.FileInfo, err error) error { + _ = filepath.Walk(dir, func(p string, f os.FileInfo, err error) error { if err != nil { // prevent panic by handling failure accessing a path return nil @@ -333,7 +334,7 @@ func doAll(dir string) []*PidFile { if !strings.HasSuffix(p, ".pid") { return nil } - contents, err := ioutil.ReadFile(p) + contents, err := os.ReadFile(p) if err != nil { return nil } @@ -346,7 +347,7 @@ func doAll(dir string) []*PidFile { } pidFile.path = p if !pidFile.IsRunning() { - pidFile.Remove() + _ = pidFile.Remove() return nil } pidFiles = append(pidFiles, pidFile) diff --git a/local/pid/pidfile_other.go b/local/pid/pidfile_other.go index 01b73db0..6150f309 100644 --- a/local/pid/pidfile_other.go +++ b/local/pid/pidfile_other.go @@ -22,12 +22,16 @@ package pid -import "syscall" +import ( + "syscall" + + "github.com/pkg/errors" +) func kill(pid int) error { pgid, err := syscall.Getpgid(pid) if err != nil { - return err + return errors.WithStack(err) } - return syscall.Kill(-pgid, syscall.SIGTERM) + return errors.WithStack(syscall.Kill(-pgid, syscall.SIGTERM)) } diff --git a/local/platformsh/applications.go b/local/platformsh/applications.go index 21a61ada..9a39db2c 100644 --- a/local/platformsh/applications.go +++ b/local/platformsh/applications.go @@ -20,7 +20,6 @@ package platformsh import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -95,7 +94,7 @@ func FindLocalApplications(rootDirectory string) LocalApplications { go func() { for file := range appParser { - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) if err != nil { terminal.Logger.Warn().Msgf("Could not read %s file: %s\n", file, err) continue diff --git a/local/platformsh/generator/commands.go b/local/platformsh/generator/commands.go index 4c5e6602..2e036413 100644 --- a/local/platformsh/generator/commands.go +++ b/local/platformsh/generator/commands.go @@ -5,7 +5,6 @@ import ( "crypto/md5" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -106,7 +105,7 @@ func generateCommands() { if err != nil { panic(err) } - f.Write(buf.Bytes()) + _, _ = f.Write(buf.Bytes()) } @@ -114,7 +113,7 @@ func parseCommands(home string) (string, error) { dir := filepath.Join(home, ".platformsh", "bin") var pharPath = filepath.Join(dir, "platform") hasher := md5.New() - if s, err := ioutil.ReadFile(pharPath); err != nil { + if s, err := os.ReadFile(pharPath); err != nil { hasher.Write(s) } @@ -135,7 +134,7 @@ func parseCommands(home string) (string, error) { var definition application if err := json.Unmarshal(cleanOutput, &definition); err != nil { - return "", err + return "", errors.WithStack(err) } allCommandNames := map[string]bool{} diff --git a/local/platformsh/generator/config.go b/local/platformsh/generator/config.go index a868cd50..c0164dfa 100644 --- a/local/platformsh/generator/config.go +++ b/local/platformsh/generator/config.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "sort" @@ -12,6 +12,7 @@ import ( "text/template" "github.com/hashicorp/go-version" + "github.com/pkg/errors" "gopkg.in/yaml.v2" ) @@ -82,22 +83,22 @@ func generateConfig() { if err != nil { panic(err) } - f.Write(buf.Bytes()) + _, _ = f.Write(buf.Bytes()) } func parseServices() (string, error) { resp, err := http.Get("https://raw.githubusercontent.com/platformsh/platformsh-docs/master/docs/data/registry.json") if err != nil { - return "", err + return "", errors.WithStack(err) } defer resp.Body.Close() var services map[string]*service - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { - return "", err + return "", errors.WithStack(err) } if err := json.Unmarshal(body, &services); err != nil { - return "", err + return "", errors.WithStack(err) } serviceNames := []string{} for name := range services { @@ -110,11 +111,11 @@ func parseServices() (string, error) { if !s.Runtime { deprecatedVersions, err := sortVersions(s.Versions.Deprecated) if err != nil { - return "", err + return "", errors.WithStack(err) } supportedVersions, err := sortVersions(s.Versions.Supported) if err != nil { - return "", err + return "", errors.WithStack(err) } servicesAsString += "\t{\n" @@ -140,16 +141,16 @@ func parseServices() (string, error) { func parsePHPExtensions() (string, error) { resp, err := http.Get("https://raw.githubusercontent.com/platformsh/platformsh-docs/master/docs/data/php_extensions.yaml") if err != nil { - return "", err + return "", errors.WithStack(err) } defer resp.Body.Close() var versions []string orderedExtensionNames := []string{} extensions := make(map[string][]string) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { - return "", err + return "", errors.WithStack(err) } var fullConfig struct { Grid map[string]struct { @@ -158,7 +159,7 @@ func parsePHPExtensions() (string, error) { } } if err := yaml.Unmarshal(body, &fullConfig); err != nil { - return "", err + return "", errors.WithStack(err) } for version, cfg := range fullConfig.Grid { for _, ext := range append(cfg.Available, cfg.Default...) { @@ -195,31 +196,12 @@ func parsePHPExtensions() (string, error) { return extsAsString, nil } -func parseLine(line string) (string, []string) { - next := strings.Index(line[1:], "|") + 1 - name := strings.TrimSpace(line[1:next]) - var versions []string - for { - current := next + 1 - nextIndex := strings.Index(line[current:], "|") - if nextIndex == -1 { - break - } - next = nextIndex + current - versions = append(versions, strings.TrimSpace(line[current:next])) - if next >= len(line) { - break - } - } - return name, versions -} - func sortVersions(versions []string) ([]string, error) { parsedVersions := make([]*version.Version, len(versions)) for i, raw := range versions { v, err := version.NewVersion(raw) if err != nil { - return nil, err + return nil, errors.WithStack(err) } parsedVersions[i] = v } diff --git a/local/platformsh/project.go b/local/platformsh/project.go index f96abe7c..9e655bc6 100644 --- a/local/platformsh/project.go +++ b/local/platformsh/project.go @@ -22,7 +22,6 @@ package platformsh import ( goerr "errors" "fmt" - "io/ioutil" "os" "path/filepath" @@ -113,7 +112,7 @@ func guessProjectRoot(currentDir string, debug bool) (string, string) { } func getProjectConfig(projectRoot string, debug bool) string { - contents, err := ioutil.ReadFile(filepath.Join(projectRoot, ".platform", "local", "project.yaml")) + contents, err := os.ReadFile(filepath.Join(projectRoot, ".platform", "local", "project.yaml")) if err != nil { if debug { fmt.Fprintf(os.Stderr, "WARNING: unable to find Platform.sh config file: %s\n", err) diff --git a/local/process/port.go b/local/process/port.go index 6e932e56..d61aab1e 100644 --- a/local/process/port.go +++ b/local/process/port.go @@ -21,17 +21,19 @@ package process import ( "net" + + "github.com/pkg/errors" ) // FindAvailablePort finds an available port func FindAvailablePort() (int, error) { addr, err := net.ResolveTCPAddr("tcp", "localhost:0") if err != nil { - return 0, err + return 0, errors.WithStack(err) } l, err := net.ListenTCP("tcp", addr) if err != nil { - return 0, err + return 0, errors.WithStack(err) } defer l.Close() return l.Addr().(*net.TCPAddr).Port, nil diff --git a/local/process/process.go b/local/process/process.go index 6f1faac3..5bc1ee20 100644 --- a/local/process/process.go +++ b/local/process/process.go @@ -80,7 +80,7 @@ func (p *Process) Run(ctx context.Context) (*exec.Cmd, error) { go func() { p.Logger.Debug().Msg("started") <-ctx.Done() - kill(cmd) + _ = kill(cmd) p.Logger.Debug().Msg("stopped") }() return cmd, nil diff --git a/local/process/process_other.go b/local/process/process_other.go index 953ef82e..d1568b33 100644 --- a/local/process/process_other.go +++ b/local/process/process_other.go @@ -25,6 +25,8 @@ package process import ( "os/exec" "syscall" + + "github.com/pkg/errors" ) func deathsig(sysProcAttr *syscall.SysProcAttr) { @@ -34,5 +36,5 @@ func deathsig(sysProcAttr *syscall.SysProcAttr) { } func kill(cmd *exec.Cmd) error { - return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + return errors.WithStack(syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)) } diff --git a/local/project/config.go b/local/project/config.go index b1ef0825..26a4ac94 100644 --- a/local/project/config.go +++ b/local/project/config.go @@ -20,7 +20,6 @@ package project import ( - "io/ioutil" "os" "path/filepath" @@ -67,7 +66,7 @@ func NewConfigFromContext(c *console.Context, projectDir string) (*Config, *File var err error fileConfig, err = newConfigFromFile(filepath.Join(projectDir, ".symfony.local.yaml")) if err != nil { - return nil, nil, err + return nil, nil, errors.WithStack(err) } if fileConfig != nil { if fileConfig.HTTP == nil { @@ -121,18 +120,18 @@ func newConfigFromFile(configFile string) (*FileConfig, error) { return nil, nil } - contents, err := ioutil.ReadFile(configFile) + contents, err := os.ReadFile(configFile) if err != nil { - return nil, err + return nil, errors.WithStack(err) } var fileConfig FileConfig if err := yaml.Unmarshal(contents, &fileConfig); err != nil { - return nil, err + return nil, errors.WithStack(err) } if err := fileConfig.parseWorkers(); err != nil { - return nil, err + return nil, errors.WithStack(err) } return &fileConfig, nil diff --git a/local/project/project.go b/local/project/project.go index 0813ec6c..7af6d6e4 100644 --- a/local/project/project.go +++ b/local/project/project.go @@ -21,7 +21,6 @@ package project import ( "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -79,7 +78,7 @@ func New(c *Config) (*Project, error) { } else { p.PHPServer, err = php.NewServer(c.HomeDir, c.ProjectDir, documentRoot, passthru, c.Logger) if err != nil { - return nil, err + return nil, errors.WithStack(err) } p.HTTP.Callback = p.PHPServer.Serve } @@ -112,7 +111,7 @@ func realPassthru(documentRoot, passthru string) (string, error) { func guessDocumentRoot(path string) string { // for Symfony: check if public-dir is set up in composer.json first - if b, err := ioutil.ReadFile(filepath.Join(path, "composer.json")); err == nil { + if b, err := os.ReadFile(filepath.Join(path, "composer.json")); err == nil { var f map[string]interface{} if err := json.Unmarshal(b, &f); err == nil { if f1, ok := f["extra"]; ok { diff --git a/local/proxy/cert_store.go b/local/proxy/cert_store.go index 365bcd7d..972774c6 100644 --- a/local/proxy/cert_store.go +++ b/local/proxy/cert_store.go @@ -24,6 +24,7 @@ import ( "sync" lru "github.com/hashicorp/golang-lru/v2" + "github.com/pkg/errors" "github.com/symfony-cli/cert" ) @@ -55,7 +56,7 @@ func (c *certStore) getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certi } cert, err := c.ca.CreateCert([]string{name}) if err != nil { - return nil, err + return nil, errors.WithStack(err) } c.cache.Add(name, cert) return &cert, nil diff --git a/local/proxy/config.go b/local/proxy/config.go index 04c3831b..8e39ab4a 100644 --- a/local/proxy/config.go +++ b/local/proxy/config.go @@ -22,7 +22,6 @@ package proxy import ( "encoding/json" "fmt" - "io/ioutil" "log" "net/http" "os" @@ -66,11 +65,11 @@ func Load(homeDir string) (*Config, error) { if err := os.MkdirAll(filepath.Dir(proxyFile), 0755); err != nil { return nil, errors.Wrapf(err, "unable to create directory for %s", proxyFile) } - if err := ioutil.WriteFile(proxyFile, DefaultConfig, 0644); err != nil { + if err := os.WriteFile(proxyFile, DefaultConfig, 0644); err != nil { return nil, errors.Wrapf(err, "unable to write %s", proxyFile) } } - data, err := ioutil.ReadFile(proxyFile) + data, err := os.ReadFile(proxyFile) if err != nil { return nil, errors.Wrapf(err, "unable to read the proxy configuration file, %s", proxyFile) } @@ -102,7 +101,7 @@ func ToConfiguredProjects() (map[string]*projects.ConfiguredProject, error) { homeDir := util.GetHomeDir() proxyConf, err := Load(homeDir) if err != nil { - return nil, err + return nil, errors.WithStack(err) } dirs := proxyConf.Dirs() for dir := range dirs { @@ -221,7 +220,7 @@ func (c *Config) Watch() { // reloads the TLD and the domains (not the port) func (c *Config) reload() { - data, err := ioutil.ReadFile(c.path) + data, err := os.ReadFile(c.path) if err != nil { return } @@ -249,7 +248,7 @@ func (c *Config) Save() error { if err != nil { return errors.WithStack(err) } - return errors.WithStack(ioutil.WriteFile(c.path, data, 0644)) + return errors.WithStack(os.WriteFile(c.path, data, 0644)) } // should be called with a lock a place diff --git a/local/proxy/proxy.go b/local/proxy/proxy.go index 041b4886..82307b9e 100644 --- a/local/proxy/proxy.go +++ b/local/proxy/proxy.go @@ -20,6 +20,7 @@ package proxy import ( + "context" "crypto/tls" "crypto/x509" "fmt" @@ -56,12 +57,15 @@ func tlsToLocalWebServer(proxy *goproxy.ProxyHttpServer, tlsConfig *tls.Config, } connectDial := func(proxy *goproxy.ProxyHttpServer, network, addr string) (c net.Conn, err error) { if proxy.ConnectDial != nil { - return proxy.ConnectDial(network, addr) + c, err := proxy.ConnectDial(network, addr) + return c, errors.WithStack(err) } - if proxy.Tr.Dial != nil { - return proxy.Tr.Dial(network, addr) + if proxy.Tr.DialContext != nil { + c, err := proxy.Tr.DialContext(context.Background(), network, addr) + return c, errors.WithStack(err) } - return net.Dial(network, addr) + co, err := net.Dial(network, addr) + return co, errors.WithStack(err) } // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header // looks like it might've been a misdirected plaintext HTTP request. @@ -76,13 +80,13 @@ func tlsToLocalWebServer(proxy *goproxy.ProxyHttpServer, tlsConfig *tls.Config, Action: goproxy.ConnectHijack, Hijack: func(req *http.Request, proxyClient net.Conn, ctx *goproxy.ProxyCtx) { ctx.Logf("Hijacking CONNECT") - proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n")) + _, _ = proxyClient.Write([]byte("HTTP/1.0 200 OK\r\n\r\n")) proxyClientTls := tls.Server(proxyClient, tlsConfig) if err := proxyClientTls.Handshake(); err != nil { defer proxyClient.Close() if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) { - io.WriteString(proxyClient, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n") + _, _ = io.WriteString(proxyClient, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n") return } @@ -124,14 +128,14 @@ func tlsToLocalWebServer(proxy *goproxy.ProxyHttpServer, tlsConfig *tls.Config, ctx.Warnf("Error copying to target: %s", err) httpError(proxyClientTls, ctx, err) } - proxyClientTls.CloseWrite() + _ = proxyClientTls.CloseWrite() wg.Done() }() go func() { if _, err := io.Copy(targetSiteTls, proxyClientTls); err != nil { ctx.Warnf("Error copying to client: %s", err) } - targetSiteTls.CloseWrite() + _ = targetSiteTls.CloseWrite() wg.Done() }() wg.Wait() @@ -320,7 +324,7 @@ func (p *Proxy) servePacFile(w http.ResponseWriter, r *http.Request) { // No need to fall back to p.Host and p.Port as r.Host is already checked // upper in the stacktrace. w.Header().Add("Content-Type", "application/x-ns-proxy-autoconfig") - w.Write([]byte(fmt.Sprintf(`// Only proxy *.%s requests + _, _ = w.Write([]byte(fmt.Sprintf(`// Only proxy *.%s requests // Configuration file in ~/.symfony5/proxy.json function FindProxyForURL (url, host) { if (dnsDomainIs(host, '.%s')) { @@ -376,5 +380,5 @@ func (p *Proxy) serveIndex(w http.ResponseWriter, r *http.Request) { content += "
" } } - w.Write([]byte(html.WrapHTML("Proxy Index", html.CreateTerminal(content), ""))) + _, _ = w.Write([]byte(html.WrapHTML("Proxy Index", html.CreateTerminal(content), ""))) } diff --git a/local/proxy/proxy_test.go b/local/proxy/proxy_test.go index da3f84eb..abad7cf1 100644 --- a/local/proxy/proxy_test.go +++ b/local/proxy/proxy_test.go @@ -22,7 +22,7 @@ package proxy import ( "crypto/tls" "crypto/x509" - "io/ioutil" + "io" "log" "net/http" "net/http/httptest" @@ -59,7 +59,7 @@ func (s *ProxySuite) TestProxy(c *C) { TLD: "wip", path: "testdata/.symfony5/proxy.json", }, ca, log.New(zerolog.New(os.Stderr), "", 0), true) - os.MkdirAll("testdata/.symfony5", 0755) + _ = os.MkdirAll("testdata/.symfony5", 0755) err = p.Save() c.Assert(err, IsNil) @@ -122,7 +122,7 @@ func (s *ProxySuite) TestProxy(c *C) { res, err := client.Do(req) c.Assert(err, IsNil) c.Assert(res.StatusCode, Equals, http.StatusNotFound) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) c.Check(strings.Contains(string(body), "not linked"), Equals, true) } @@ -134,7 +134,7 @@ func (s *ProxySuite) TestProxy(c *C) { res, err := client.Do(req) c.Assert(err, IsNil) c.Assert(res.StatusCode, Equals, http.StatusNotFound) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) c.Check(strings.Contains(string(body), "not started"), Equals, true) } /* @@ -142,7 +142,7 @@ func (s *ProxySuite) TestProxy(c *C) { { backend := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) - w.Write([]byte(`symfony.wip`)) + _, _ = w.Write([]byte(`symfony.wip`)) })) cert, err := ca.CreateCert([]string{"localhost", "127.0.0.1"}) c.Assert(err, IsNil) @@ -164,7 +164,7 @@ func (s *ProxySuite) TestProxy(c *C) { res, err := client.Do(req) c.Assert(err, IsNil) c.Assert(res.StatusCode, Equals, http.StatusOK) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) c.Check(string(body), Equals, "symfony.wip") } */ @@ -172,7 +172,7 @@ func (s *ProxySuite) TestProxy(c *C) { { backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) - w.Write([]byte(`http://symfony-no-tls.wip`)) + _, _ = w.Write([]byte(`http://symfony-no-tls.wip`)) })) defer backend.Close() backendURL, err := url.Parse(backend.URL) @@ -180,14 +180,14 @@ func (s *ProxySuite) TestProxy(c *C) { p := pid.New("symfony_com_no_tls", nil) port, _ := strconv.Atoi(backendURL.Port()) - p.Write(os.Getpid(), port, "http") + _ = p.Write(os.Getpid(), port, "http") req, _ := http.NewRequest("GET", "http://symfony-no-tls.wip/", nil) req.Close = true res, err := client.Do(req) c.Assert(err, IsNil) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) c.Assert(res.StatusCode, Equals, http.StatusOK) c.Assert(string(body), Equals, "http://symfony-no-tls.wip") } @@ -212,10 +212,10 @@ func (s *ProxySuite) TestProxy(c *C) { backend := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) if r.Proto == "HTTP/2.0" { - w.Write([]byte(`http2`)) + _, _ = w.Write([]byte(`http2`)) return } - w.Write([]byte(`symfony.wip`)) + _, _ = w.Write([]byte(`symfony.wip`)) })) cert, err := ca.CreateCert([]string{"localhost", "127.0.0.1"}) c.Assert(err, IsNil) @@ -238,7 +238,7 @@ func (s *ProxySuite) TestProxy(c *C) { res, err := client.Do(req) c.Assert(err, IsNil) c.Assert(res.StatusCode, Equals, http.StatusOK) - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) c.Check(string(body), Equals, "http2") } */ diff --git a/local/runner.go b/local/runner.go index 7337ae74..22c107db 100644 --- a/local/runner.go +++ b/local/runner.go @@ -71,7 +71,7 @@ func NewRunner(pidFile *pid.PidFile, mode runnerMode) (*Runner, error) { } r.binary, err = exec.LookPath(pidFile.Binary()) if err != nil { - r.pidFile.Remove() + _ = r.pidFile.Remove() return nil, errors.WithStack(err) } @@ -91,7 +91,7 @@ func (r *Runner) Run() error { } if _, isExitCoder := err.(console.ExitCoder); isExitCoder { - return err + return errors.WithStack(err) } terminal.Printfln("Impossible to go to the background: %s", err) terminal.Println("Continue in foreground") @@ -107,7 +107,7 @@ func (r *Runner) Run() error { cmdExitChan := make(chan error) // receives command exit status, allow to cmd.Wait() in non-blocking way restartChan := make(chan bool) // receives requests to restart the command sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, os.Kill, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + signal.Notify(sigChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) defer signal.Stop(sigChan) if len(r.pidFile.Watched) > 0 { @@ -175,7 +175,7 @@ func (r *Runner) Run() error { timer.Reset(RunnerReliefDuration) if r.mode == RunnerModeLoopDetached { - reexec.NotifyForeground("started") + _ = reexec.NotifyForeground("started") } select { @@ -203,7 +203,7 @@ func (r *Runner) Run() error { } if firstBoot && r.mode == RunnerModeLoopDetached { terminal.RemapOutput(cmd.Stdout, cmd.Stderr).SetDecorated(true) - reexec.NotifyForeground(reexec.UP) + _ = reexec.NotifyForeground(reexec.UP) } firstBoot = false @@ -213,13 +213,13 @@ func (r *Runner) Run() error { terminal.Logger.Info().Msgf("Signal \"%s\" received, forwarding to command and exiting\n", sig) err := cmd.Process.Signal(sig) if err != nil && runtime.GOOS == "windows" && strings.Contains(err.Error(), "not supported by windows") { - return exec.Command("CMD", "/C", "TASKKILL", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)).Run() + return errors.WithStack(exec.Command("CMD", "/C", "TASKKILL", "/F", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()) } - return err + return errors.WithStack(err) case <-restartChan: // We use SIGTERM here because it's nicer and thus when we use our // wrappers, signal will be nicely forwarded - cmd.Process.Signal(syscall.SIGTERM) + _ = cmd.Process.Signal(syscall.SIGTERM) // we need to drain cmdExit channel to unblock cmd channel receiver <-cmdExitChan case err := <-cmdExitChan: @@ -241,7 +241,7 @@ func (r *Runner) Run() error { return r.pidFile.Remove() } - return err + return errors.WithStack(err) } terminal.Logger.Info().Msgf(`Restarting command "%s"`, r.pidFile) diff --git a/local/sum.go b/local/sum.go index 2a603b38..4e747014 100644 --- a/local/sum.go +++ b/local/sum.go @@ -27,6 +27,6 @@ import ( func Name(dir string) string { h := sha1.New() - io.WriteString(h, dir) + _, _ = io.WriteString(h, dir) return fmt.Sprintf("%x", h.Sum(nil)) } diff --git a/main.go b/main.go index e4f95c1a..da2a1633 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,7 @@ package main import ( "fmt" - "io/ioutil" + "io" "os" "time" @@ -83,7 +83,7 @@ func main() { } // called via "symfony composer"? if len(args) >= 2 && args[1] == "composer" { - res := php.Composer("", args[2:], getCliExtraEnv(), os.Stdout, os.Stderr, ioutil.Discard, zerolog.Nop()) + res := php.Composer("", args[2:], getCliExtraEnv(), os.Stdout, os.Stderr, io.Discard, zerolog.Nop()) terminal.Eprintln(res.Error()) os.Exit(res.ExitCode()) } @@ -124,5 +124,7 @@ func main() { Channel: channel, BuildDate: buildDate, } - app.Run(args) + if err := app.Run(args); err != nil { + panic(err) + } } diff --git a/reexec/process_windows.go b/reexec/process_windows.go index f1ea0352..ef491201 100644 --- a/reexec/process_windows.go +++ b/reexec/process_windows.go @@ -122,7 +122,7 @@ func newWindowsProcess(e *processentry32) *windowsProcess { func findProcess(pid int) (*windowsProcess, error) { ps, err := processes() if err != nil { - return nil, err + return nil, errors.WithStack(err) } for _, p := range ps { diff --git a/reexec/reexec.go b/reexec/reexec.go index ab434f67..b6f455da 100644 --- a/reexec/reexec.go +++ b/reexec/reexec.go @@ -21,7 +21,6 @@ package reexec import ( "fmt" - "io/ioutil" "os" "os/exec" "os/signal" @@ -80,7 +79,7 @@ func ExecBinaryWithEnv(binary string, envs []string) bool { case state := <-done: return state case <-time.After(10 * time.Second): - p.Kill() + _ = p.Kill() return false } } @@ -90,7 +89,7 @@ func Background(homeDir string) error { return errors.New("Not applicable in a Go run context") } - statusFile, err := ioutil.TempFile(homeDir, "status-") + statusFile, err := os.CreateTemp(homeDir, "status-") if err != nil { return errors.Wrap(err, "Could not create status file") } @@ -151,7 +150,7 @@ func Background(homeDir string) error { continue } if err := p.Signal(sig); err != nil { - p.Kill() + _ = p.Kill() return errors.Wrapf(err, "error sending signal %s", sig) } // if the signal terminates the process we will loop over and @@ -170,7 +169,7 @@ func Background(homeDir string) error { case status := <-statusCh: return console.Exit("", status) case <-ticker.C: - p.Kill() + _ = p.Kill() return errors.New("reexec timed out") } } @@ -190,9 +189,9 @@ func NotifyForeground(status string) error { os.Stdin.Close() os.Stdout.Close() os.Stderr.Close() - return os.Remove(statusFile) + return errors.WithStack(os.Remove(statusFile)) } - return ioutil.WriteFile(statusFile, []byte(status), 0600) + return errors.WithStack(os.WriteFile(statusFile, []byte(status), 0600)) } func WatchParent(stopCh chan bool) error { @@ -232,7 +231,7 @@ func Restart(postRespawn func()) error { } p, err := Respawn() if err != nil { - return err + return errors.WithStack(err) } if postRespawn != nil { @@ -283,7 +282,7 @@ func Restart(postRespawn func()) error { func Respawn() (*os.Process, error) { argv0, err := console.CurrentBinaryPath() if err != nil { - return nil, err + return nil, errors.WithStack(err) } wd, err := os.Getwd() if err != nil { diff --git a/updater/updater.go b/updater/updater.go index 3d70fc33..51c5a2db 100644 --- a/updater/updater.go +++ b/updater/updater.go @@ -23,7 +23,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -132,7 +131,7 @@ func (updater *Updater) check(currentVersion *version.Version, enableCache bool) if enableCache && manifestFileErr == nil { if stat, err := manifestFile.Stat(); err == nil { if time.Since(stat.ModTime()) < 1*time.Hour { - if manifestCacheBody, manifestCacheErr := ioutil.ReadAll(manifestFile); manifestCacheErr == nil { + if manifestCacheBody, manifestCacheErr := io.ReadAll(manifestFile); manifestCacheErr == nil { manifestBody = manifestCacheBody } } else { @@ -153,7 +152,7 @@ func (updater *Updater) check(currentVersion *version.Version, enableCache bool) updater.logger.Printf("Checking for updates (current version: %s)", currentVersion) if manifestBody == nil { - req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("https://api.github.com/repos/symfony-cli/symfony-cli/releases/latest"), nil) + req, err := http.NewRequest(http.MethodGet, "https://api.github.com/repos/symfony-cli/symfony-cli/releases/latest", nil) if err != nil { updater.logger.Err(err).Msg("") return nil @@ -171,13 +170,13 @@ func (updater *Updater) check(currentVersion *version.Version, enableCache bool) return nil } - manifestBody, err = ioutil.ReadAll(resp.Body) + manifestBody, err = io.ReadAll(resp.Body) if err != nil { updater.logger.Err(err).Msg("") return nil } - if err := ioutil.WriteFile(manifestCachePath, manifestBody, 0644); err != nil { + if err := os.WriteFile(manifestCachePath, manifestBody, 0644); err != nil { updater.logger.Err(err).Msg("") return nil } @@ -231,7 +230,7 @@ type cacheInnerTransport struct { func (rt *cacheInnerTransport) RoundTrip(req *http.Request) (*http.Response, error) { resp, err := rt.RoundTripper.RoundTrip(req) if resp == nil { - return resp, err + return resp, errors.WithStack(err) } if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest { @@ -242,5 +241,5 @@ func (rt *cacheInnerTransport) RoundTrip(req *http.Request) (*http.Response, err resp.Header.Set("cache-control", "no-cache") } - return resp, err + return resp, errors.WithStack(err) }