diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d50468c..fd248524 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,53 @@ on: - master jobs: + gofmt: + name: Go Format Check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: 'go.mod' + - name: Check Go formatting + run: | + if [ -n "$(gofmt -s -l .)" ]; then + echo "Go code is not formatted. Please run 'gofmt -s -w .'" + gofmt -s -d . + exit 1 + fi + + golangci-lint: + name: Go Linting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: 'go.mod' + - name: golangci-lint + uses: golangci/golangci-lint-action@v6 + with: + version: latest + args: --timeout=5m + + go-mod-tidy: + name: Go Modules Tidy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: 'go.mod' + - name: Check if go.mod is tidy + run: | + go mod tidy + if [ -n "$(git diff --name-only)" ]; then + echo "go.mod is not tidy. Please run 'go mod tidy'" + git diff + exit 1 + fi + test: runs-on: ubuntu-latest steps: diff --git a/cli_config/cli_config.go b/cli_config/cli_config.go index 765af35f..5a9fdfd5 100644 --- a/cli_config/cli_config.go +++ b/cli_config/cli_config.go @@ -56,15 +56,15 @@ func (c *Config) LoadFile(path string) error { return fmt.Errorf("%w: %s", InvalidConfigErr, err) } - if c.Vm.Manager != "lima" && c.Vm.Manager != "auto" && c.Vm.Manager != "mock" { + if c.Vm.Manager != "" && c.Vm.Manager != "lima" && c.Vm.Manager != "auto" && c.Vm.Manager != "mock" { return fmt.Errorf("%w: unsupported value for `vm.manager`. Must be one of: auto, lima", InvalidConfigErr) } - if c.Vm.Ubuntu != "18.04" && c.Vm.Ubuntu != "20.04" && c.Vm.Ubuntu != "22.04" && c.Vm.Ubuntu != "24.04" { + if c.Vm.Ubuntu != "" && c.Vm.Ubuntu != "18.04" && c.Vm.Ubuntu != "20.04" && c.Vm.Ubuntu != "22.04" && c.Vm.Ubuntu != "24.04" { return fmt.Errorf("%w: unsupported value for `vm.ubuntu`. Must be one of: 18.04, 20.04, 22.04, 24.04", InvalidConfigErr) } - if c.Vm.HostsResolver != "hosts_file" { + if c.Vm.HostsResolver != "" && c.Vm.HostsResolver != "hosts_file" { return fmt.Errorf("%w: unsupported value for `vm.hosts_resolver`. Must be one of: hosts_file", InvalidConfigErr) } diff --git a/cli_config/cli_config_test.go b/cli_config/cli_config_test.go index 16581e32..a63d0f9b 100644 --- a/cli_config/cli_config_test.go +++ b/cli_config/cli_config_test.go @@ -26,7 +26,9 @@ open: t.Fatal(err) } - conf.LoadFile(path) + if err := conf.LoadFile(path); err != nil { + t.Fatal(err) + } if conf.LoadPlugins != true { t.Errorf("expected LoadPlugins to be true (default value)") @@ -53,7 +55,9 @@ func TestLoadEnv(t *testing.T) { AskVaultPass: false, } - conf.LoadEnv("TRELLIS_") + if err := conf.LoadEnv("TRELLIS_"); err != nil { + t.Fatal(err) + } if conf.AskVaultPass != true { t.Errorf("expected AskVaultPass to be true") diff --git a/cmd/alias.go b/cmd/alias.go index bce20279..226fed38 100644 --- a/cmd/alias.go +++ b/cmd/alias.go @@ -88,7 +88,7 @@ func (c *AliasCommand) Run(args []string) int { FailMessage: "Error generating config", }, ) - spinner.Start() + _ = spinner.Start() environments := c.Trellis.EnvironmentNames() var envsToAlias []string @@ -102,7 +102,7 @@ func (c *AliasCommand) Run(args []string) int { tempDir, tempDirErr := os.MkdirTemp("", "trellis-alias-") if tempDirErr != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(tempDirErr.Error()) return 1 } @@ -127,7 +127,7 @@ func (c *AliasCommand) Run(args []string) int { _, site, err := c.Trellis.MainSiteFromEnvironment(environment) if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(err.Error()) return 1 } @@ -143,7 +143,7 @@ func (c *AliasCommand) Run(args []string) int { ).Cmd("ansible-playbook", playbook.CmdArgs()) if err := aliasPlaybook.Run(); err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error("Error creating WP-CLI aliases. Temporary playbook failed to execute:") c.UI.Error(mockUi.ErrorWriter.String()) return 1 @@ -154,7 +154,7 @@ func (c *AliasCommand) Run(args []string) int { for _, environment := range envsToAlias { part, err := os.ReadFile(filepath.Join(tempDir, environment+".yml.part")) if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(err.Error()) return 1 } @@ -164,7 +164,7 @@ func (c *AliasCommand) Run(args []string) int { combinedYmlPath := filepath.Join(tempDir, "/combined.yml") writeFileErr := os.WriteFile(combinedYmlPath, []byte(combined), 0644) if writeFileErr != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(writeFileErr.Error()) return 1 } @@ -185,13 +185,13 @@ func (c *AliasCommand) Run(args []string) int { ).Cmd("ansible-playbook", playbook.CmdArgs()) if err := aliasCopyPlaybook.Run(); err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error("Error creating WP-CLI aliases. Temporary playbook failed to execute:") c.UI.Error(mockUi.ErrorWriter.String()) return 1 } - spinner.Stop() + _ = spinner.Stop() c.UI.Info("") message := ` Action Required: use the generated config by adding these lines to site/wp-cli.yml or an alternative wp-cli.yml (or wp-cli.local.yml) config. diff --git a/cmd/alias_test.go b/cmd/alias_test.go index 72f4c9e2..fa9c2eda 100644 --- a/cmd/alias_test.go +++ b/cmd/alias_test.go @@ -84,7 +84,7 @@ func TestIntegrationAlias(t *testing.T) { alias := exec.Command(bin, "alias") alias.Dir = path.Join(dummy, "trellis") - alias.Run() + _ = alias.Run() if _, err := os.Stat(actualPath); os.IsNotExist(err) { t.Error("wp-cli.trellis-alias.yml file not generated") diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 55af5763..9be09661 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -25,6 +25,6 @@ func TestHelperProcess(t *testing.T) { return } - fmt.Fprintf(os.Stdout, strings.Join(os.Args[3:], " ")) + fmt.Fprint(os.Stdout, strings.Join(os.Args[3:], " ")) os.Exit(0) } diff --git a/cmd/deploy.go b/cmd/deploy.go index 66458657..c1558083 100644 --- a/cmd/deploy.go +++ b/cmd/deploy.go @@ -80,7 +80,7 @@ func (c *DeployCommand) Run(args []string) int { } if environment == "development" { - if c.Trellis.CliConfig.AllowDevelopmentDeploys == false { + if !c.Trellis.CliConfig.AllowDevelopmentDeploys { c.UI.Error(` Error: deploying to the development environment is not supported by default. diff --git a/cmd/dot_env.go b/cmd/dot_env.go index 103a6d76..49b8f91f 100644 --- a/cmd/dot_env.go +++ b/cmd/dot_env.go @@ -55,7 +55,7 @@ func (c *DotEnvCommand) Run(args []string) int { FailMessage: "Error templating .env file", }, ) - spinner.Start() + _ = spinner.Start() environment := "development" if len(args) == 1 { @@ -85,12 +85,12 @@ func (c *DotEnvCommand) Run(args []string) int { ).Cmd("ansible-playbook", playbook.CmdArgs()) if err := dotenv.Run(); err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(mockUi.ErrorWriter.String()) return 1 } - spinner.Stop() + _ = spinner.Stop() return 0 } diff --git a/cmd/dot_env_test.go b/cmd/dot_env_test.go index b2578972..be65944e 100644 --- a/cmd/dot_env_test.go +++ b/cmd/dot_env_test.go @@ -134,7 +134,7 @@ func TestIntegrationDotEnv(t *testing.T) { dotEnv := exec.Command(bin, "dotenv") dotEnv.Dir = filepath.Join(dummy, "trellis") - dotEnv.Run() + _ = dotEnv.Run() if _, err := os.Stat(actualPath); os.IsNotExist(err) { t.Error(".env file not generated") diff --git a/cmd/droplet_create.go b/cmd/droplet_create.go index 589f2e7b..3b9af57e 100644 --- a/cmd/droplet_create.go +++ b/cmd/droplet_create.go @@ -11,8 +11,8 @@ import ( "github.com/digitalocean/godo" "github.com/digitalocean/godo/util" "github.com/fatih/color" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/posener/complete" "github.com/roots/trellis-cli/digitalocean" "github.com/roots/trellis-cli/trellis" @@ -263,16 +263,16 @@ func (c *DropletCreateCommand) createDroplet(region string, size string, image s }, ) - s.Start() + _ = s.Start() err = util.WaitForActive(context.TODO(), c.doClient.Client, monitorUri) if err != nil { - s.StopFail() + _ = s.StopFail() c.UI.Error(err.Error()) return nil, err } - s.Stop() + _ = s.Stop() return droplet, nil } @@ -382,13 +382,13 @@ func (c *DropletCreateCommand) waitForSSH(droplet *godo.Droplet) (*godo.Droplet, FailMessage: "Timeout waiting for SSH", }, ) - s.Start() + _ = s.Start() err = digitalocean.CheckSSH(ip, ctx) if err != nil { - s.StopFail() + _ = s.StopFail() } - s.Stop() + _ = s.Stop() return droplet, nil } diff --git a/cmd/droplet_dns.go b/cmd/droplet_dns.go index 3f2fd563..8c6b652f 100644 --- a/cmd/droplet_dns.go +++ b/cmd/droplet_dns.go @@ -8,8 +8,8 @@ import ( "github.com/digitalocean/godo" "github.com/fatih/color" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/posener/complete" "github.com/roots/trellis-cli/digitalocean" "github.com/roots/trellis-cli/trellis" @@ -261,5 +261,5 @@ func (c *DropletDnsCommand) selectIP() (ip string, err error) { } ip, err = droplets[i].PublicIPv4() - return ip, nil + return ip, err } diff --git a/cmd/galaxy_install_test.go b/cmd/galaxy_install_test.go index 8e3563c2..f15d5ff9 100644 --- a/cmd/galaxy_install_test.go +++ b/cmd/galaxy_install_test.go @@ -103,7 +103,7 @@ func TestGalaxyInstallRun(t *testing.T) { galaxyInstallCommand := GalaxyInstallCommand{ui, trellis} for _, file := range tc.roleFiles { - os.Create(file) + _, _ = os.Create(file) } code := galaxyInstallCommand.Run(tc.args) diff --git a/cmd/init.go b/cmd/init.go index 94d2cc8c..94ca43c0 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -168,16 +168,16 @@ func (c *InitCommand) deleteVirtualenv() error { FailMessage: "Error deleting virtualenv", }, ) - spinner.Start() + _ = spinner.Start() err := c.Trellis.Virtualenv.Delete() if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(err.Error()) return err } - spinner.Stop() + _ = spinner.Stop() return nil } @@ -191,10 +191,10 @@ func (c *InitCommand) createVirtualenv(virtualenvCmd *exec.Cmd) error { }, ) - spinner.Start() + _ = spinner.Start() err := c.Trellis.Virtualenv.Create() if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(err.Error()) c.UI.Error("") c.UI.Error("Project initialization failed due to the error above.") @@ -207,7 +207,7 @@ func (c *InitCommand) createVirtualenv(virtualenvCmd *exec.Cmd) error { } c.Trellis.VenvInitialized = true - spinner.Stop() + _ = spinner.Stop() return nil } @@ -219,16 +219,16 @@ func (c *InitCommand) upgradePip() error { FailMessage: "Error upgrading pip", }, ) - spinner.Start() + _ = spinner.Start() pipUpgradeOutput, err := command.Cmd("python3", []string{"-m", "pip", "install", "--upgrade", "pip"}).CombinedOutput() if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(string(pipUpgradeOutput)) return err } - spinner.Stop() + _ = spinner.Stop() return nil } @@ -240,7 +240,7 @@ func (c *InitCommand) pipInstall() error { StopMessage: "Dependencies installed", }, ) - spinner.Start() + _ = spinner.Start() pipCmd := command.Cmd("pip", []string{"install", "-r", "requirements.txt"}) // Wrap pipCmd's Stdout in a custom writer that only displays output once the timer has elapsed. @@ -250,7 +250,7 @@ func (c *InitCommand) pipInstall() error { go func() { <-timer.C - spinner.Pause() + _ = spinner.Pause() writer.writer = os.Stdout c.UI.Warn("\n\npip install taking longer than expected. Switching to verbose output:\n") }() @@ -260,11 +260,11 @@ func (c *InitCommand) pipInstall() error { err := pipCmd.Run() if err != nil { - spinner.StopFail() + _ = spinner.StopFail() c.UI.Error(errorOutput.String()) return err } - spinner.Stop() + _ = spinner.Stop() return nil } diff --git a/cmd/key_generate.go b/cmd/key_generate.go index 00ea0b70..e633de49 100644 --- a/cmd/key_generate.go +++ b/cmd/key_generate.go @@ -12,8 +12,8 @@ import ( "strings" "github.com/fatih/color" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/mitchellh/go-homedir" "github.com/posener/complete" "github.com/roots/trellis-cli/command" @@ -121,7 +121,7 @@ func (c *KeyGenerateCommand) Run(args []string) int { publicKeyPath := filepath.Join(c.path, publicKeyName) trellisPublicKeysPath := filepath.Join(c.Trellis.Path, "public_keys") trellisPublicKeyPath := filepath.Join(trellisPublicKeysPath, publicKeyName) - os.Mkdir(trellisPublicKeysPath, os.ModePerm) + _ = os.Mkdir(trellisPublicKeysPath, os.ModePerm) keyExists, _ := os.Stat(keyPath) publicKeyExists, _ := os.Stat(trellisPublicKeyPath) diff --git a/cmd/key_generate_test.go b/cmd/key_generate_test.go index 8f6ab42a..5b729cd2 100644 --- a/cmd/key_generate_test.go +++ b/cmd/key_generate_test.go @@ -97,7 +97,9 @@ func TestKeyGenerateExistingPrivateKey(t *testing.T) { tmpDir := t.TempDir() privateKeyPath := filepath.Join(tmpDir, "trellis_example_com_ed25519") - os.WriteFile(privateKeyPath, []byte{}, 0666) + if err := os.WriteFile(privateKeyPath, []byte{}, 0666); err != nil { + t.Fatal(err) + } ui := cli.NewMockUi() keyGenerateCommand := NewKeyGenerateCommand(ui, trellis) @@ -122,7 +124,9 @@ func TestKeyGenerateExistingPublicKey(t *testing.T) { tmpDir := t.TempDir() - os.Mkdir(filepath.Join(trellis.Path, "public_keys"), os.ModePerm) + if err := os.MkdirAll(filepath.Join(trellis.Path, "public_keys"), os.ModePerm); err != nil { + t.Fatal(err) + } publicKeyPath := filepath.Join(trellis.Path, "public_keys", "trellis_example_com_ed25519.pub") err := os.WriteFile(publicKeyPath, []byte{}, 0666) @@ -155,7 +159,7 @@ func TestKeyGenerateKeyscan(t *testing.T) { // fake gh binary to satisfy ok.LookPath ghPath := filepath.Join(tmpDir, "gh") - os.OpenFile(ghPath, os.O_CREATE, 0555) + _, _ = os.OpenFile(ghPath, os.O_CREATE, 0555) path := os.Getenv("PATH") t.Setenv("PATH", fmt.Sprintf("PATH=%s:%s", path, tmpDir)) @@ -211,7 +215,7 @@ func TestKeyGenerateHelperProcess(t *testing.T) { case "good_host": // return fake hash for a good host host := "|1|5XBUprxMy6abCgLQkQ0= ssh-ed25519 AAAAC3NzaC1lZYqEOf" - fmt.Fprintf(os.Stdout, host) + fmt.Fprint(os.Stdout, host) os.Exit(0) case "bad_host": // simulate error for a bad host @@ -220,9 +224,9 @@ func TestKeyGenerateHelperProcess(t *testing.T) { case "ssh-keygen": tmpDir := os.Getenv("GO_TEST_HELPER_TMP_PATH") path := filepath.Join(tmpDir, "trellis_example_com_ed25519.pub") - os.OpenFile(path, os.O_CREATE, 0644) + _, _ = os.OpenFile(path, os.O_CREATE, 0644) path = filepath.Join(tmpDir, "trellis_example_com_ed25519") - os.OpenFile(path, os.O_CREATE, 0644) + _, _ = os.OpenFile(path, os.O_CREATE, 0644) os.Exit(0) case "gh": // make all gh commands succeed. No output needed diff --git a/cmd/logs_test.go b/cmd/logs_test.go index 79e35362..91471314 100644 --- a/cmd/logs_test.go +++ b/cmd/logs_test.go @@ -137,7 +137,7 @@ func TestLogsRunGoAccess(t *testing.T) { // fake goaccess binary to satisfy ok.LookPath goAccessPath := filepath.Join(tmpDir, "goaccess") - os.OpenFile(goAccessPath, os.O_CREATE, 0555) + _, _ = os.OpenFile(goAccessPath, os.O_CREATE, 0555) path := os.Getenv("PATH") t.Setenv("PATH", fmt.Sprintf("PATH=%s:%s", path, tmpDir)) diff --git a/cmd/new.go b/cmd/new.go index 468bb1b0..2d2d46b7 100644 --- a/cmd/new.go +++ b/cmd/new.go @@ -9,8 +9,8 @@ import ( "strings" "github.com/fatih/color" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/roots/trellis-cli/github" "github.com/roots/trellis-cli/trellis" "github.com/weppos/publicsuffix-go/publicsuffix" @@ -125,7 +125,10 @@ func (c *NewCommand) Run(args []string) int { return 1 } - os.Chdir(path) + if err := os.Chdir(path); err != nil { + c.UI.Error(fmt.Sprintf("Error changing to project directory: %s", err)) + return 1 + } if err := c.trellis.LoadProject(); err != nil { c.UI.Error(err.Error()) @@ -146,7 +149,7 @@ func (c *NewCommand) Run(args []string) int { // Update default configs for env, config := range c.trellis.Environments { c.trellis.UpdateDefaultConfig(config, c.name, c.host, env) - c.trellis.WriteYamlFile( + _ = c.trellis.WriteYamlFile( config, filepath.Join("group_vars", env, "wordpress_sites.yml"), c.YamlHeader("https://roots.io/trellis/docs/wordpress-sites/"), @@ -154,7 +157,7 @@ func (c *NewCommand) Run(args []string) int { stringGenerator := trellis.RandomStringGenerator{Length: 64} vault := c.trellis.GenerateVaultConfig(c.name, env, &stringGenerator) - c.trellis.WriteYamlFile( + _ = c.trellis.WriteYamlFile( vault, filepath.Join("group_vars", env, "vault.yml"), c.YamlHeader("https://roots.io/trellis/docs/vault/"), @@ -245,11 +248,6 @@ func (c *NewCommand) YamlHeader(doc string) string { return fmt.Sprintf(header, c.CliVersion, doc) } -func addTrellisFile(path string) error { - path = filepath.Join(path, ".trellis.yml") - return os.WriteFile(path, []byte{}, 0666) -} - func askDomain(ui cli.Ui, path string) (host string, err error) { path = filepath.Base(path) domain, err := publicsuffix.Parse(path) diff --git a/cmd/open.go b/cmd/open.go index a24ddeb8..05e14469 100644 --- a/cmd/open.go +++ b/cmd/open.go @@ -31,7 +31,7 @@ func (c *OpenCommand) Run(args []string) int { return 1 } - var openArgs = []string{} + var openArgs []string if len(args) == 0 { _, site, siteErr := c.Trellis.MainSiteFromEnvironment("development") diff --git a/cmd/valet_link.go b/cmd/valet_link.go index adcb3eee..3b4c9175 100644 --- a/cmd/valet_link.go +++ b/cmd/valet_link.go @@ -41,7 +41,7 @@ func (c *ValetLinkCommand) Run(args []string) int { return 1 } - config, _ := c.Trellis.Environments[environment] + config := c.Trellis.Environments[environment] c.UI.Info(fmt.Sprintf("Linking environment %s...", environment)) diff --git a/cmd/valet_link_test.go b/cmd/valet_link_test.go index a81d5f89..ea96786d 100644 --- a/cmd/valet_link_test.go +++ b/cmd/valet_link_test.go @@ -142,7 +142,7 @@ func TestValetLinkRun(t *testing.T) { defer trellis.TestChdir(t, "../trellis/testdata/trellis")() if err := trellisProject.LoadProject(); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } trellis := trellis.NewMockTrellis(true) diff --git a/cmd/vault_decrypt_test.go b/cmd/vault_decrypt_test.go index 1e456517..8c5c125e 100644 --- a/cmd/vault_decrypt_test.go +++ b/cmd/vault_decrypt_test.go @@ -59,7 +59,7 @@ func TestVaultDecryptRun(t *testing.T) { defer trellis.TestChdir(t, "../trellis/testdata/trellis")() if err := trellisProject.LoadProject(); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } cases := []struct { diff --git a/cmd/vault_edit.go b/cmd/vault_edit.go index 62d53000..9b3a9819 100644 --- a/cmd/vault_edit.go +++ b/cmd/vault_edit.go @@ -6,8 +6,8 @@ import ( "path/filepath" "strings" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/posener/complete" "github.com/roots/trellis-cli/command" "github.com/roots/trellis-cli/pkg/flags" diff --git a/cmd/vault_encrypt_test.go b/cmd/vault_encrypt_test.go index 4613a6a4..838542c4 100644 --- a/cmd/vault_encrypt_test.go +++ b/cmd/vault_encrypt_test.go @@ -59,7 +59,7 @@ func TestVaultEncryptRun(t *testing.T) { defer trellis.TestChdir(t, "../trellis/testdata/trellis")() if err := trellisProject.LoadProject(); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } cases := []struct { diff --git a/cmd/vault_view.go b/cmd/vault_view.go index a28ba236..4e9195e6 100644 --- a/cmd/vault_view.go +++ b/cmd/vault_view.go @@ -6,8 +6,8 @@ import ( "path/filepath" "strings" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/posener/complete" "github.com/roots/trellis-cli/command" "github.com/roots/trellis-cli/pkg/flags" diff --git a/cmd/vault_view_test.go b/cmd/vault_view_test.go index 109cd99c..27923f77 100644 --- a/cmd/vault_view_test.go +++ b/cmd/vault_view_test.go @@ -59,7 +59,7 @@ func TestVaultViewRun(t *testing.T) { defer trellis.TestChdir(t, "../trellis/testdata/trellis")() if err := trellisProject.LoadProject(); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } trellis := trellis.NewMockTrellis(true) diff --git a/cmd/vm_delete.go b/cmd/vm_delete.go index 92006a62..58038644 100644 --- a/cmd/vm_delete.go +++ b/cmd/vm_delete.go @@ -4,8 +4,8 @@ import ( "flag" "strings" - "github.com/manifoldco/promptui" "github.com/hashicorp/cli" + "github.com/manifoldco/promptui" "github.com/posener/complete" "github.com/roots/trellis-cli/trellis" ) diff --git a/cmd/vm_shell.go b/cmd/vm_shell.go index 038ebdb9..0f63f19e 100644 --- a/cmd/vm_shell.go +++ b/cmd/vm_shell.go @@ -63,9 +63,6 @@ func (c *VmShellCommand) Run(args []string) int { c.workdir = "/srv/www/" + siteName + "/current" } - shellArgs := []string{"--workdir", c.workdir} - shellArgs = append(shellArgs, args...) - if err := manager.OpenShell(instanceName, c.workdir, args); err != nil { c.UI.Error(err.Error()) return 1 diff --git a/command/main.go b/command/main.go index 8505917f..84fb7938 100644 --- a/command/main.go +++ b/command/main.go @@ -56,7 +56,7 @@ func (c *Command) Cmd(command string, args []string) *exec.Cmd { } /* - Enables mocking of the underlying ExecCommand command (defaults to exec.Command) and no-ops the OptionApplier function so they have no effect. +Enables mocking of the underlying ExecCommand command (defaults to exec.Command) and no-ops the OptionApplier function so they have no effect. */ func Mock(f CommandFunc) { OptionApplier = func(option CommandOption, cmd *exec.Cmd) {} @@ -64,8 +64,8 @@ func Mock(f CommandFunc) { } /* - Restores the default ExecCommand and OptionApplier. - Should be used via `defer` after `Mock` is called. +Restores the default ExecCommand and OptionApplier. +Should be used via `defer` after `Mock` is called. */ func Restore() { OptionApplier = applyOption diff --git a/command/main_test.go b/command/main_test.go index 83a585f0..756d44d1 100644 --- a/command/main_test.go +++ b/command/main_test.go @@ -25,7 +25,7 @@ func anotherFakeOption() CommandOption { func TestCmdWithOptions(t *testing.T) { cmd := WithOptions(fakeOption(), anotherFakeOption()).Cmd("foo", []string{}) - expected := fmt.Sprintf("foo arg1 arg2") + expected := "foo arg1 arg2" actual := cmd.String() if actual != expected { @@ -64,7 +64,9 @@ func TestWithUiOutput(t *testing.T) { defer Restore() ui := cli.NewMockUi() - WithOptions(WithUiOutput(ui)).Cmd("foo", []string{"arg"}).Run() + if err := WithOptions(WithUiOutput(ui)).Cmd("foo", []string{"arg"}).Run(); err != nil { + t.Fatal(err) + } combined := ui.OutputWriter.String() + ui.ErrorWriter.String() @@ -78,6 +80,6 @@ func TestHelperProcess(t *testing.T) { return } - fmt.Fprintf(os.Stdout, strings.Join(os.Args[3:], " ")) + fmt.Fprint(os.Stdout, strings.Join(os.Args[3:], " ")) os.Exit(0) } diff --git a/digitalocean/client.go b/digitalocean/client.go index 2c722442..514c2ffe 100644 --- a/digitalocean/client.go +++ b/digitalocean/client.go @@ -99,10 +99,10 @@ func (do *Client) CreateSSHKey(key string) error { u, err := user.Current() if err != nil { name = "trellis-cli-ssh-key" + } else { + name = u.Username } - name = u.Username - createRequest := &godo.KeyCreateRequest{ Name: name, PublicKey: key, diff --git a/digitalocean/digitalocean.go b/digitalocean/digitalocean.go index 2b61764a..f276d7ec 100644 --- a/digitalocean/digitalocean.go +++ b/digitalocean/digitalocean.go @@ -82,6 +82,9 @@ func LoadSSHKey(sshKeys []string) (keyPath string, contents []byte, publicKey ss func loadPublicKey(path string) (contents []byte, publicKey ssh.PublicKey, err error) { path, err = homedir.Expand(path) + if err != nil { + return nil, nil, err + } key, err := os.ReadFile(path) if err != nil { return nil, nil, err diff --git a/github/main.go b/github/main.go index 631b7aca..d1309e83 100644 --- a/github/main.go +++ b/github/main.go @@ -44,7 +44,9 @@ func DownloadRelease(repo string, version string, path string, dest string) (rel release = NewReleaseFromVersion(repo, version) } - os.Chdir(path) + if err := os.Chdir(path); err != nil { + return nil, fmt.Errorf("Error changing to directory %s: %v", path, err) + } archivePath := fmt.Sprintf("%s.zip", release.Version) err = DownloadFile(archivePath, release.ZipUrl, Client) @@ -106,7 +108,7 @@ func FetchLatestRelease(repo string, client *http.Client) (*Release, error) { } if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf(string(body)) + return nil, fmt.Errorf("%s", string(body)) } release := &Release{} diff --git a/github/main_test.go b/github/main_test.go index 1ad46efc..0d92dad3 100644 --- a/github/main_test.go +++ b/github/main_test.go @@ -2,7 +2,6 @@ package github import ( "context" - "fmt" "io" "net/http" "net/http/httptest" @@ -29,7 +28,9 @@ func TestNewReleaseFromVersion(t *testing.T) { func TestDownloadRelease(t *testing.T) { tmpDir := t.TempDir() - os.Chdir(tmpDir) + if err := os.Chdir(tmpDir); err != nil { + t.Fatal(err) + } var dir = "roots-trellis" @@ -82,11 +83,11 @@ func TestFetechLatestRelease(t *testing.T) { }{ { "success response", - fmt.Sprintf(`{ + `{ "tag_name": "v1.0", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.0", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.0" -}`), +}`, "", &Release{ Version: "v1.0", @@ -107,7 +108,7 @@ func TestFetechLatestRelease(t *testing.T) { if tc.responseError != "" { http.Error(rw, tc.responseError, 400) } else { - rw.Write([]byte(tc.response)) + _, _ = rw.Write([]byte(tc.response)) } })) defer server.Close() diff --git a/help.go b/help.go index 7ce354d5..9a82ff2e 100644 --- a/help.go +++ b/help.go @@ -39,7 +39,7 @@ func deprecatedCommandHelpFunc(commandNames []string, f cli.HelpFunc) cli.HelpFu sort.Strings(keys) for _, key := range keys { - commandFunc, _ := commands[key] + commandFunc := commands[key] command, _ := commandFunc() key = fmt.Sprintf("%s%s", key, strings.Repeat(" ", maxKeyLen-len(key))) buf.WriteString(fmt.Sprintf(" %s %s\n", key, command.Synopsis())) diff --git a/main_test.go b/main_test.go index 3187bf2f..1a19663a 100644 --- a/main_test.go +++ b/main_test.go @@ -39,7 +39,7 @@ func TestIntegrationForceNoPlugin(t *testing.T) { trellisCommand := command.WithOptions(command.WithUiOutput(mockUi)).Cmd(bin, []string{"--help"}) trellisCommand.Env = []string{"PATH=" + tempDir + ":$PATH", "TRELLIS_LOAD_PLUGINS=false"} - trellisCommand.Run() + _ = trellisCommand.Run() output := mockUi.ErrorWriter.String() for _, unexpected := range []string{"Available third party plugin commands are", "abc"} { diff --git a/pkg/db_opener/db_opener.go b/pkg/db_opener/db_opener.go index d0339a35..a7f9a6f7 100644 --- a/pkg/db_opener/db_opener.go +++ b/pkg/db_opener/db_opener.go @@ -10,4 +10,3 @@ type DBCredentials struct { DBName string `json:"db_name"` WPEnv string `json:"wp_env"` } - diff --git a/pkg/lima/instance.go b/pkg/lima/instance.go index 8b32bcd5..f84eacc2 100644 --- a/pkg/lima/instance.go +++ b/pkg/lima/instance.go @@ -107,9 +107,10 @@ func (i *Instance) CreateInventoryFile() error { /* Gets the IP address of the instance using the output of `ip route`: - default via 192.168.64.1 proto dhcp src 192.168.64.2 metric 100 - 192.168.64.0/24 proto kernel scope link src 192.168.64.2 - 192.168.64.1 proto dhcp scope link src 192.168.64.2 metric 100 + + default via 192.168.64.1 proto dhcp src 192.168.64.2 metric 100 + 192.168.64.0/24 proto kernel scope link src 192.168.64.2 + 192.168.64.1 proto dhcp scope link src 192.168.64.2 metric 100 */ func (i *Instance) IP() (ip string, err error) { output, err := command.Cmd( diff --git a/pkg/lima/manager.go b/pkg/lima/manager.go index accde687..a494ac8e 100644 --- a/pkg/lima/manager.go +++ b/pkg/lima/manager.go @@ -10,8 +10,8 @@ import ( "strings" "github.com/fatih/color" - "github.com/mcuadros/go-version" "github.com/hashicorp/cli" + "github.com/mcuadros/go-version" "github.com/roots/trellis-cli/command" "github.com/roots/trellis-cli/pkg/vm" "github.com/roots/trellis-cli/trellis" @@ -283,7 +283,9 @@ func (m *Manager) instances() (instances map[string]Instance) { for _, line := range bytes.Split(output, []byte("\n")) { instance := &Instance{} - json.Unmarshal([]byte(line), instance) + if err := json.Unmarshal([]byte(line), instance); err != nil { + continue + } m.initInstance(instance) instances[instance.Name] = *instance } diff --git a/pkg/lima/manager_test.go b/pkg/lima/manager_test.go index bd8a2564..4e54f9d6 100644 --- a/pkg/lima/manager_test.go +++ b/pkg/lima/manager_test.go @@ -24,7 +24,7 @@ func TestNewManager(t *testing.T) { tmp := t.TempDir() - os.OpenFile(filepath.Join(tmp, "limactl"), os.O_CREATE, 0555) + _, _ = os.OpenFile(filepath.Join(tmp, "limactl"), os.O_CREATE, 0555) path := os.Getenv("PATH") t.Setenv("PATH", fmt.Sprintf("PATH=%s:%s", path, tmp)) @@ -57,7 +57,7 @@ func TestNewManagerUnsupportedOS(t *testing.T) { tmp := t.TempDir() - os.OpenFile(filepath.Join(tmp, "limactl"), os.O_CREATE, 0555) + _, _ = os.OpenFile(filepath.Join(tmp, "limactl"), os.O_CREATE, 0555) path := os.Getenv("PATH") t.Setenv("PATH", fmt.Sprintf("PATH=%s:%s", path, tmp)) @@ -331,10 +331,6 @@ default } } -func newMockHostsResolver(hosts map[string]string) MockHostsResolver { - return MockHostsResolver{Hosts: hosts} -} - func (h *MockHostsResolver) AddHosts(name string, ip string) error { h.Hosts[name] = ip return nil diff --git a/plugin/finder_test.go b/plugin/finder_test.go index 29b43e68..8ec4d8a7 100644 --- a/plugin/finder_test.go +++ b/plugin/finder_test.go @@ -136,7 +136,7 @@ func TestFind(t *testing.T) { for _, tc := range cases { // cleanup files from previous test case. os.RemoveAll(tempDir) - os.MkdirAll(tempDir, 0700) + _ = os.MkdirAll(tempDir, 0700) if _, err := createTempFile(tc.pluginFileName, tc.pluginFileMode); err != nil { t.Fatalf("unexpected error creating plugin file: %v", err) diff --git a/plugin/register_test.go b/plugin/register_test.go index 32026001..1c201947 100644 --- a/plugin/register_test.go +++ b/plugin/register_test.go @@ -109,7 +109,7 @@ func TestIntegrationPluginCommand(t *testing.T) { spyCommand := command.WithOptions(command.WithUiOutput(mockUi)).Cmd(bin, tc.args) spyCommand.Env = []string{"PATH=" + tempDir + ":" + os.ExpandEnv("$PATH")} - spyCommand.Run() + _ = spyCommand.Run() stdOut := mockUi.OutputWriter.String() for _, expected := range tc.expectedStdOut { @@ -167,7 +167,7 @@ func TestIntegrationPluginListInHelpFunc(t *testing.T) { trellisCommand := command.WithOptions(command.WithUiOutput(mockUi)).Cmd(bin, []string{"--help"}) trellisCommand.Env = []string{"PATH=" + tempDir + ":$PATH"} - trellisCommand.Run() + _ = trellisCommand.Run() output := mockUi.ErrorWriter.String() expected := "Available plugin commands" diff --git a/trellis/complete.go b/trellis/complete.go index c6eb758e..ea5fbbd9 100644 --- a/trellis/complete.go +++ b/trellis/complete.go @@ -21,7 +21,7 @@ func (t *Trellis) PredictSite(flags *flag.FlagSet) complete.PredictFunc { } flags.SetOutput(io.Discard) - flags.Parse(args.Completed) + _ = flags.Parse(args.Completed) cmdArgs := flags.Args() switch len(cmdArgs) { @@ -42,7 +42,7 @@ func (t *Trellis) PredictEnvironment(flags *flag.FlagSet) complete.PredictFunc { } flags.SetOutput(io.Discard) - flags.Parse(args.Completed) + _ = flags.Parse(args.Completed) cmdArgs := flags.Args() switch len(cmdArgs) { diff --git a/trellis/complete_test.go b/trellis/complete_test.go index 7323670a..cd1ba51e 100644 --- a/trellis/complete_test.go +++ b/trellis/complete_test.go @@ -27,7 +27,7 @@ func TestCompletionFunctions(t *testing.T) { defer TestChdir(t, "testdata/trellis")() if err := trellis.LoadProject(); err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } flags := flag.NewFlagSet("", flag.ContinueOnError) @@ -109,7 +109,7 @@ func TestCompletionFunctions(t *testing.T) { // element if we have one since we usually output a final newline // which results in a blank. var outBuf bytes.Buffer - io.Copy(&outBuf, r) + _, _ = io.Copy(&outBuf, r) actual := strings.Split(outBuf.String(), "\n") if len(actual) > 0 { actual = actual[:len(actual)-1] diff --git a/trellis/config.go b/trellis/config.go index 554765da..ff1b8825 100644 --- a/trellis/config.go +++ b/trellis/config.go @@ -142,9 +142,7 @@ func (c *Config) AllHosts() []string { for _, siteHost := range site.SiteHosts { hosts = append(hosts, siteHost.Canonical) - for _, redirect := range siteHost.Redirects { - hosts = append(hosts, redirect) - } + hosts = append(hosts, siteHost.Redirects...) } } diff --git a/trellis/detector_test.go b/trellis/detector_test.go index d780a277..934ad3cd 100644 --- a/trellis/detector_test.go +++ b/trellis/detector_test.go @@ -67,15 +67,25 @@ func TestDetectTrellisProjectStructure(t *testing.T) { trellisDir := filepath.Join(testDir, "trellis") siteDir := filepath.Join(testDir, "site") - os.Mkdir(trellisDir, 0700) - os.Mkdir(siteDir, 0700) - os.Mkdir(filepath.Join(trellisDir, ConfigDir), 0700) + if err := os.Mkdir(trellisDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(siteDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(trellisDir, ConfigDir), 0700); err != nil { + t.Fatal(err) + } devDir := filepath.Join(trellisDir, "group_vars", "development") - os.MkdirAll(devDir, 0700) + if err := os.MkdirAll(devDir, 0700); err != nil { + t.Fatal(err) + } devConfig := filepath.Join(devDir, "wordpress_sites.yml") - os.WriteFile(devConfig, []byte{}, 0666) + if err := os.WriteFile(devConfig, []byte{}, 0666); err != nil { + t.Fatal(err) + } project := &ProjectDetector{} diff --git a/trellis/hosts_test.go b/trellis/hosts_test.go index 7511f8d4..7d095a6b 100644 --- a/trellis/hosts_test.go +++ b/trellis/hosts_test.go @@ -17,12 +17,12 @@ func TestUpdateHosts(t *testing.T) { hostsFile, err := trellis.UpdateHosts("production", "1.2.3.4") if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } content, err := os.ReadFile(hostsFile) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err) } const hostsContent = ` diff --git a/trellis/mock_detector.go b/trellis/mock_detector.go index 481f357f..37432be4 100644 --- a/trellis/mock_detector.go +++ b/trellis/mock_detector.go @@ -5,5 +5,9 @@ type MockProjectDetector struct { } func (p *MockProjectDetector) Detect(path string) (projectPath string, ok bool) { - return "trellis", p.detected + if p.detected { + // Return current directory for mock to avoid chdir errors + return ".", true + } + return "", false } diff --git a/trellis/testing.go b/trellis/testing.go index 80d1cec3..b369b31d 100644 --- a/trellis/testing.go +++ b/trellis/testing.go @@ -21,7 +21,9 @@ func LoadFixtureProject(t *testing.T) func() { _, b, _, _ := runtime.Caller(0) basepath := filepath.Dir(b) - os.Chdir(basepath) + if err := os.Chdir(basepath); err != nil { + t.Fatalf("err: %s", err) + } cmd := exec.Command("cp", "-a", "testdata/trellis", tempDir) output, err := cmd.CombinedOutput() @@ -29,7 +31,9 @@ func LoadFixtureProject(t *testing.T) func() { t.Fatalf("failed to copy trellis fixture project: %s\n%s", err, output) } - os.Chdir(filepath.Join(tempDir, "trellis")) + if err := os.Chdir(filepath.Join(tempDir, "trellis")); err != nil { + t.Fatalf("err: %s", err) + } return func() { if err := os.Chdir(old); err != nil { @@ -49,5 +53,9 @@ func TestChdir(t *testing.T, dir string) func() { if err := os.Chdir(dir); err != nil { t.Fatalf("err: %s", err) } - return func() { os.Chdir(old) } + return func() { + if err := os.Chdir(old); err != nil { + t.Fatalf("err: %s", err) + } + } } diff --git a/trellis/trellis.go b/trellis/trellis.go index abe03e50..27e508e7 100644 --- a/trellis/trellis.go +++ b/trellis/trellis.go @@ -155,7 +155,9 @@ func (t *Trellis) ActivateProject() bool { return false } - os.Chdir(t.Path) + // Attempt to change to the trellis directory + // but don't fail detection if it fails + _ = os.Chdir(t.Path) return true } @@ -167,7 +169,9 @@ the directory is changed to the project path. */ func (t *Trellis) LoadProject() error { if t.Path != "" { - os.Chdir(t.Path) + if err := os.Chdir(t.Path); err != nil { + return fmt.Errorf("Error changing to project directory %s: %v", t.Path, err) + } return nil } @@ -185,7 +189,9 @@ func (t *Trellis) LoadProject() error { t.Path = path t.Virtualenv = NewVirtualenv(t.ConfigPath()) - os.Chdir(t.Path) + if err := os.Chdir(t.Path); err != nil { + return fmt.Errorf("Error changing to project directory %s: %v", t.Path, err) + } if err = t.LoadProjectCliConfig(); err != nil { return err @@ -248,7 +254,6 @@ func (t *Trellis) GetVmInstanceName() (string, error) { return siteName, nil } - func (t *Trellis) SiteNamesFromEnvironment(environment string) []string { var names []string @@ -331,7 +336,7 @@ func (t *Trellis) LoadProjectCliConfig() error { } } - t.CliConfig.LoadEnv("TRELLIS_") + _ = t.CliConfig.LoadEnv("TRELLIS_") if t.CliConfig.AskVaultPass { // https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-ask-vault-pass diff --git a/trellis/trellis_test.go b/trellis/trellis_test.go index b51a62e7..f2fe4ad4 100644 --- a/trellis/trellis_test.go +++ b/trellis/trellis_test.go @@ -18,7 +18,7 @@ func TestCreateConfigDir(t *testing.T) { ConfigDir: configPath, } - trellis.CreateConfigDir() + _ = trellis.CreateConfigDir() _, err := os.Stat(configPath) if err != nil { diff --git a/trellis/vault.go b/trellis/vault.go index a886253e..c66f92d6 100644 --- a/trellis/vault.go +++ b/trellis/vault.go @@ -3,7 +3,6 @@ package trellis import ( "bufio" "crypto/rand" - "fmt" "io" "log" "os" @@ -129,7 +128,7 @@ func assertAvailablePRNG() { _, err := io.ReadFull(rand.Reader, buf) if err != nil { - log.Fatal(fmt.Sprintf("Unable to generate random salt values. crypto/rand is unavailable: Read() failed with %#v", err)) + log.Fatalf("Unable to generate random salt values. crypto/rand is unavailable: Read() failed with %#v", err) } } diff --git a/trellis/virtualenv.go b/trellis/virtualenv.go index 73aecf23..9cf19464 100644 --- a/trellis/virtualenv.go +++ b/trellis/virtualenv.go @@ -106,25 +106,25 @@ func (v *Virtualenv) Installed() (ok bool, cmd *exec.Cmd) { } /* - Updates the shebang lines in pip generated bin files to properly handle - paths with spaces. +Updates the shebang lines in pip generated bin files to properly handle +paths with spaces. - Pip does not properly handle paths with spaces in them when creating the bin - scripts: +Pip does not properly handle paths with spaces in them when creating the bin +scripts: - #!/path with spaces/bin/python + #!/path with spaces/bin/python - This is an invalid POSIX path so Python can't execute the script. +This is an invalid POSIX path so Python can't execute the script. - As a workaround, this function replaces that invalid shebang with the workaround - that Virtualenv uses itself for the pip binary: +As a workaround, this function replaces that invalid shebang with the workaround +that Virtualenv uses itself for the pip binary: - #!/bin/sh - '''exec' "/path with spaces/bin/python" "$0" "$@" - ' ''' + #!/bin/sh + '''exec' "/path with spaces/bin/python" "$0" "$@" + ' ''' - If this function is called on a BinPath without spaces, it's just a no-op - that doesn't modify any files. +If this function is called on a BinPath without spaces, it's just a no-op +that doesn't modify any files. */ func (v *Virtualenv) UpdateBinShebangs(binGlob string) error { if !strings.Contains(v.BinPath, " ") { diff --git a/trellis/virtualenv_test.go b/trellis/virtualenv_test.go index 31f2edc0..246c9dcd 100644 --- a/trellis/virtualenv_test.go +++ b/trellis/virtualenv_test.go @@ -115,7 +115,9 @@ func TestInitialized(t *testing.T) { t.Error("Expected to be uniniatlized") } - os.MkdirAll(venv.BinPath, os.ModePerm) + if err := os.MkdirAll(venv.BinPath, os.ModePerm); err != nil { + t.Fatal(err) + } testCreateFile(t, filepath.Join(venv.BinPath, "python"))() testCreateFile(t, filepath.Join(venv.BinPath, "pip"))() @@ -142,7 +144,9 @@ func TestInstalledPython3WithEnsurepip(t *testing.T) { t.Setenv("PATH", tempDir) pythonPath := filepath.Join(tempDir, "python3") - os.OpenFile(pythonPath, os.O_CREATE, 0555) + if _, err := os.OpenFile(pythonPath, os.O_CREATE, 0555); err != nil { + t.Fatal(err) + } venv := NewVirtualenv(tempDir) @@ -180,7 +184,9 @@ func TestInstalledPython3WithoutEnsurepip(t *testing.T) { t.Setenv("PATH", tempDir) pythonPath := filepath.Join(tempDir, "python3") - os.OpenFile(pythonPath, os.O_CREATE, 0555) + if _, err := os.OpenFile(pythonPath, os.O_CREATE, 0555); err != nil { + t.Fatal(err) + } var output bytes.Buffer @@ -211,7 +217,9 @@ func TestInstalledVirtualenv(t *testing.T) { t.Setenv("PATH", tempDir) venvPath := filepath.Join(tempDir, "virtualenv") - os.OpenFile(venvPath, os.O_CREATE, 0555) + if _, err := os.OpenFile(venvPath, os.O_CREATE, 0555); err != nil { + t.Fatal(err) + } venv := NewVirtualenv(tempDir) @@ -282,7 +290,9 @@ next line func TestUpdateBinShebangsNoSpaces(t *testing.T) { dir := t.TempDir() - os.MkdirAll(filepath.Join(dir, "virtualenv", "bin"), 0755) + if err := os.MkdirAll(filepath.Join(dir, "virtualenv", "bin"), 0755); err != nil { + t.Fatal(err) + } venv := NewVirtualenv(dir) content := `#!/trellis/virtualenv/bin/python\n` @@ -292,7 +302,7 @@ func TestUpdateBinShebangsNoSpaces(t *testing.T) { t.Fatal(err) } - venv.UpdateBinShebangs("foo*") + _ = venv.UpdateBinShebangs("foo*") output, err := os.ReadFile(path) if err != nil { @@ -308,7 +318,9 @@ func TestUpdateBinShebangsWithSpaces(t *testing.T) { t.SkipNow() dir := t.TempDir() - os.MkdirAll(filepath.Join(dir, "virtualenv", "bin"), 0755) + if err := os.MkdirAll(filepath.Join(dir, "virtualenv", "bin"), 0755); err != nil { + t.Fatal(err) + } venv := NewVirtualenv(dir) @@ -344,7 +356,7 @@ func TestUpdateBinShebangsWithSpaces(t *testing.T) { } } - venv.UpdateBinShebangs("foo*") + _ = venv.UpdateBinShebangs("foo*") for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -376,7 +388,7 @@ func TestEnsurePipSuccessHelperProcess(t *testing.T) { return } - fmt.Fprintf(os.Stdout, strings.Join(os.Args[3:], " ")) + fmt.Fprint(os.Stdout, strings.Join(os.Args[3:], " ")) os.Exit(0) } @@ -385,6 +397,6 @@ func TestEnsurePipFailureHelperProcess(t *testing.T) { return } - fmt.Fprintf(os.Stderr, strings.Join(os.Args[3:], " ")) + fmt.Fprint(os.Stderr, strings.Join(os.Args[3:], " ")) os.Exit(1) } diff --git a/update/main.go b/update/main.go index 4a2eff99..754a4169 100644 --- a/update/main.go +++ b/update/main.go @@ -69,11 +69,7 @@ func (n *Notifier) shouldCheckForUpdate() bool { // skip on non-terminals fd := os.Stdout.Fd() - if !(isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)) { - return false - } - - return true + return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd) } func (n *Notifier) getLatestReleaseInfo(stateFilePath string) (*github.Release, error) { diff --git a/update/main_test.go b/update/main_test.go index 03aa6250..705a2422 100644 --- a/update/main_test.go +++ b/update/main_test.go @@ -163,11 +163,11 @@ latest_release: zipurl: https://api.github.com/repos/roots/trellis-cli/zipball/v1.0 url: https://github.com/roots/trellis-cli/releases/tag/v1.0 `, now.Add(-time.Hour*25).Format(time.RFC3339)), - fmt.Sprintf(`{ + `{ "tag_name": "v1.1", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.1", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.1" -}`), +}`, &github.Release{ Version: "v1.1", URL: "https://github.com/roots/trellis-cli/releases/tag/v1.1", @@ -184,22 +184,22 @@ latest_release: zipurl: https://api.github.com/repos/roots/trellis-cli/zipball/v1.0 url: https://github.com/roots/trellis-cli/releases/tag/v1.0 `, now.Add(-time.Hour*25).Format(time.RFC3339)), - fmt.Sprintf(`{ + `{ "tag_name": "v1.0", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.0", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.0" -}`), +}`, nil, }, { "no_cache_newer_version", "v1.0", "", - fmt.Sprintf(`{ + `{ "tag_name": "v1.1", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.1", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.1" -}`), +}`, &github.Release{ Version: "v1.1", URL: "https://github.com/roots/trellis-cli/releases/tag/v1.1", @@ -210,22 +210,22 @@ latest_release: "no_cache_same_version", "v1.0", "", - fmt.Sprintf(`{ + `{ "tag_name": "v1.0", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.0", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.0" -}`), +}`, nil, }, { "no_cache_older_version", "v1.1", "", - fmt.Sprintf(`{ + `{ "tag_name": "v1.0", "html_url": "https://github.com/roots/trellis-cli/releases/tag/v1.0", "zipball_url": "https://api.github.com/repos/roots/trellis-cli/zipball/v1.0" -}`), +}`, nil, }, } @@ -239,7 +239,7 @@ latest_release: if tc.githubResponse != "" { server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Write([]byte(tc.githubResponse)) + _, _ = rw.Write([]byte(tc.githubResponse)) })) defer server.Close()