From 12da984ccee0b64a2eca8916010ee2d00ebe43cf Mon Sep 17 00:00:00 2001 From: darkweak Date: Tue, 20 Dec 2022 20:41:58 +0100 Subject: [PATCH 1/6] feat(code-quality): add golangci-lint to CI and lint project --- .github/workflows/go_generate_update.yml | 3 +++ book/checkout.go | 14 +++++----- book/clone.go | 2 +- book/reqs.go | 12 ++++----- commands/init_templating.go | 11 ++++---- commands/init_templating_php.go | 6 ++--- commands/local_check_requirements.go | 4 +-- commands/local_check_security.go | 2 +- commands/local_new.go | 19 +++++++------ commands/local_php_list.go | 2 +- commands/local_proxy_domain_attach.go | 2 +- commands/local_proxy_domain_detach.go | 2 +- commands/local_proxy_start.go | 15 ++++++----- commands/local_proxy_status.go | 6 ++--- commands/local_run.go | 2 +- commands/local_server_ca_install.go | 4 +-- commands/local_server_ca_uninstall.go | 4 +-- commands/local_server_start.go | 34 +++++++++++++----------- commands/local_server_status.go | 30 ++++++++++----------- commands/openers.go | 12 +-------- commands/var_export.go | 4 +-- envs/docker.go | 8 +++--- envs/envs.go | 3 +-- envs/local.go | 7 +++-- envs/local_test.go | 10 ++++--- envs/local_tunnel.go | 5 ++-- humanlog/symfony.go | 2 +- local/fcgi_client/fcgiclient.go | 7 +++-- local/http/http.go | 4 +-- local/logs/tailer.go | 14 +++++----- local/php/composer.go | 9 +++---- local/php/executor.go | 6 ++--- local/php/executor_test.go | 33 ++++++++++++++--------- local/php/php_server.go | 13 +++++---- local/php/platformsh.go | 14 +++++----- local/php/toolbar.go | 16 +++++------ local/pid/pidfile.go | 17 ++++++------ local/platformsh/applications.go | 3 +-- local/platformsh/generator/commands.go | 5 ++-- local/platformsh/generator/config.go | 6 ++--- local/platformsh/project.go | 3 +-- local/process/process.go | 2 +- local/project/config.go | 3 +-- local/project/project.go | 3 +-- local/proxy/config.go | 9 +++---- local/proxy/proxy.go | 17 ++++++------ local/proxy/proxy_test.go | 18 ++++++------- local/runner.go | 14 +++++----- local/sum.go | 2 +- main.go | 6 ++--- reexec/reexec.go | 11 ++++---- updater/updater.go | 9 +++---- 52 files changed, 232 insertions(+), 237 deletions(-) diff --git a/.github/workflows/go_generate_update.yml b/.github/workflows/go_generate_update.yml index ecdd54da..8710078d 100644 --- a/.github/workflows/go_generate_update.yml +++ b/.github/workflows/go_generate_update.yml @@ -35,6 +35,9 @@ jobs: run: | RESULT=$(git status --untracked-files=no --porcelain) echo "gitstatus=$RESULT" >> $GITHUB_OUTPUT + - + name: golangci-lint + uses: golangci/golangci-lint-action@v3 - name: Test if: steps.git.outputs.gitstatus != '' diff --git a/book/checkout.go b/book/checkout.go index b9288399..1bfb397f 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 @@ -117,7 +117,7 @@ func (b *Book) Checkout(step string) error { } printBanner("[WEB] Stopping the Local Web Server", b.Debug) - executeCommand([]string{"symfony", "server:stop"}, b.Debug, true, nil) + _ = executeCommand([]string{"symfony", "server:stop"}, b.Debug, true, nil) printBanner("[WEB] Stopping the Platform.sh tunnel", b.Debug) if err := executeCommand([]string{"symfony", "tunnel:close", "-y"}, b.Debug, true, nil); err != nil { @@ -131,7 +131,7 @@ func (b *Book) Checkout(step string) error { 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) + _ = executeCommand([]string{"symfony", "server:stop", "--dir", filepath.Join(b.Dir, "spa")}, b.Debug, true, nil) } else { terminal.Println("Skipped for this step") } @@ -237,7 +237,7 @@ 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 @@ -246,7 +246,7 @@ func (b *Book) Checkout(step string) error { if err := executeCommand(args, b.Debug, false, nil); err != nil { return err } - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) } else { terminal.Println("Skipped for this step") } @@ -264,7 +264,7 @@ 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 { @@ -273,7 +273,7 @@ func (b *Book) Checkout(step string) error { if err := executeCommand(args, b.Debug, false, env); err != nil { return err } - os.Chdir(b.Dir) + _ = os.Chdir(b.Dir) } else { terminal.Println("Skipped for this step") } diff --git a/book/clone.go b/book/clone.go index 84f3c116..4fc08627 100644 --- a/book/clone.go +++ b/book/clone.go @@ -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 { diff --git a/book/reqs.go b/book/reqs.go index c833b2cb..22bb1bc4 100644 --- a/book/reqs.go +++ b/book/reqs.go @@ -75,13 +75,13 @@ func CheckRequirements() (bool, error) { v, _, _, _ := store.BestVersionForDir(wd) if v == nil { ready = false - terminal.Println("[KO] Cannot find PHP, please install it https://php.net/") + _, _ = terminal.Println("[KO] Cannot find PHP, please install it https://php.net/") } else { if v.FullVersion.GreaterThan(minv) { - terminal.Printfln("[OK] PHP installed version %s (%s)", v.FullVersion, v.PHPPath) + _, _ = terminal.Printfln("[OK] PHP installed version %s (%s)", v.FullVersion, v.PHPPath) } else { ready = false - terminal.Printfln("[KO] PHP installed; version %s found but we need version 7.2.5+ (%s)", v.FullVersion, v.PHPPath) + _, _ = terminal.Printfln("[KO] PHP installed; version %s found but we need version 7.2.5+ (%s)", v.FullVersion, v.PHPPath) } } @@ -110,12 +110,12 @@ func CheckRequirements() (bool, error) { if _, ok := phpexts[ext]; !ok { if reason == "required" { ready = false - terminal.Printfln(`[KO] PHP extension "%s" not found, please install it - %s`, ext, reason) + _, _ = terminal.Printfln(`[KO] PHP extension "%s" not found, please install it - %s`, ext, reason) } else { - terminal.Printfln(`[KO] PHP extension "%s" not found, %s`, ext, reason) + _, _ = terminal.Printfln(`[KO] PHP extension "%s" not found, %s`, ext, reason) } } else { - terminal.Printfln(`[OK] PHP extension "%s" installed - %s`, ext, reason) + _, _ = terminal.Printfln(`[OK] PHP extension "%s" installed - %s`, ext, reason) } } } diff --git a/commands/init_templating.go b/commands/init_templating.go index 859cd50a..b1abe10f 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,7 +193,7 @@ 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) @@ -206,7 +205,7 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri } 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..595449cc 100644 --- a/commands/init_templating_php.go +++ b/commands/init_templating_php.go @@ -22,7 +22,7 @@ package commands import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" @@ -158,7 +158,7 @@ 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 } @@ -181,7 +181,7 @@ 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 } diff --git a/commands/local_check_requirements.go b/commands/local_check_requirements.go index 6671a9ce..44489a58 100644 --- a/commands/local_check_requirements.go +++ b/commands/local_check_requirements.go @@ -21,7 +21,6 @@ package commands import ( _ "embed" - "io/ioutil" "os" "path/filepath" @@ -33,6 +32,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 @@ -63,7 +63,7 @@ var localRequirementsCheckCmd = &console.Command{ cachePath := filepath.Join(cacheDir, "check.php") defer os.Remove(cachePath) - if err := ioutil.WriteFile(cachePath, phpChecker, 0600); err != nil { + if err := os.WriteFile(cachePath, phpChecker, 0600); err != nil { return err } diff --git a/commands/local_check_security.go b/commands/local_check_security.go index bf4223f2..54b75dcf 100644 --- a/commands/local_check_security.go +++ b/commands/local_check_security.go @@ -69,7 +69,7 @@ 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) + _, _ = terminal.Stdout.Write(output) if os.Getenv("GITHUB_WORKSPACE") != "" { gOutFile := os.Getenv("GITHUB_OUTPUT") diff --git a/commands/local_new.go b/commands/local_new.go index e94fafc4..a6afbf9f 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" @@ -148,7 +147,7 @@ var localNewCmd = &console.Command{ return err } - if "" != c.String("php") && !c.Bool("cloud") { + if c.String("php") != "" && !c.Bool("cloud") { if err := createPhpVersionFile(c.String("php"), dir); err != nil { return err } @@ -317,24 +316,24 @@ func parseDockerComposeServices(dir string) []*CloudService { } func initProjectGit(c *console.Context, s *terminal.Spinner, dir string) error { - terminal.Println("* Setting up the project under Git version control") - terminal.Printfln(" (running git init %s)\n", dir) + _, _ = terminal.Println("* Setting up the project under Git version control") + _, _ = terminal.Printfln(" (running git init %s)\n", dir) // Only force the branch to be "main" when running a Cloud context to make // onboarding simpler. if buf, err := git.Init(dir, c.Bool("cloud"), c.Bool("debug")); err != nil { - fmt.Print(buf.String()) + _, _ = fmt.Print(buf.String()) return err } buf, err := git.AddAndCommit(dir, []string{"."}, "Add initial set of files", c.Bool("debug")) if err != nil { - fmt.Print(buf.String()) + _, _ = fmt.Print(buf.String()) } return err } func createProjectWithComposer(c *console.Context, dir, version string) error { if c.Bool("demo") { - terminal.Println("* Creating a new Symfony Demo project with Composer") + _, _ = terminal.Println("* Creating a new Symfony Demo project with Composer") } else if version != "" { if version == "lts" || version == "previous" || version == "stable" || version == "next" || version == "dev" { var err error @@ -344,9 +343,9 @@ func createProjectWithComposer(c *console.Context, dir, version string) error { } } - terminal.Printfln("* Creating a new Symfony %s project with Composer", version) + _, _ = terminal.Printfln("* Creating a new Symfony %s project with Composer", version) } else { - terminal.Println("* Creating a new Symfony project with Composer") + _, _ = terminal.Println("* Creating a new Symfony project with Composer") } repo := "symfony/skeleton" @@ -397,7 +396,7 @@ func getSpecialVersion(version string) (string, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/commands/local_php_list.go b/commands/local_php_list.go index b570e639..ced939ef 100644 --- a/commands/local_php_list.go +++ b/commands/local_php_list.go @@ -54,7 +54,7 @@ var localPhpListCmd = &console.Command{ currentPHPPath := "" v, source, warning, _ := phpStore.BestVersionForDir(wd) if warning != "" { - terminal.Eprintfln("WARNING %s", warning) + _, _ = terminal.Eprintfln("WARNING %s", warning) } if v != nil { currentPHPPath = v.PHPPath diff --git a/commands/local_proxy_domain_attach.go b/commands/local_proxy_domain_attach.go index ea37acf7..bfcf0908 100644 --- a/commands/local_proxy_domain_attach.go +++ b/commands/local_proxy_domain_attach.go @@ -53,7 +53,7 @@ var localProxyAttachDomainCmd = &console.Command{ } terminal.Println("The proxy is now configured with the following domains for this directory:") for _, domain := range config.GetDomains(projectDir) { - terminal.Printfln(" * http://%s", domain) + _, _ = terminal.Printfln(" * http://%s", domain) } return nil }, diff --git a/commands/local_proxy_domain_detach.go b/commands/local_proxy_domain_detach.go index 45783544..2fa48ef7 100644 --- a/commands/local_proxy_domain_detach.go +++ b/commands/local_proxy_domain_detach.go @@ -46,7 +46,7 @@ var localProxyDetachDomainCmd = &console.Command{ } terminal.Println("The following domains are not defined anymore on the proxy:") for _, domain := range domains { - terminal.Printfln(" * http://%s", domain) + _, _ = terminal.Printfln(" * http://%s", domain) } return nil }, diff --git a/commands/local_proxy_start.go b/commands/local_proxy_start.go index 50182da9..7782bb37 100644 --- a/commands/local_proxy_start.go +++ b/commands/local_proxy_start.go @@ -70,8 +70,8 @@ var localProxyStartCmd = &console.Command{ if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - terminal.Printfln("Impossible to go to the background: %s", err) - terminal.Println("Continue in foreground") + _, _ = terminal.Printfln("Impossible to go to the background: %s", err) + _, _ = terminal.Println("Continue in foreground") } else { return nil } @@ -112,8 +112,7 @@ var localProxyStartCmd = &console.Command{ if err != nil { return errors.WithStack(err) } - var lw io.Writer - lw = f + var lw io.Writer = f logger := zerolog.New(decorateLogger(lw, c.Bool("no-humanize"))).With().Timestamp().Logger() config, err := proxy.Load(homeDir) @@ -123,7 +122,7 @@ var localProxyStartCmd = &console.Command{ if c.IsSet("host") { config.Host = c.String("host") - config.Save() + _ = config.Save() } spinner := terminal.NewSpinner(terminal.Stderr) @@ -159,9 +158,11 @@ var localProxyStartCmd = &console.Command{ 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_status.go b/commands/local_proxy_status.go index a2015d50..a97f8b4a 100644 --- a/commands/local_proxy_status.go +++ b/commands/local_proxy_status.go @@ -42,10 +42,10 @@ var localProxyStatusCmd = &console.Command{ return nil } - terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) + _, _ = terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) - terminal.Println() - terminal.Println("Configured Web Servers") + _, _ = terminal.Println() + _, _ = terminal.Println("Configured Web Servers") return printConfiguredServers() }, } diff --git a/commands/local_run.go b/commands/local_run.go index 6a89f769..7b195762 100644 --- a/commands/local_run.go +++ b/commands/local_run.go @@ -86,7 +86,7 @@ var localRunCmd = &console.Command{ if err := runner.Run(); err != nil { if _, wentToBackground := err.(local.RunnerWentToBackground); wentToBackground { - terminal.Printfln("Stream the logs via %s server:log", c.App.HelpName) + _, _ = terminal.Printfln("Stream the logs via %s server:log", c.App.HelpName) return nil } diff --git a/commands/local_server_ca_install.go b/commands/local_server_ca_install.go index f29a1b2d..3caed935 100644 --- a/commands/local_server_ca_install.go +++ b/commands/local_server_ca_install.go @@ -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_start.go b/commands/local_server_start.go index 7cfd022d..691827c1 100644 --- a/commands/local_server_start.go +++ b/commands/local_server_start.go @@ -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) @@ -128,16 +128,16 @@ var localServerStartCmd = &console.Command{ if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - terminal.Eprintln("Impossible to go to the background") - terminal.Eprintln("Continue in foreground") + _, _ = terminal.Eprintln("Impossible to go to the background") + _, _ = terminal.Eprintln("Continue in foreground") config.Daemon = false } else { - terminal.Eprintfln("Stream the logs via %s server:log", c.App.HelpName) + _, _ = terminal.Eprintfln("Stream the logs via %s server:log", c.App.HelpName) return nil } } - 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 { @@ -206,11 +206,11 @@ 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 @@ -266,7 +266,7 @@ var localServerStartCmd = &console.Command{ } } - reexec.NotifyForeground("http") + _ = reexec.NotifyForeground("http") port, err := p.HTTP.Start(errChan) if err != nil { return err @@ -298,21 +298,23 @@ var localServerStartCmd = &console.Command{ return err } - reexec.NotifyForeground("listening") + _ = reexec.NotifyForeground("listening") ui.Warning(localWebServerProdWarningMsg) ui.Success(msg) } if !reexec.IsChild() { - go tailer.Tail(terminal.Stderr) + go func(tLog logs.Tailer) { + _ = tLog.Tail(terminal.Stderr) + }(tailer) } if fileConfig != nil { - reexec.NotifyForeground("workers") + _ = reexec.NotifyForeground("workers") for name, worker := range fileConfig.Workers { pidFile := pid.New(projectDir, worker.Cmd) if pidFile.IsRunning() { - terminal.Eprintfln("WARNING Unable to start worker \"%s\": it is already running for this project as PID %d", name, pidFile.Pid) + _, _ = terminal.Eprintfln("WARNING Unable to start worker \"%s\": it is already running for this project as PID %d", name, pidFile.Pid) continue } pidFile.Watched = worker.Watch @@ -323,7 +325,7 @@ var localServerStartCmd = &console.Command{ go func(name string, pidFile *pid.PidFile) { runner, err := local.NewRunner(pidFile, local.RunnerModeLoopAttached) if err != nil { - terminal.Eprintfln("WARNING Unable to start worker \"%s\": %s", name, err) + _, _ = terminal.Eprintfln("WARNING Unable to start worker \"%s\": %s", name, err) return } @@ -341,13 +343,13 @@ var localServerStartCmd = &console.Command{ ui.Success(fmt.Sprintf("Started worker \"%s\"", name)) if err := runner.Run(); err != nil { - terminal.Eprintfln("WARNING Worker \"%s\" exited with an error: %s", name, err) + _, _ = terminal.Eprintfln("WARNING Worker \"%s\" exited with an error: %s", name, err) } }(name, pidFile) } } - reexec.NotifyForeground(reexec.UP) + _ = reexec.NotifyForeground(reexec.UP) if reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) } diff --git a/commands/local_server_status.go b/commands/local_server_status.go index 13936caf..9d01ea02 100644 --- a/commands/local_server_status.go +++ b/commands/local_server_status.go @@ -55,47 +55,47 @@ func printWebServerStatus(projectDir string) error { workers := pid.AllWorkers(projectDir) // web server - terminal.Println("Local Web Server") + _, _ = terminal.Println("Local Web Server") if !pidFile.IsRunning() { - terminal.Println(" Not Running") + _, _ = terminal.Println(" Not Running") } else { - terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) + _, _ = terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) homeDir := util.GetHomeDir() phpStore := phpstore.New(homeDir, true, nil) version, source, warning, err := phpStore.BestVersionForDir(projectDir) if err == nil { - terminal.Printfln(" The Web server is using %s %s (from %s)", version.ServerTypeName(), version.Version, source) + _, _ = terminal.Printfln(" The Web server is using %s %s (from %s)", version.ServerTypeName(), version.Version, source) if warning != "" { - terminal.Printfln(" WARNING %s", warning) + _, _ = terminal.Printfln(" WARNING %s", warning) } } - terminal.Println() - terminal.Println("Local Domains") + _, _ = terminal.Println() + _, _ = terminal.Println("Local Domains") if proxyConf, err := proxy.Load(util.GetHomeDir()); err == nil { for _, domain := range proxyConf.GetDomains(projectDir) { - terminal.Printfln(" %s://%s", pidFile.Scheme, domain, pidFile.Scheme, domain) + _, _ = terminal.Printfln(" %s://%s", pidFile.Scheme, domain, pidFile.Scheme, domain) } } } // workers - terminal.Println() - terminal.Println("Workers") + _, _ = terminal.Println() + _, _ = terminal.Println("Workers") if len(workers) == 0 { - terminal.Println(" No Workers") + _, _ = terminal.Println(" No Workers") } else { for _, p := range workers { msg := fmt.Sprintf(` PID %d: %s`, p.Pid, p.Command()) if len(p.Watched) > 0 { msg += fmt.Sprintf(" (watching %s/)", strings.Join(p.Watched, "/, ")) } - terminal.Println(msg) + _, _ = terminal.Println(msg) } } // env vars - terminal.Println() - terminal.Println("Environment Variables") + _, _ = terminal.Println() + _, _ = terminal.Println("Environment Variables") data, err := envs.GetEnv(projectDir, terminal.IsDebug()) if err != nil { return err @@ -108,7 +108,7 @@ func printWebServerStatus(projectDir string) error { if env["SYMFONY_DOCKER_ENV"] == "1" && env["SYMFONY_TUNNEL_ENV"] == "" { envVars = `Exposed from Docker` } - terminal.Printfln(" %s", envVars) + _, _ = terminal.Printfln(" %s", envVars) return nil } diff --git a/commands/openers.go b/commands/openers.go index 7e51e8a3..72377679 100644 --- a/commands/openers.go +++ b/commands/openers.go @@ -32,16 +32,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", @@ -163,6 +153,6 @@ func abstractOpenCmd(url string) { terminal.Eprintln("Error while opening:", err, "") terminal.Eprintfln("Please visit %s manually.", url, url) } else { - terminal.Eprintfln("Opened: %s", url, url) + _, _ = terminal.Eprintfln("Opened: %s", url, url) } } diff --git a/commands/var_export.go b/commands/var_export.go index d17c0574..3651715f 100644 --- a/commands/var_export.go +++ b/commands/var_export.go @@ -70,11 +70,11 @@ var variableExportCmd = &console.Command{ } sort.Strings(keys) for _, k := range keys { - terminal.Printfln("export %s=%s", k, m[k]) + _, _ = terminal.Printfln("export %s=%s", k, m[k]) } } else { // output the string (useful when doing export $(envs)) - terminal.Print(envs.AsString(env)) + _, _ = terminal.Print(envs.AsString(env)) } return nil diff --git a/envs/docker.go b/envs/docker.go index 6f725151..89a3f951 100644 --- a/envs/docker.go +++ b/envs/docker.go @@ -23,7 +23,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "net" "net/url" "os" @@ -197,7 +196,10 @@ func (l *Local) dockerServiceToRelationship(client *docker.Client, container typ } sort.Sort(exposedPorts) - for _, p := range exposedPorts { + + if exposedPorts.Len() > 0 { + p := exposedPorts[0] + rels := make(map[string]map[string]interface{}) if p.PrivatePort == 1025 { // recommended image: schickling/mailcatcher @@ -479,7 +481,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..bf35a2f9 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" @@ -58,7 +57,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 +97,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 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/local/fcgi_client/fcgiclient.go b/local/fcgi_client/fcgiclient.go index d3d68e42..5a970c88 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" @@ -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() @@ -376,9 +375,9 @@ func (f *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res } 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 } diff --git a/local/http/http.go b/local/http/http.go index 43e09e67..ca3e74d9 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/logs/tailer.go b/local/logs/tailer.go index 365a7a53..a55db3a8 100644 --- a/local/logs/tailer.go +++ b/local/logs/tailer.go @@ -112,7 +112,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { } p, err := pid.Load(e.Path()) if err != nil { - terminal.Printfln("WARNING %s", err) + _, _ = terminal.Printfln("WARNING %s", err) continue } tailer.pidFileChan <- p @@ -179,7 +179,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { go func() { tsf, err := tailFile(applog, tailer.Follow, tailer.LinesNb) if err != nil { - terminal.Printfln("WARNING %s log file cannot be tailed: %s", applog, err) + _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", applog, err) return } for line := range tsf.Lines { @@ -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()) } } @@ -229,15 +229,15 @@ func (tailer Tailer) WatchAdditionalPidFile(file *pid.PidFile) { func tailLogFile(p *pid.PidFile, lines chan *namedLine, follow bool, nblines int64) { if err := p.WaitForLogs(); err != nil { - terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) + _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) return } t, err := tailFile(p.LogFile(), follow, nblines) if err != nil { - terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) + _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) return } - terminal.Printfln("Following %s log file (%s)", p.String(), p.LogFile()) + _, _ = terminal.Printfln("Following %s log file (%s)", p.String(), p.LogFile()) for line := range t.Lines { lines <- &namedLine{name: p.ShortName(), line: line} } @@ -253,7 +253,7 @@ func tailFile(filename string, follow bool, nblines int64) (*tail.Tail, error) { return tail.TailFile(filename, tail.Config{ Location: &tail.SeekInfo{ Offset: pos, - Whence: os.SEEK_SET, + Whence: io.SeekStart, }, ReOpen: follow, Follow: follow, diff --git a/local/php/composer.go b/local/php/composer.go index f7ea1b72..71d32fba 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" @@ -120,7 +119,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 } @@ -179,7 +178,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{ @@ -210,7 +209,7 @@ func downloadComposerInstaller() ([]byte, error) { return nil, err } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } func downloadComposerInstallerSignature() ([]byte, error) { @@ -219,5 +218,5 @@ func downloadComposerInstallerSignature() ([]byte, error) { return nil, err } defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } diff --git a/local/php/executor.go b/local/php/executor.go index 28fc58f6..085aa89c 100644 --- a/local/php/executor.go +++ b/local/php/executor.go @@ -77,7 +77,7 @@ func (e *Executor) lookupPHP(cliDir string, forceReload bool) (*phpstore.Version phpStore := phpstore.New(cliDir, forceReload, nil) v, source, warning, err := phpStore.BestVersionForDir(e.scriptDir) if warning != "" { - terminal.Eprintfln("WARNING %s", warning) + _, _ = terminal.Eprintfln("WARNING %s", warning) } if err != nil { return nil, "", true, err @@ -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) @@ -400,7 +400,7 @@ func LookPath(file string) (string, error) { wd, _ := os.Getwd() v, _, warning, _ := phpStore.BestVersionForDir(wd) if warning != "" { - terminal.Eprintfln("WARNING %s", warning) + _, _ = terminal.Eprintfln("WARNING %s", warning) } if v == nil { // unable to find the current PHP version, fall back diff --git a/local/php/executor_test.go b/local/php/executor_test.go index 52216ce7..175d4655 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() { + _ = os.Chdir(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")) + defer func() { + _ = os.Chdir(oldwd) + }() + _ = os.Chdir(filepath.Join(home, "project")) - os.Rename("git", ".git") - defer os.Rename(".git", "git") + _ = 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() { + _ = os.WriteFile(projectFile, contents, 0644) + }() + _ = os.WriteFile(projectFile, bytes.Replace(contents, []byte("bew7pfa7t2ut2"), []byte("aew7pfa7t2ut2"), 1), 0644) output.Reset() outCloser = testStdoutCapture(c, &output) diff --git a/local/php/php_server.go b/local/php/php_server.go index 676e88a0..62e1f675 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" @@ -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()), ""))) } } @@ -205,7 +204,7 @@ 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 } @@ -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..a1134190 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" @@ -25,7 +25,7 @@ func InstallPlatformPhar(home string) error { 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 } } @@ -39,14 +39,16 @@ func InstallPlatformPhar(home string) error { return err } defer resp.Body.Close() - installer, err := ioutil.ReadAll(resp.Body) + installer, err := io.ReadAll(resp.Body) if err != nil { return err } installerPath := filepath.Join(home, "platformsh-installer.php") - ioutil.WriteFile(installerPath, installer, 0666) - defer os.Remove(installerPath) + _ = os.WriteFile(installerPath, installer, 0666) + defer func() { + _ = os.Remove(installerPath) + }() var stdout bytes.Buffer e := &Executor{ @@ -62,5 +64,5 @@ func InstallPlatformPhar(home string) error { return errors.Errorf("unable to setup platformsh CLI: %s", stdout.String()) } - return ioutil.WriteFile(versionPath, internalVersion, 0644) + return 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 9f211fe3..86cea1fe 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,7 +71,7 @@ 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 } @@ -255,7 +254,7 @@ func (p *PidFile) Write(pid, port int, scheme string) error { return err } - return ioutil.WriteFile(p.path, b, 0644) + return 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() { + _ = p.Remove() + }() 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/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..23f017fa 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) } diff --git a/local/platformsh/generator/config.go b/local/platformsh/generator/config.go index 32b59d8d..107e3836 100644 --- a/local/platformsh/generator/config.go +++ b/local/platformsh/generator/config.go @@ -5,7 +5,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "log" "net/http" "os" @@ -83,7 +83,7 @@ func generateConfig() { if err != nil { panic(err) } - f.Write(buf.Bytes()) + _, _ = f.Write(buf.Bytes()) } func parseServices() (string, error) { @@ -93,7 +93,7 @@ func parseServices() (string, error) { } 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 } 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/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/project/config.go b/local/project/config.go index b1ef0825..c5d3767b 100644 --- a/local/project/config.go +++ b/local/project/config.go @@ -20,7 +20,6 @@ package project import ( - "io/ioutil" "os" "path/filepath" @@ -121,7 +120,7 @@ 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 } diff --git a/local/project/project.go b/local/project/project.go index 400b9816..635a6e0d 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" @@ -112,7 +111,7 @@ func realPassthru(documentRoot, passthru string) (string, error) { func guessDocumentRoot(path string) string { // for Symfony: check if public-dir is setup 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/config.go b/local/proxy/config.go index 04c3831b..60b53179 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) } @@ -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 71d989b0..ac024443 100644 --- a/local/proxy/proxy.go +++ b/local/proxy/proxy.go @@ -20,6 +20,7 @@ package proxy import ( + "context" "crypto/tls" "crypto/x509" "fmt" @@ -58,8 +59,8 @@ func tlsToLocalWebServer(proxy *goproxy.ProxyHttpServer, tlsConfig *tls.Config, if proxy.ConnectDial != nil { return proxy.ConnectDial(network, addr) } - if proxy.Tr.Dial != nil { - return proxy.Tr.Dial(network, addr) + if proxy.Tr.DialContext != nil { + return proxy.Tr.DialContext(context.Background(), network, addr) } return net.Dial(network, addr) } @@ -76,13 +77,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 +125,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 +321,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')) { @@ -371,5 +372,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 03437d05..029a51f3 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) } /* @@ -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") } @@ -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 b128c91d..0c83d587 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) } @@ -93,8 +93,8 @@ func (r *Runner) Run() error { if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - terminal.Printfln("Impossible to go to the background: %s", err) - terminal.Println("Continue in foreground") + _, _ = terminal.Printfln("Impossible to go to the background: %s", err) + _, _ = terminal.Println("Continue in foreground") r.mode = RunnerModeOnce } else { if err := reexec.NotifyForeground("boot"); err != nil { @@ -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, syscall.SIGTERM, 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 @@ -219,7 +219,7 @@ func (r *Runner) Run() error { 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: 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..e1bbb476 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,5 @@ func main() { Channel: channel, BuildDate: buildDate, } - app.Run(args) + _ = app.Run(args) } diff --git a/reexec/reexec.go b/reexec/reexec.go index 15e28619..b46a8210 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") } } @@ -192,7 +191,7 @@ func NotifyForeground(status string) error { os.Stderr.Close() return os.Remove(statusFile) } - return ioutil.WriteFile(statusFile, []byte(status), 0600) + return os.WriteFile(statusFile, []byte(status), 0600) } func WatchParent(stopCh chan bool) error { diff --git a/updater/updater.go b/updater/updater.go index 483c69c4..2ec02c00 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 } From 7f28bebbcda76c2f21f28943e8011d7c9dab5666 Mon Sep 17 00:00:00 2001 From: darkweak Date: Wed, 21 Dec 2022 20:15:55 +0100 Subject: [PATCH 2/6] feat(code-quality): move golangci-lint to PR only --- .github/workflows/go_generate_update.yml | 3 --- .github/workflows/releaser.yml | 3 +++ 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/go_generate_update.yml b/.github/workflows/go_generate_update.yml index 8710078d..ecdd54da 100644 --- a/.github/workflows/go_generate_update.yml +++ b/.github/workflows/go_generate_update.yml @@ -35,9 +35,6 @@ jobs: run: | RESULT=$(git status --untracked-files=no --porcelain) echo "gitstatus=$RESULT" >> $GITHUB_OUTPUT - - - name: golangci-lint - uses: golangci/golangci-lint-action@v3 - name: Test if: steps.git.outputs.gitstatus != '' diff --git a/.github/workflows/releaser.yml b/.github/workflows/releaser.yml index db22647a..bf01d479 100644 --- a/.github/workflows/releaser.yml +++ b/.github/workflows/releaser.yml @@ -64,6 +64,9 @@ 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 - name: Test run: go test -v ./... From 4e63324e57914c5d966613be2ee158e0c7b72a6c Mon Sep 17 00:00:00 2001 From: darkweak Date: Wed, 21 Dec 2022 20:34:55 +0100 Subject: [PATCH 3/6] feat(code-quality): add error checks --- book/checkout.go | 28 +++++++++++++++------ book/clone.go | 4 ++- commands/local_proxy_start.go | 8 ++++-- commands/local_server_ca_install.go | 8 ++++-- commands/local_server_ca_uninstall.go | 8 ++++-- commands/local_server_start.go | 36 ++++++++++++++++++++------- local/fcgi_client/fcgiclient.go | 8 ++++-- local/php/composer.go | 4 ++- local/php/fpm.go | 4 ++- local/php/php_builtin_server.go | 4 ++- local/php/platformsh.go | 4 ++- local/runner.go | 8 ++++-- main.go | 5 +++- 13 files changed, 97 insertions(+), 32 deletions(-) diff --git a/book/checkout.go b/book/checkout.go index 1bfb397f..6caa0d4d 100644 --- a/book/checkout.go +++ b/book/checkout.go @@ -35,7 +35,9 @@ 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) + if err := os.Chdir(b.Dir); err != nil { + return err + } step = strings.Replace(step, ".", "-", -1) tag := fmt.Sprintf("step-%s", step) branch := "work-" + tag @@ -117,7 +119,9 @@ func (b *Book) Checkout(step string) error { } 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 err + } printBanner("[WEB] Stopping the Platform.sh tunnel", b.Debug) if err := executeCommand([]string{"symfony", "tunnel:close", "-y"}, b.Debug, true, nil); err != nil { @@ -131,7 +135,9 @@ func (b *Book) Checkout(step string) error { 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 err + } } else { terminal.Println("Skipped for this step") } @@ -237,7 +243,9 @@ 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")) + if err = os.Chdir(filepath.Join(b.Dir, "spa")); err != nil { + return err + } 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 @@ -246,7 +254,9 @@ func (b *Book) Checkout(step string) error { if err := executeCommand(args, b.Debug, false, nil); err != nil { return err } - _ = os.Chdir(b.Dir) + if err = os.Chdir(b.Dir); err != nil { + return err + } } else { terminal.Println("Skipped for this step") } @@ -264,7 +274,9 @@ 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")) + if err = os.Chdir(filepath.Join(b.Dir, "spa")); err != nil { + return err + } 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 { @@ -273,7 +285,9 @@ func (b *Book) Checkout(step string) error { if err := executeCommand(args, b.Debug, false, env); err != nil { return err } - _ = os.Chdir(b.Dir) + if err = os.Chdir(b.Dir); err != nil { + return err + } } else { terminal.Println("Skipped for this step") } diff --git a/book/clone.go b/book/clone.go index 4fc08627..f51d6997 100644 --- a/book/clone.go +++ b/book/clone.go @@ -50,7 +50,9 @@ func (b *Book) Clone(version string) error { } terminal.Println("") - _ = os.Chdir(b.Dir) + if err = os.Chdir(b.Dir); err != nil { + return err + } // checkout the first step by default ui.Section("Getting Ready for the First Step of the Book") if err := b.Checkout("3"); err != nil { diff --git a/commands/local_proxy_start.go b/commands/local_proxy_start.go index 7782bb37..938d34f9 100644 --- a/commands/local_proxy_start.go +++ b/commands/local_proxy_start.go @@ -122,7 +122,9 @@ var localProxyStartCmd = &console.Command{ if c.IsSet("host") { config.Host = c.String("host") - _ = config.Save() + if err = config.Save(); err != nil { + return err + } } spinner := terminal.NewSpinner(terminal.Stderr) @@ -158,7 +160,9 @@ var localProxyStartCmd = &console.Command{ if !c.Bool("foreground") && reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) - _ = reexec.NotifyForeground(reexec.UP) + if err = reexec.NotifyForeground(reexec.UP); err != nil { + return err + } } else { defer func() { _ = pidFile.Remove() diff --git a/commands/local_server_ca_install.go b/commands/local_server_ca_install.go index 3caed935..9a0e3e15 100644 --- a/commands/local_server_ca_install.go +++ b/commands/local_server_ca_install.go @@ -61,8 +61,12 @@ var localServerCAInstallCmd = &console.Command{ return errors.Wrap(err, "failed to load the local Certificate Authority") } if renew && !newCA { - _ = ca.Uninstall() - _ = os.RemoveAll(certsDir) + if err = ca.Uninstall(); err != nil { + return err + } + if err = os.RemoveAll(certsDir); err != nil { + return err + } renew = false goto retry diff --git a/commands/local_server_ca_uninstall.go b/commands/local_server_ca_uninstall.go index f133bfdd..e9d8ce66 100644 --- a/commands/local_server_ca_uninstall.go +++ b/commands/local_server_ca_uninstall.go @@ -49,8 +49,12 @@ 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) + if err = ca.Uninstall(); err != nil { + return err + } + if err = os.RemoveAll(certsDir); err != nil { + return err + } ui.Success("The local Certificate Authority has been uninstalled") return nil }, diff --git a/commands/local_server_start.go b/commands/local_server_start.go index 691827c1..245ee7ba 100644 --- a/commands/local_server_start.go +++ b/commands/local_server_start.go @@ -112,7 +112,9 @@ var localServerStartCmd = &console.Command{ return console.Exit("", 1) } - _ = reexec.NotifyForeground("config") + if err = reexec.NotifyForeground("config"); err != nil { + return err + } config, fileConfig, err := project.NewConfigFromContext(c, projectDir) if err != nil { return errors.WithStack(err) @@ -137,7 +139,9 @@ var localServerStartCmd = &console.Command{ } } - _ = reexec.NotifyForeground("proxy") + if err = reexec.NotifyForeground("proxy"); err != nil { + return err + } proxyConfig, err := proxy.Load(homeDir) if err != nil { return errors.WithStack(err) @@ -148,7 +152,9 @@ var localServerStartCmd = &console.Command{ } } - _ = reexec.NotifyForeground("tls") + if err = reexec.NotifyForeground("tls"); err != nil { + return err + } if !config.NoTLS && config.PKCS12 == "" { ca, err := cert.NewCA(filepath.Join(homeDir, "certs")) if err != nil { @@ -206,11 +212,15 @@ var localServerStartCmd = &console.Command{ errChan := make(chan error, 1) if !reexec.IsChild() { - _ = tailer.Watch(pidFile) + if err = tailer.Watch(pidFile); err != nil { + return err + } } if p.PHPServer != nil { - _ = reexec.NotifyForeground("php") + if err = reexec.NotifyForeground("php"); err != nil { + return err + } phpPidFile, phpStartCallback, err := p.PHPServer.Start(ctx, pidFile) if err != nil { return err @@ -266,7 +276,9 @@ var localServerStartCmd = &console.Command{ } } - _ = reexec.NotifyForeground("http") + if err = reexec.NotifyForeground("http"); err != nil { + return err + } port, err := p.HTTP.Start(errChan) if err != nil { return err @@ -298,7 +310,9 @@ var localServerStartCmd = &console.Command{ return err } - _ = reexec.NotifyForeground("listening") + if err = reexec.NotifyForeground("listening"); err != nil { + return err + } ui.Warning(localWebServerProdWarningMsg) ui.Success(msg) } @@ -310,7 +324,9 @@ var localServerStartCmd = &console.Command{ } if fileConfig != nil { - _ = reexec.NotifyForeground("workers") + if err = reexec.NotifyForeground("workers"); err != nil { + return err + } for name, worker := range fileConfig.Workers { pidFile := pid.New(projectDir, worker.Cmd) if pidFile.IsRunning() { @@ -349,7 +365,9 @@ var localServerStartCmd = &console.Command{ } } - _ = reexec.NotifyForeground(reexec.UP) + if err = reexec.NotifyForeground(reexec.UP); err != nil { + return err + } if reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) } diff --git a/local/fcgi_client/fcgiclient.go b/local/fcgi_client/fcgiclient.go index 5a970c88..f47a45e5 100644 --- a/local/fcgi_client/fcgiclient.go +++ b/local/fcgi_client/fcgiclient.go @@ -336,7 +336,9 @@ 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) + if _, err = io.Copy(body, req); err != nil { + return + } } body.Close() @@ -366,7 +368,9 @@ func (f *FCGIClient) Request(p map[string]string, req io.Reader) (resp *http.Res resp.Header = http.Header(mimeHeader) // TODO: fixTransferEncoding? resp.TransferEncoding = resp.Header["Transfer-Encoding"] - resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64) + if resp.ContentLength, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64); err != nil { + return nil, err + } // status err = errors.WithStack(extractStatus(resp)) diff --git a/local/php/composer.go b/local/php/composer.go index 71d32fba..79df77e7 100644 --- a/local/php/composer.go +++ b/local/php/composer.go @@ -178,7 +178,9 @@ 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") - _ = os.WriteFile(setupPath, installer, 0666) + if err = os.WriteFile(setupPath, installer, 0666); err != nil { + return "", err + } var stdout bytes.Buffer e := &Executor{ diff --git a/local/php/fpm.go b/local/php/fpm.go index ecbce2ff..ee983eb6 100644 --- a/local/php/fpm.go +++ b/local/php/fpm.go @@ -113,7 +113,9 @@ clear_env = no func (p *Server) fpmConfigFile() string { path := filepath.Join(p.homeDir, fmt.Sprintf("php/%s/fpm-%s.ini", name(p.projectDir), p.Version.Version)) if _, err := os.Stat(filepath.Dir(path)); os.IsNotExist(err) { - _ = os.MkdirAll(filepath.Dir(path), 0755) + if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return "" + } } return path } diff --git a/local/php/php_builtin_server.go b/local/php/php_builtin_server.go index 88638d75..90ef3b2d 100644 --- a/local/php/php_builtin_server.go +++ b/local/php/php_builtin_server.go @@ -63,7 +63,9 @@ require $script; func (p *Server) phpRouterFile() string { path := filepath.Join(p.homeDir, fmt.Sprintf("php/%s-router.php", name(p.projectDir))) if _, err := os.Stat(filepath.Dir(path)); os.IsNotExist(err) { - _ = os.MkdirAll(filepath.Dir(path), 0755) + if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return "" + } } return path } diff --git a/local/php/platformsh.go b/local/php/platformsh.go index a1134190..93a62262 100644 --- a/local/php/platformsh.go +++ b/local/php/platformsh.go @@ -45,7 +45,9 @@ func InstallPlatformPhar(home string) error { } installerPath := filepath.Join(home, "platformsh-installer.php") - _ = os.WriteFile(installerPath, installer, 0666) + if err = os.WriteFile(installerPath, installer, 0666); err != nil { + return err + } defer func() { _ = os.Remove(installerPath) }() diff --git a/local/runner.go b/local/runner.go index 0c83d587..bc97eda6 100644 --- a/local/runner.go +++ b/local/runner.go @@ -175,7 +175,9 @@ func (r *Runner) Run() error { timer.Reset(RunnerReliefDuration) if r.mode == RunnerModeLoopDetached { - _ = reexec.NotifyForeground("started") + if err = reexec.NotifyForeground("started"); err != nil { + return err + } } select { @@ -203,7 +205,9 @@ func (r *Runner) Run() error { } if firstBoot && r.mode == RunnerModeLoopDetached { terminal.RemapOutput(cmd.Stdout, cmd.Stderr).SetDecorated(true) - _ = reexec.NotifyForeground(reexec.UP) + if err = reexec.NotifyForeground(reexec.UP); err != nil { + return err + } } firstBoot = false diff --git a/main.go b/main.go index e1bbb476..9f29dbc7 100644 --- a/main.go +++ b/main.go @@ -124,5 +124,8 @@ func main() { Channel: channel, BuildDate: buildDate, } - _ = app.Run(args) + err = app.Run(args) + if err != nil { + panic(err) + } } From 1779fcdf3e38663b172ffb5ab89c09ade1756903 Mon Sep 17 00:00:00 2001 From: darkweak Date: Sun, 15 Jan 2023 22:59:17 +0100 Subject: [PATCH 4/6] fix from tucksaun review --- .github/workflows/releaser.yml | 2 ++ .golangci.yml | 11 ++++++++++ book/reqs.go | 12 +++++------ commands/local_check_security.go | 2 +- commands/local_new.go | 14 ++++++------ commands/local_php_list.go | 2 +- commands/local_proxy_domain_attach.go | 2 +- commands/local_proxy_domain_detach.go | 2 +- commands/local_proxy_start.go | 4 ++-- commands/local_proxy_status.go | 6 +++--- commands/local_run.go | 2 +- commands/local_server_start.go | 12 +++++------ commands/local_server_status.go | 30 +++++++++++++------------- commands/openers.go | 2 +- commands/var_export.go | 4 ++-- local/http/http.go | 4 ++-- local/logs/tailer.go | 12 +++++------ local/php/executor.go | 4 ++-- local/php/executor_test.go | 2 +- local/php/php_server.go | 6 +++--- local/pid/pidfile.go | 2 +- local/platformsh/generator/commands.go | 2 +- local/platformsh/generator/config.go | 2 +- local/proxy/proxy.go | 8 +++---- local/proxy/proxy_test.go | 2 +- local/runner.go | 4 ++-- local/sum.go | 2 +- reexec/process_windows.go | 2 +- 28 files changed, 86 insertions(+), 73 deletions(-) create mode 100644 .golangci.yml diff --git a/.github/workflows/releaser.yml b/.github/workflows/releaser.yml index bf01d479..ad06c64f 100644 --- a/.github/workflows/releaser.yml +++ b/.github/workflows/releaser.yml @@ -67,6 +67,8 @@ jobs: - 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..b3d46505 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,11 @@ +run: + timeout: 30s + issues-exit-code: 1 + +linters: + disable: + # TODO remove these linters and fix the deadcode/errcheck/unused/varcheck + - deadcode + - errcheck + - unused + - varcheck \ No newline at end of file diff --git a/book/reqs.go b/book/reqs.go index 22bb1bc4..c833b2cb 100644 --- a/book/reqs.go +++ b/book/reqs.go @@ -75,13 +75,13 @@ func CheckRequirements() (bool, error) { v, _, _, _ := store.BestVersionForDir(wd) if v == nil { ready = false - _, _ = terminal.Println("[KO] Cannot find PHP, please install it https://php.net/") + terminal.Println("[KO] Cannot find PHP, please install it https://php.net/") } else { if v.FullVersion.GreaterThan(minv) { - _, _ = terminal.Printfln("[OK] PHP installed version %s (%s)", v.FullVersion, v.PHPPath) + terminal.Printfln("[OK] PHP installed version %s (%s)", v.FullVersion, v.PHPPath) } else { ready = false - _, _ = terminal.Printfln("[KO] PHP installed; version %s found but we need version 7.2.5+ (%s)", v.FullVersion, v.PHPPath) + terminal.Printfln("[KO] PHP installed; version %s found but we need version 7.2.5+ (%s)", v.FullVersion, v.PHPPath) } } @@ -110,12 +110,12 @@ func CheckRequirements() (bool, error) { if _, ok := phpexts[ext]; !ok { if reason == "required" { ready = false - _, _ = terminal.Printfln(`[KO] PHP extension "%s" not found, please install it - %s`, ext, reason) + terminal.Printfln(`[KO] PHP extension "%s" not found, please install it - %s`, ext, reason) } else { - _, _ = terminal.Printfln(`[KO] PHP extension "%s" not found, %s`, ext, reason) + terminal.Printfln(`[KO] PHP extension "%s" not found, %s`, ext, reason) } } else { - _, _ = terminal.Printfln(`[OK] PHP extension "%s" installed - %s`, ext, reason) + terminal.Printfln(`[OK] PHP extension "%s" installed - %s`, ext, reason) } } } diff --git a/commands/local_check_security.go b/commands/local_check_security.go index 54b75dcf..bf4223f2 100644 --- a/commands/local_check_security.go +++ b/commands/local_check_security.go @@ -69,7 +69,7 @@ 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) + terminal.Stdout.Write(output) if os.Getenv("GITHUB_WORKSPACE") != "" { gOutFile := os.Getenv("GITHUB_OUTPUT") diff --git a/commands/local_new.go b/commands/local_new.go index a6afbf9f..80dd7756 100644 --- a/commands/local_new.go +++ b/commands/local_new.go @@ -316,24 +316,24 @@ func parseDockerComposeServices(dir string) []*CloudService { } func initProjectGit(c *console.Context, s *terminal.Spinner, dir string) error { - _, _ = terminal.Println("* Setting up the project under Git version control") - _, _ = terminal.Printfln(" (running git init %s)\n", dir) + terminal.Println("* Setting up the project under Git version control") + terminal.Printfln(" (running git init %s)\n", dir) // Only force the branch to be "main" when running a Cloud context to make // onboarding simpler. if buf, err := git.Init(dir, c.Bool("cloud"), c.Bool("debug")); err != nil { - _, _ = fmt.Print(buf.String()) + fmt.Print(buf.String()) return err } buf, err := git.AddAndCommit(dir, []string{"."}, "Add initial set of files", c.Bool("debug")) if err != nil { - _, _ = fmt.Print(buf.String()) + fmt.Print(buf.String()) } return err } func createProjectWithComposer(c *console.Context, dir, version string) error { if c.Bool("demo") { - _, _ = terminal.Println("* Creating a new Symfony Demo project with Composer") + terminal.Println("* Creating a new Symfony Demo project with Composer") } else if version != "" { if version == "lts" || version == "previous" || version == "stable" || version == "next" || version == "dev" { var err error @@ -343,9 +343,9 @@ func createProjectWithComposer(c *console.Context, dir, version string) error { } } - _, _ = terminal.Printfln("* Creating a new Symfony %s project with Composer", version) + terminal.Printfln("* Creating a new Symfony %s project with Composer", version) } else { - _, _ = terminal.Println("* Creating a new Symfony project with Composer") + terminal.Println("* Creating a new Symfony project with Composer") } repo := "symfony/skeleton" diff --git a/commands/local_php_list.go b/commands/local_php_list.go index ced939ef..b570e639 100644 --- a/commands/local_php_list.go +++ b/commands/local_php_list.go @@ -54,7 +54,7 @@ var localPhpListCmd = &console.Command{ currentPHPPath := "" v, source, warning, _ := phpStore.BestVersionForDir(wd) if warning != "" { - _, _ = terminal.Eprintfln("WARNING %s", warning) + terminal.Eprintfln("WARNING %s", warning) } if v != nil { currentPHPPath = v.PHPPath diff --git a/commands/local_proxy_domain_attach.go b/commands/local_proxy_domain_attach.go index bfcf0908..ea37acf7 100644 --- a/commands/local_proxy_domain_attach.go +++ b/commands/local_proxy_domain_attach.go @@ -53,7 +53,7 @@ var localProxyAttachDomainCmd = &console.Command{ } terminal.Println("The proxy is now configured with the following domains for this directory:") for _, domain := range config.GetDomains(projectDir) { - _, _ = terminal.Printfln(" * http://%s", domain) + terminal.Printfln(" * http://%s", domain) } return nil }, diff --git a/commands/local_proxy_domain_detach.go b/commands/local_proxy_domain_detach.go index 2fa48ef7..45783544 100644 --- a/commands/local_proxy_domain_detach.go +++ b/commands/local_proxy_domain_detach.go @@ -46,7 +46,7 @@ var localProxyDetachDomainCmd = &console.Command{ } terminal.Println("The following domains are not defined anymore on the proxy:") for _, domain := range domains { - _, _ = terminal.Printfln(" * http://%s", domain) + terminal.Printfln(" * http://%s", domain) } return nil }, diff --git a/commands/local_proxy_start.go b/commands/local_proxy_start.go index 938d34f9..23137958 100644 --- a/commands/local_proxy_start.go +++ b/commands/local_proxy_start.go @@ -70,8 +70,8 @@ var localProxyStartCmd = &console.Command{ if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - _, _ = terminal.Printfln("Impossible to go to the background: %s", err) - _, _ = terminal.Println("Continue in foreground") + terminal.Printfln("Impossible to go to the background: %s", err) + terminal.Println("Continue in foreground") } else { return nil } diff --git a/commands/local_proxy_status.go b/commands/local_proxy_status.go index a97f8b4a..a2015d50 100644 --- a/commands/local_proxy_status.go +++ b/commands/local_proxy_status.go @@ -42,10 +42,10 @@ var localProxyStatusCmd = &console.Command{ return nil } - _, _ = terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) + terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) - _, _ = terminal.Println() - _, _ = terminal.Println("Configured Web Servers") + terminal.Println() + terminal.Println("Configured Web Servers") return printConfiguredServers() }, } diff --git a/commands/local_run.go b/commands/local_run.go index 7b195762..6a89f769 100644 --- a/commands/local_run.go +++ b/commands/local_run.go @@ -86,7 +86,7 @@ var localRunCmd = &console.Command{ if err := runner.Run(); err != nil { if _, wentToBackground := err.(local.RunnerWentToBackground); wentToBackground { - _, _ = terminal.Printfln("Stream the logs via %s server:log", c.App.HelpName) + terminal.Printfln("Stream the logs via %s server:log", c.App.HelpName) return nil } diff --git a/commands/local_server_start.go b/commands/local_server_start.go index 245ee7ba..f3482df2 100644 --- a/commands/local_server_start.go +++ b/commands/local_server_start.go @@ -130,11 +130,11 @@ var localServerStartCmd = &console.Command{ if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - _, _ = terminal.Eprintln("Impossible to go to the background") - _, _ = terminal.Eprintln("Continue in foreground") + terminal.Eprintln("Impossible to go to the background") + terminal.Eprintln("Continue in foreground") config.Daemon = false } else { - _, _ = terminal.Eprintfln("Stream the logs via %s server:log", c.App.HelpName) + terminal.Eprintfln("Stream the logs via %s server:log", c.App.HelpName) return nil } } @@ -330,7 +330,7 @@ var localServerStartCmd = &console.Command{ for name, worker := range fileConfig.Workers { pidFile := pid.New(projectDir, worker.Cmd) if pidFile.IsRunning() { - _, _ = terminal.Eprintfln("WARNING Unable to start worker \"%s\": it is already running for this project as PID %d", name, pidFile.Pid) + terminal.Eprintfln("WARNING Unable to start worker \"%s\": it is already running for this project as PID %d", name, pidFile.Pid) continue } pidFile.Watched = worker.Watch @@ -341,7 +341,7 @@ var localServerStartCmd = &console.Command{ go func(name string, pidFile *pid.PidFile) { runner, err := local.NewRunner(pidFile, local.RunnerModeLoopAttached) if err != nil { - _, _ = terminal.Eprintfln("WARNING Unable to start worker \"%s\": %s", name, err) + terminal.Eprintfln("WARNING Unable to start worker \"%s\": %s", name, err) return } @@ -359,7 +359,7 @@ var localServerStartCmd = &console.Command{ ui.Success(fmt.Sprintf("Started worker \"%s\"", name)) if err := runner.Run(); err != nil { - _, _ = terminal.Eprintfln("WARNING Worker \"%s\" exited with an error: %s", name, err) + terminal.Eprintfln("WARNING Worker \"%s\" exited with an error: %s", name, err) } }(name, pidFile) } diff --git a/commands/local_server_status.go b/commands/local_server_status.go index 9d01ea02..13936caf 100644 --- a/commands/local_server_status.go +++ b/commands/local_server_status.go @@ -55,47 +55,47 @@ func printWebServerStatus(projectDir string) error { workers := pid.AllWorkers(projectDir) // web server - _, _ = terminal.Println("Local Web Server") + terminal.Println("Local Web Server") if !pidFile.IsRunning() { - _, _ = terminal.Println(" Not Running") + terminal.Println(" Not Running") } else { - _, _ = terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) + terminal.Printfln(" Listening on %s://127.0.0.1:%d", pidFile.Scheme, pidFile.Port, pidFile.Scheme, pidFile.Port) homeDir := util.GetHomeDir() phpStore := phpstore.New(homeDir, true, nil) version, source, warning, err := phpStore.BestVersionForDir(projectDir) if err == nil { - _, _ = terminal.Printfln(" The Web server is using %s %s (from %s)", version.ServerTypeName(), version.Version, source) + terminal.Printfln(" The Web server is using %s %s (from %s)", version.ServerTypeName(), version.Version, source) if warning != "" { - _, _ = terminal.Printfln(" WARNING %s", warning) + terminal.Printfln(" WARNING %s", warning) } } - _, _ = terminal.Println() - _, _ = terminal.Println("Local Domains") + terminal.Println() + terminal.Println("Local Domains") if proxyConf, err := proxy.Load(util.GetHomeDir()); err == nil { for _, domain := range proxyConf.GetDomains(projectDir) { - _, _ = terminal.Printfln(" %s://%s", pidFile.Scheme, domain, pidFile.Scheme, domain) + terminal.Printfln(" %s://%s", pidFile.Scheme, domain, pidFile.Scheme, domain) } } } // workers - _, _ = terminal.Println() - _, _ = terminal.Println("Workers") + terminal.Println() + terminal.Println("Workers") if len(workers) == 0 { - _, _ = terminal.Println(" No Workers") + terminal.Println(" No Workers") } else { for _, p := range workers { msg := fmt.Sprintf(` PID %d: %s`, p.Pid, p.Command()) if len(p.Watched) > 0 { msg += fmt.Sprintf(" (watching %s/)", strings.Join(p.Watched, "/, ")) } - _, _ = terminal.Println(msg) + terminal.Println(msg) } } // env vars - _, _ = terminal.Println() - _, _ = terminal.Println("Environment Variables") + terminal.Println() + terminal.Println("Environment Variables") data, err := envs.GetEnv(projectDir, terminal.IsDebug()) if err != nil { return err @@ -108,7 +108,7 @@ func printWebServerStatus(projectDir string) error { if env["SYMFONY_DOCKER_ENV"] == "1" && env["SYMFONY_TUNNEL_ENV"] == "" { envVars = `Exposed from Docker` } - _, _ = terminal.Printfln(" %s", envVars) + terminal.Printfln(" %s", envVars) return nil } diff --git a/commands/openers.go b/commands/openers.go index 72377679..3607e5d1 100644 --- a/commands/openers.go +++ b/commands/openers.go @@ -153,6 +153,6 @@ func abstractOpenCmd(url string) { terminal.Eprintln("Error while opening:", err, "") terminal.Eprintfln("Please visit %s manually.", url, url) } else { - _, _ = terminal.Eprintfln("Opened: %s", url, url) + terminal.Eprintfln("Opened: %s", url, url) } } diff --git a/commands/var_export.go b/commands/var_export.go index 3651715f..d17c0574 100644 --- a/commands/var_export.go +++ b/commands/var_export.go @@ -70,11 +70,11 @@ var variableExportCmd = &console.Command{ } sort.Strings(keys) for _, k := range keys { - _, _ = terminal.Printfln("export %s=%s", k, m[k]) + terminal.Printfln("export %s=%s", k, m[k]) } } else { // output the string (useful when doing export $(envs)) - _, _ = terminal.Print(envs.AsString(env)) + terminal.Print(envs.AsString(env)) } return nil diff --git a/local/http/http.go b/local/http/http.go index ca3e74d9..43e09e67 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/logs/tailer.go b/local/logs/tailer.go index a55db3a8..a5f05ed8 100644 --- a/local/logs/tailer.go +++ b/local/logs/tailer.go @@ -112,7 +112,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { } p, err := pid.Load(e.Path()) if err != nil { - _, _ = terminal.Printfln("WARNING %s", err) + terminal.Printfln("WARNING %s", err) continue } tailer.pidFileChan <- p @@ -179,7 +179,7 @@ func (tailer *Tailer) Watch(pidFile *pid.PidFile) error { go func() { tsf, err := tailFile(applog, tailer.Follow, tailer.LinesNb) if err != nil { - _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", applog, err) + terminal.Printfln("WARNING %s log file cannot be tailed: %s", applog, err) return } for line := range tsf.Lines { @@ -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()) } } @@ -229,15 +229,15 @@ func (tailer Tailer) WatchAdditionalPidFile(file *pid.PidFile) { func tailLogFile(p *pid.PidFile, lines chan *namedLine, follow bool, nblines int64) { if err := p.WaitForLogs(); err != nil { - _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) + terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) return } t, err := tailFile(p.LogFile(), follow, nblines) if err != nil { - _, _ = terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) + terminal.Printfln("WARNING %s log file cannot be tailed: %s", p.String(), err) return } - _, _ = terminal.Printfln("Following %s log file (%s)", p.String(), p.LogFile()) + terminal.Printfln("Following %s log file (%s)", p.String(), p.LogFile()) for line := range t.Lines { lines <- &namedLine{name: p.ShortName(), line: line} } diff --git a/local/php/executor.go b/local/php/executor.go index 085aa89c..1e0bb050 100644 --- a/local/php/executor.go +++ b/local/php/executor.go @@ -77,7 +77,7 @@ func (e *Executor) lookupPHP(cliDir string, forceReload bool) (*phpstore.Version phpStore := phpstore.New(cliDir, forceReload, nil) v, source, warning, err := phpStore.BestVersionForDir(e.scriptDir) if warning != "" { - _, _ = terminal.Eprintfln("WARNING %s", warning) + terminal.Eprintfln("WARNING %s", warning) } if err != nil { return nil, "", true, err @@ -400,7 +400,7 @@ func LookPath(file string) (string, error) { wd, _ := os.Getwd() v, _, warning, _ := phpStore.BestVersionForDir(wd) if warning != "" { - _, _ = terminal.Eprintfln("WARNING %s", warning) + terminal.Eprintfln("WARNING %s", warning) } if v == nil { // unable to find the current PHP version, fall back diff --git a/local/php/executor_test.go b/local/php/executor_test.go index 175d4655..12baf97b 100644 --- a/local/php/executor_test.go +++ b/local/php/executor_test.go @@ -54,7 +54,7 @@ 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() { diff --git a/local/php/php_server.go b/local/php/php_server.go index 62e1f675..2663d102 100644 --- a/local/php/php_server.go +++ b/local/php/php_server.go @@ -139,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()), ""))) } } @@ -279,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/pid/pidfile.go b/local/pid/pidfile.go index 86cea1fe..c655ccdd 100644 --- a/local/pid/pidfile.go +++ b/local/pid/pidfile.go @@ -316,7 +316,7 @@ 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)) } diff --git a/local/platformsh/generator/commands.go b/local/platformsh/generator/commands.go index 23f017fa..d091bd38 100644 --- a/local/platformsh/generator/commands.go +++ b/local/platformsh/generator/commands.go @@ -105,7 +105,7 @@ func generateCommands() { if err != nil { panic(err) } - _, _ = f.Write(buf.Bytes()) + f.Write(buf.Bytes()) } diff --git a/local/platformsh/generator/config.go b/local/platformsh/generator/config.go index 107e3836..b01e31f2 100644 --- a/local/platformsh/generator/config.go +++ b/local/platformsh/generator/config.go @@ -83,7 +83,7 @@ func generateConfig() { if err != nil { panic(err) } - _, _ = f.Write(buf.Bytes()) + f.Write(buf.Bytes()) } func parseServices() (string, error) { diff --git a/local/proxy/proxy.go b/local/proxy/proxy.go index ac024443..afad4d91 100644 --- a/local/proxy/proxy.go +++ b/local/proxy/proxy.go @@ -77,13 +77,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 } @@ -321,7 +321,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')) { @@ -372,5 +372,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 029a51f3..53f2ae48 100644 --- a/local/proxy/proxy_test.go +++ b/local/proxy/proxy_test.go @@ -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) diff --git a/local/runner.go b/local/runner.go index bc97eda6..08790fd2 100644 --- a/local/runner.go +++ b/local/runner.go @@ -93,8 +93,8 @@ func (r *Runner) Run() error { if _, isExitCoder := err.(console.ExitCoder); isExitCoder { return err } - _, _ = terminal.Printfln("Impossible to go to the background: %s", err) - _, _ = terminal.Println("Continue in foreground") + terminal.Printfln("Impossible to go to the background: %s", err) + terminal.Println("Continue in foreground") r.mode = RunnerModeOnce } else { if err := reexec.NotifyForeground("boot"); err != nil { diff --git a/local/sum.go b/local/sum.go index 4e747014..2a603b38 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/reexec/process_windows.go b/reexec/process_windows.go index f1ea0352..041ab105 100644 --- a/reexec/process_windows.go +++ b/reexec/process_windows.go @@ -46,7 +46,7 @@ func Getppid() int { } func waitForProcess(ps *os.Process) { - _, _ = ps.Wait() + ps.Wait() return } From 90ab8cb4d55814d539329cf1d19ae8770cbb8134 Mon Sep 17 00:00:00 2001 From: darkweak Date: Tue, 14 Feb 2023 10:04:27 +0100 Subject: [PATCH 5/6] fix: review from tucksaun, wrap errors --- .golangci.yml | 17 +++++--- book/checkout.go | 54 +++++++++++++------------- book/clone.go | 6 +-- book/reqs.go | 4 +- commands/book_check_reqs.go | 3 +- commands/book_checkout.go | 7 ++-- commands/init_templating.go | 2 +- commands/init_templating_php.go | 11 +++--- commands/local_check_requirements.go | 7 ++-- commands/local_check_security.go | 2 +- commands/local_new.go | 46 +++++++++++----------- commands/local_proxy_domain_attach.go | 7 ++-- commands/local_proxy_domain_detach.go | 5 ++- commands/local_proxy_start.go | 14 +++---- 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 | 50 ++++++++++++------------ commands/local_server_status.go | 5 ++- commands/local_server_stop.go | 5 ++- commands/local_var_expose.go | 5 ++- commands/openers.go | 11 +++--- commands/platformsh.go | 7 ++-- commands/platformsh_hooks.go | 5 ++- commands/project_init.go | 11 +++--- commands/root.go | 8 ++-- commands/var_export.go | 4 +- envs/local_tunnel.go | 10 ++--- envs/url.go | 6 +-- git/branches.go | 4 +- git/exec.go | 2 +- git/remote.go | 2 +- humanlog/handler.go | 2 +- inotify/inotify.go | 11 +++++- local/fcgi_client/fcgiclient.go | 10 ++--- local/http/http.go | 4 +- local/http/push.go | 2 +- local/http/response_proxy.go | 3 +- local/logs/tailer.go | 10 +++-- local/php/composer.go | 24 +++++++----- local/php/executor.go | 35 ++++++++++------- local/php/executor_posix.go | 4 +- local/php/executor_test.go | 2 +- local/php/executor_windows.go | 6 +-- local/php/php_server.go | 14 +++---- local/php/platformsh.go | 10 ++--- local/pid/pidfile.go | 22 +++++------ local/pid/pidfile_other.go | 10 +++-- local/platformsh/generator/commands.go | 4 +- local/platformsh/generator/config.go | 19 ++++----- local/process/port.go | 6 ++- local/process/process_other.go | 4 +- local/project/config.go | 6 +-- local/project/project.go | 2 +- local/proxy/cert_store.go | 3 +- local/proxy/config.go | 2 +- local/proxy/proxy.go | 17 ++++---- local/proxy/proxy_test.go | 2 +- local/runner.go | 12 +++--- local/sum.go | 2 +- reexec/process_windows.go | 2 +- reexec/reexec.go | 8 ++-- updater/updater.go | 4 +- 66 files changed, 335 insertions(+), 275 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b3d46505..26348e3b 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,9 +3,14 @@ run: issues-exit-code: 1 linters: - disable: - # TODO remove these linters and fix the deadcode/errcheck/unused/varcheck - - deadcode - - errcheck - - unused - - varcheck \ No newline at end of file + 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 \ No newline at end of file diff --git a/book/checkout.go b/book/checkout.go index 6caa0d4d..e036c1e1 100644 --- a/book/checkout.go +++ b/book/checkout.go @@ -36,7 +36,7 @@ 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 if err := os.Chdir(b.Dir); err != nil { - return err + return errors.WithStack(err) } step = strings.Replace(step, ".", "-", -1) tag := fmt.Sprintf("step-%s", step) @@ -82,21 +82,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 { @@ -112,7 +112,7 @@ 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") @@ -120,23 +120,23 @@ func (b *Book) Checkout(step string) error { printBanner("[WEB] Stopping the Local Web Server", b.Debug) if err = executeCommand([]string{"symfony", "server:stop"}, b.Debug, true, nil); err != nil { - return err + return errors.WithStack(err) } 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 { if err = executeCommand([]string{"symfony", "server:stop", "--dir", filepath.Join(b.Dir, "spa")}, b.Debug, true, nil); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -144,12 +144,12 @@ func (b *Book) Checkout(step string) error { 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 { @@ -159,7 +159,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 { @@ -185,7 +185,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") @@ -194,7 +194,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") @@ -208,7 +208,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") @@ -221,7 +221,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") @@ -229,13 +229,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") @@ -244,7 +244,7 @@ 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 { if err = os.Chdir(filepath.Join(b.Dir, "spa")); err != nil { - return err + return errors.WithStack(err) } args := []string{"npm", "install"} if _, err := os.Stat(filepath.Join(b.Dir, "yarn.lock")); err == nil { @@ -252,10 +252,10 @@ 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) } if err = os.Chdir(b.Dir); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -275,7 +275,7 @@ func (b *Book) Checkout(step string) error { return errors.Errorf("unable to get the URL of the local web server:\n%s\n%s", stderr.String(), endpoint.String()) } if err = os.Chdir(filepath.Join(b.Dir, "spa")); err != nil { - return err + return errors.WithStack(err) } env := append(os.Environ(), "API_ENDPOINT="+endpoint.String()) args := []string{"npx", "encore", "dev"} @@ -283,10 +283,10 @@ func (b *Book) Checkout(step string) error { args = []string{"yarn", "encore", "dev"} } if err := executeCommand(args, b.Debug, false, env); err != nil { - return err + return errors.WithStack(err) } if err = os.Chdir(b.Dir); err != nil { - return err + return errors.WithStack(err) } } else { terminal.Println("Skipped for this step") @@ -295,7 +295,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") @@ -336,7 +336,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 f51d6997..7462ffd6 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 { @@ -51,7 +51,7 @@ func (b *Book) Clone(version string) error { terminal.Println("") if err = os.Chdir(b.Dir); err != nil { - return err + return errors.WithStack(err) } // checkout the first step by default ui.Section("Getting Ready for the First Step of the Book") @@ -61,7 +61,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 c833b2cb..23a1c7cd 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 b1abe10f..711fabb0 100644 --- a/commands/init_templating.go +++ b/commands/init_templating.go @@ -198,7 +198,7 @@ func getTemplates(rootDirectory, chosenTemplateName string, minorPHPVersion stri 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) diff --git a/commands/init_templating_php.go b/commands/init_templating_php.go index 595449cc..6182da7f 100644 --- a/commands/init_templating_php.go +++ b/commands/init_templating_php.go @@ -26,6 +26,7 @@ import ( "path/filepath" "strings" + "github.com/pkg/errors" "github.com/symfony-cli/terminal" ) @@ -160,16 +161,16 @@ type composerLock struct { func parseComposerLock(directory string) (*composerLock, error) { 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 { @@ -183,12 +184,12 @@ type composerJSON struct { func parseComposerJSON(directory string) (*composerJSON, error) { 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 44489a58..5d085e71 100644 --- a/commands/local_check_requirements.go +++ b/commands/local_check_requirements.go @@ -24,6 +24,7 @@ import ( "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" @@ -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 := os.WriteFile(cachePath, phpChecker, 0600); err != nil { - return err + return errors.WithStack(err) } args := []string{"php", cachePath} diff --git a/commands/local_check_security.go b/commands/local_check_security.go index bf4223f2..54b75dcf 100644 --- a/commands/local_check_security.go +++ b/commands/local_check_security.go @@ -69,7 +69,7 @@ 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) + _, _ = terminal.Stdout.Write(output) if os.Getenv("GITHUB_WORKSPACE") != "" { gOutFile := os.Getenv("GITHUB_OUTPUT") diff --git a/commands/local_new.go b/commands/local_new.go index 80dd7756..d398ab99 100644 --- a/commands/local_new.go +++ b/commands/local_new.go @@ -140,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) } } @@ -199,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() @@ -207,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 { @@ -215,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 @@ -322,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 { @@ -339,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) } } @@ -384,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 } @@ -392,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 := 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) @@ -419,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 23137958..e85e2de0 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())) @@ -117,13 +117,13 @@ var localProxyStartCmd = &console.Command{ config, err := proxy.Load(homeDir) if err != nil { - return err + return errors.WithStack(err) } if c.IsSet("host") { config.Host = c.String("host") if err = config.Save(); err != nil { - return err + return errors.WithStack(err) } } @@ -147,7 +147,7 @@ var localProxyStartCmd = &console.Command{ case err := <-errChan: if err != nil { timer.Stop() - return err + return errors.WithStack(err) } case <-timer.C: spinner.Stop() @@ -155,13 +155,13 @@ 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) if err = reexec.NotifyForeground(reexec.UP); err != nil { - return err + return errors.WithStack(err) } } else { defer func() { 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 9a0e3e15..4a6ebf04 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") @@ -62,10 +62,10 @@ var localServerCAInstallCmd = &console.Command{ } if renew && !newCA { if err = ca.Uninstall(); err != nil { - return err + return errors.WithStack(err) } if err = os.RemoveAll(certsDir); err != nil { - return err + return errors.WithStack(err) } renew = false diff --git a/commands/local_server_ca_uninstall.go b/commands/local_server_ca_uninstall.go index e9d8ce66..8495b37f 100644 --- a/commands/local_server_ca_uninstall.go +++ b/commands/local_server_ca_uninstall.go @@ -50,10 +50,10 @@ var localServerCAUninstallCmd = &console.Command{ return errors.Wrap(err, "failed to load the local Certificate Authority") } if err = ca.Uninstall(); err != nil { - return err + return errors.WithStack(err) } if err = os.RemoveAll(certsDir); err != nil { - return err + return errors.WithStack(err) } 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 f3482df2..7736f7d5 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() @@ -113,7 +113,7 @@ var localServerStartCmd = &console.Command{ } if err = reexec.NotifyForeground("config"); err != nil { - return err + return errors.WithStack(err) } config, fileConfig, err := project.NewConfigFromContext(c, projectDir) if err != nil { @@ -128,7 +128,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") @@ -140,7 +140,7 @@ var localServerStartCmd = &console.Command{ } if err = reexec.NotifyForeground("proxy"); err != nil { - return err + return errors.WithStack(err) } proxyConfig, err := proxy.Load(homeDir) if err != nil { @@ -153,7 +153,7 @@ var localServerStartCmd = &console.Command{ } if err = reexec.NotifyForeground("tls"); err != nil { - return err + return errors.WithStack(err) } if !config.NoTLS && config.PKCS12 == "" { ca, err := cert.NewCA(filepath.Join(homeDir, "certs")) @@ -192,12 +192,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()) @@ -213,17 +213,17 @@ var localServerStartCmd = &console.Command{ if !reexec.IsChild() { if err = tailer.Watch(pidFile); err != nil { - return err + return errors.WithStack(err) } } if p.PHPServer != nil { if err = reexec.NotifyForeground("php"); err != nil { - return err + return errors.WithStack(err) } 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 @@ -231,7 +231,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() { @@ -264,24 +264,24 @@ 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) } } } if err = reexec.NotifyForeground("http"); err != nil { - return err + return errors.WithStack(err) } port, err := p.HTTP.Start(errChan) if err != nil { - return err + return errors.WithStack(err) } scheme := "https" @@ -303,15 +303,15 @@ 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) } if err = reexec.NotifyForeground("listening"); err != nil { - return err + return errors.WithStack(err) } ui.Warning(localWebServerProdWarningMsg) ui.Success(msg) @@ -325,7 +325,7 @@ var localServerStartCmd = &console.Command{ if fileConfig != nil { if err = reexec.NotifyForeground("workers"); err != nil { - return err + return errors.WithStack(err) } for name, worker := range fileConfig.Workers { pidFile := pid.New(projectDir, worker.Cmd) @@ -366,7 +366,7 @@ var localServerStartCmd = &console.Command{ } if err = reexec.NotifyForeground(reexec.UP); err != nil { - return err + return errors.WithStack(err) } if reexec.IsChild() { terminal.RemapOutput(lw, lw).SetDecorated(true) @@ -374,12 +374,12 @@ var localServerStartCmd = &console.Command{ 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") @@ -397,10 +397,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 3607e5d1..b20d42ff 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" @@ -46,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() { @@ -78,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 { @@ -103,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 { 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 0a6e17d6..bd1de463 100644 --- a/commands/root.go +++ b/commands/root.go @@ -150,7 +150,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("") @@ -186,8 +186,10 @@ 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) + link, e := filepath.EvalSymlinks(dir) + + return link, errors.WithStack(e) } 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/local_tunnel.go b/envs/local_tunnel.go index bf35a2f9..bb5767d7 100644 --- a/envs/local_tunnel.go +++ b/envs/local_tunnel.go @@ -30,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" ) @@ -116,17 +117,16 @@ 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) - return nil + return errors.WithStack(os.Remove(path)) } // Path returns the path to the Platform.sh local tunnel state file 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/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/inotify/inotify.go b/inotify/inotify.go index 68394c3b..12b69b47 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,9 @@ func Stop(c chan<- EventInfo) { } func simpleWatch(path string, c chan<- EventInfo, events ...notify.Event) error { - return notify.Watch(path, c, events...) + if err := notify.Watch(path, c, events...); err != nil { + return errors.WithStack(err) + } + + return nil } diff --git a/local/fcgi_client/fcgiclient.go b/local/fcgi_client/fcgiclient.go index f47a45e5..2a0255ca 100644 --- a/local/fcgi_client/fcgiclient.go +++ b/local/fcgi_client/fcgiclient.go @@ -255,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 { @@ -363,19 +363,19 @@ 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? resp.TransferEncoding = resp.Header["Transfer-Encoding"] if resp.ContentLength, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64); err != nil { - return nil, err + return nil, errors.WithStack(err) } // status err = errors.WithStack(extractStatus(resp)) if err != nil { - return nil, err + return nil, errors.WithStack(err) } if chunked(resp.TransferEncoding) { @@ -437,7 +437,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 43e09e67..ca3e74d9 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..f831fdfc 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() + conn, buf, err := hj.Hijack() + return conn, buf, 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 a5f05ed8..d6f2f96f 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.WithStack(err) } 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.WithStack(err) } 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,7 +250,7 @@ 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{ + t, e := tail.TailFile(filename, tail.Config{ Location: &tail.SeekInfo{ Offset: pos, Whence: io.SeekStart, @@ -260,6 +260,8 @@ func tailFile(filename string, follow bool, nblines int64) (*tail.Tail, error) { Poll: true, Logger: tail.DiscardingLogger, }) + + return t, errors.WithStack(e) } // 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 79df77e7..1564312e 100644 --- a/local/php/composer.go +++ b/local/php/composer.go @@ -154,7 +154,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 { @@ -163,11 +163,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) @@ -179,7 +179,7 @@ func downloadComposer(dir string) (string, error) { } setupPath := filepath.Join(dir, "composer-setup.php") if err = os.WriteFile(setupPath, installer, 0666); err != nil { - return "", err + return "", errors.WithStack(err) } var stdout bytes.Buffer @@ -196,10 +196,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 @@ -208,17 +208,21 @@ 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 io.ReadAll(resp.Body) + b, e := io.ReadAll(resp.Body) + + return b, errors.WithStack(e) } 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 io.ReadAll(resp.Body) + b, e := io.ReadAll(resp.Body) + + return b, errors.WithStack(e) } diff --git a/local/php/executor.go b/local/php/executor.go index 1e0bb050..51f699a2 100644 --- a/local/php/executor.go +++ b/local/php/executor.go @@ -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 @@ -394,7 +394,9 @@ 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) + path, err := exec.LookPath(file) + + return path, errors.WithStack(err) } phpStore := phpstore.New(util.GetHomeDir(), false, nil) wd, _ := os.Getwd() @@ -404,21 +406,26 @@ func LookPath(file string) (string, error) { } if v == nil { // unable to find the current PHP version, fall back - return exec.LookPath(file) + path, err := exec.LookPath(file) + + return path, 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) + path, err := exec.LookPath(file) + return path, 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) + path, err = exec.LookPath(file) + + return path, 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 12baf97b..175d4655 100644 --- a/local/php/executor_test.go +++ b/local/php/executor_test.go @@ -54,7 +54,7 @@ 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() { diff --git a/local/php/executor_windows.go b/local/php/executor_windows.go index f5145733..12961bd8 100644 --- a/local/php/executor_windows.go +++ b/local/php/executor_windows.go @@ -31,14 +31,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 2663d102..8ecf920c 100644 --- a/local/php/php_server.go +++ b/local/php/php_server.go @@ -70,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{ @@ -139,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()), ""))) } } @@ -168,7 +168,7 @@ func (p *Server) Start(ctx context.Context, pidFile *pid.PidFile) (*pid.PidFile, cmd.Dir = workingDir if err = e.Config(false); err != nil { - return err + return errors.WithStack(err) } cmd.Env = append(cmd.Env, e.environ...) @@ -206,7 +206,7 @@ func (p *Server) Serve(w http.ResponseWriter, r *http.Request, env map[string]st } 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() @@ -260,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 } @@ -279,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 93a62262..59783835 100644 --- a/local/php/platformsh.go +++ b/local/php/platformsh.go @@ -18,7 +18,7 @@ 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") @@ -36,17 +36,17 @@ 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 := io.ReadAll(resp.Body) if err != nil { - return err + return errors.WithStack(err) } installerPath := filepath.Join(home, "platformsh-installer.php") if err = os.WriteFile(installerPath, installer, 0666); err != nil { - return err + return errors.WithStack(err) } defer func() { _ = os.Remove(installerPath) @@ -66,5 +66,5 @@ func InstallPlatformPhar(home string) error { return errors.Errorf("unable to setup platformsh CLI: %s", stdout.String()) } - return os.WriteFile(versionPath, internalVersion, 0644) + return errors.WithStack(os.WriteFile(versionPath, internalVersion, 0644)) } diff --git a/local/pid/pidfile.go b/local/pid/pidfile.go index c655ccdd..6e6b7795 100644 --- a/local/pid/pidfile.go +++ b/local/pid/pidfile.go @@ -73,11 +73,11 @@ func New(dir string, args []string) *PidFile { func Load(path string) (*PidFile, error) { 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 @@ -150,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") @@ -191,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 } @@ -203,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 } @@ -246,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 os.WriteFile(p.path, b, 0644) + return errors.WithStack(os.WriteFile(p.path, b, 0644)) } // Stop kills the current process @@ -316,7 +316,7 @@ 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)) } 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/generator/commands.go b/local/platformsh/generator/commands.go index d091bd38..2e036413 100644 --- a/local/platformsh/generator/commands.go +++ b/local/platformsh/generator/commands.go @@ -105,7 +105,7 @@ func generateCommands() { if err != nil { panic(err) } - f.Write(buf.Bytes()) + _, _ = f.Write(buf.Bytes()) } @@ -134,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 b01e31f2..fecc05e3 100644 --- a/local/platformsh/generator/config.go +++ b/local/platformsh/generator/config.go @@ -14,6 +14,7 @@ import ( "text/template" "github.com/hashicorp/go-version" + "github.com/pkg/errors" ) type service struct { @@ -83,22 +84,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 := 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 { @@ -111,11 +112,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" @@ -141,7 +142,7 @@ func parseServices() (string, error) { func parsePHPExtensions() (string, error) { resp, err := http.Get("https://raw.githubusercontent.com/platformsh/platformsh-docs/master/docs/src/languages/php/extensions.md") if err != nil { - return "", err + return "", errors.WithStack(err) } defer resp.Body.Close() var versions []string @@ -179,7 +180,7 @@ func parsePHPExtensions() (string, error) { } } if err := scanner.Err(); err != nil { - return "", err + return "", errors.WithStack(err) } maxNameLen := 0 for name := range extensions { @@ -228,7 +229,7 @@ func sortVersions(versions []string) ([]string, error) { 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/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_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 c5d3767b..dcfa1cbb 100644 --- a/local/project/config.go +++ b/local/project/config.go @@ -122,16 +122,16 @@ func newConfigFromFile(configFile string) (*FileConfig, error) { 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 635a6e0d..32163788 100644 --- a/local/project/project.go +++ b/local/project/project.go @@ -78,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 } diff --git a/local/proxy/cert_store.go b/local/proxy/cert_store.go index b015d89b..80e0599a 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" + "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 60b53179..8e39ab4a 100644 --- a/local/proxy/config.go +++ b/local/proxy/config.go @@ -101,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 { diff --git a/local/proxy/proxy.go b/local/proxy/proxy.go index afad4d91..2ade75f6 100644 --- a/local/proxy/proxy.go +++ b/local/proxy/proxy.go @@ -57,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) + conn, err := proxy.ConnectDial(network, addr) + return conn, errors.WithStack(err) } if proxy.Tr.DialContext != nil { - return proxy.Tr.DialContext(context.Background(), network, addr) + conn, err := proxy.Tr.DialContext(context.Background(), network, addr) + return conn, errors.WithStack(err) } - return net.Dial(network, addr) + conn, err := net.Dial(network, addr) + return conn, errors.WithStack(err) } // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header // looks like it might've been a misdirected plaintext HTTP request. @@ -77,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 } @@ -321,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')) { @@ -372,5 +375,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 53f2ae48..029a51f3 100644 --- a/local/proxy/proxy_test.go +++ b/local/proxy/proxy_test.go @@ -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) diff --git a/local/runner.go b/local/runner.go index 08790fd2..0a7d0220 100644 --- a/local/runner.go +++ b/local/runner.go @@ -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") @@ -176,7 +176,7 @@ func (r *Runner) Run() error { if r.mode == RunnerModeLoopDetached { if err = reexec.NotifyForeground("started"); err != nil { - return err + return errors.WithStack(err) } } @@ -206,7 +206,7 @@ func (r *Runner) Run() error { if firstBoot && r.mode == RunnerModeLoopDetached { terminal.RemapOutput(cmd.Stdout, cmd.Stderr).SetDecorated(true) if err = reexec.NotifyForeground(reexec.UP); err != nil { - return err + return errors.WithStack(err) } } @@ -217,9 +217,9 @@ 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 @@ -245,7 +245,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/reexec/process_windows.go b/reexec/process_windows.go index 041ab105..ae2ef2d7 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 b46a8210..296e10ff 100644 --- a/reexec/reexec.go +++ b/reexec/reexec.go @@ -189,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 os.WriteFile(statusFile, []byte(status), 0600) + return errors.WithStack(os.WriteFile(statusFile, []byte(status), 0600)) } func WatchParent(stopCh chan bool) error { @@ -231,7 +231,7 @@ func Restart(postRespawn func()) error { } p, err := Respawn() if err != nil { - return err + return errors.WithStack(err) } if postRespawn != nil { @@ -282,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 2ec02c00..78327b93 100644 --- a/updater/updater.go +++ b/updater/updater.go @@ -230,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 { @@ -241,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) } From 8f5915c6a9277c3e4f02378afe3942bd00837ff5 Mon Sep 17 00:00:00 2001 From: darkweak Date: Tue, 14 Feb 2023 10:56:52 +0100 Subject: [PATCH 6/6] fix ci errors --- local/php/executor_windows.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/local/php/executor_windows.go b/local/php/executor_windows.go index 12961bd8..f5145733 100644 --- a/local/php/executor_windows.go +++ b/local/php/executor_windows.go @@ -31,14 +31,14 @@ func shouldSignalBeIgnored(sig os.Signal) bool { func symlink(oldname, newname string) error { source, err := os.Open(oldname) if err != nil { - return errors.WithStack(err) + return err } defer source.Close() destination, err := os.Create(newname) if err != nil { - return errors.WithStack(err) + return err } defer destination.Close() _, err = io.Copy(destination, source) - return errors.WithStack(err) + return err }