diff --git a/.golangci.yml b/.golangci.yml index f9618763..ba43aca4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,19 +1,30 @@ +version: "2" run: - # Our CI expects a vendor directory, hence we have to use -mod=readonly here as well. modules-download-mode: readonly - deadline: 30m - timeout: 5m - -# default linters are enabled `golangci-lint help linters` linters: - disable-all: true + default: none enable: - - errcheck - - gosec - - gosimple - - govet - - ineffassign - - staticcheck - - typecheck - - unused - - stylecheck + - errcheck + - gosec + - govet + - ineffassign + - staticcheck + - unused + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/CLAUDE.md b/CLAUDE.md index 5e2c825d..24ae7ee1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,13 +84,10 @@ make lint-in-container The project uses golangci-lint with the following enabled linters: - errcheck - gosec -- gosimple - govet - ineffassign - staticcheck -- typecheck - unused -- stylecheck ## Development Workflow @@ -105,4 +102,4 @@ The project uses golangci-lint with the following enabled linters: - This is an OCM plugin - the binary has prefix `ocm-` and can be invoked as `ocm backplane` - Configuration file expected at `$HOME/.config/backplane/config.json` - The project uses Go modules with vendoring -- Static linking is used for the final binary \ No newline at end of file +- Static linking is used for the final binary diff --git a/Makefile b/Makefile index d3f0d4d3..801e3751 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ GO_BUILD_FLAGS :=-tags 'include_gcs include_oss containers_image_openpgp gssapi' GO_BUILD_FLAGS_DARWIN :=-tags 'include_gcs include_oss containers_image_openpgp' GO_BUILD_FLAGS_LINUX_CROSS :=-tags 'include_gcs include_oss containers_image_openpgp' -GOLANGCI_LINT_VERSION=v1.61.0 +GOLANGCI_LINT_VERSION=v2.5.0 GORELEASER_VERSION=v1.14.1 GOVULNCHECK_VERSION=v1.0.1 @@ -66,8 +66,8 @@ test-in-container: build-image # Installed using instructions from: https://golangci-lint.run/usage/install/#linux-and-windows getlint: @mkdir -p $(GOPATH)/bin - @ls $(GOPATH)/bin/golangci-lint 1>/dev/null || (echo "Installing golangci-lint..." && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin $(GOLANGCI_LINT_VERSION)) - + @echo "Installing golangci-lint $(GOLANGCI_LINT_VERSION)..." + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin $(GOLANGCI_LINT_VERSION) .PHONY: lint lint: getlint $(GOPATH)/bin/golangci-lint run --timeout 5m @@ -128,7 +128,7 @@ mock-gen: .PHONY: build-image build-image: - $(CONTAINER_ENGINE) build --pull --platform linux/amd64 --build-arg=GOLANGCI_LINT_VERSION -t backplane-cli-builder -f ./make.Dockerfile . + $(CONTAINER_ENGINE) build --pull --platform linux/amd64 --build-arg GOLANGCI_LINT_VERSION=$(GOLANGCI_LINT_VERSION) -t backplane-cli-builder -f ./make.Dockerfile . .PHONY: lint-in-container lint-in-container: build-image diff --git a/cmd/ocm-backplane/cloud/common.go b/cmd/ocm-backplane/cloud/common.go index e3f082ab..43b2a8e7 100644 --- a/cmd/ocm-backplane/cloud/common.go +++ b/cmd/ocm-backplane/cloud/common.go @@ -113,7 +113,7 @@ func (cfg *QueryConfig) GetCloudConsole() (*ConsoleResponse, error) { func (cfg *QueryConfig) getCloudConsoleFromPublicAPI(ocmToken string) (*ConsoleResponse, error) { logger.Debugln("Getting Cloud Console") - client, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.BackplaneConfiguration.URL, ocmToken, cfg.BackplaneConfiguration.ProxyURL) + client, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.URL, ocmToken, cfg.ProxyURL) if err != nil { return nil, err } @@ -173,7 +173,7 @@ func (cfg *QueryConfig) GetCloudCredentials() (bpCredentials.Response, error) { } func (cfg *QueryConfig) getCloudCredentialsFromBackplaneAPI(ocmToken string) (bpCredentials.Response, error) { - client, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.BackplaneConfiguration.URL, ocmToken, cfg.BackplaneConfiguration.ProxyURL) + client, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.URL, ocmToken, cfg.ProxyURL) if err != nil { return nil, err } @@ -243,15 +243,15 @@ func (cfg *QueryConfig) getIsolatedCredentials(ocmToken string) (aws.Credentials return aws.Credentials{}, fmt.Errorf("unable to extract email from given token: %w", err) } - if cfg.BackplaneConfiguration.AssumeInitialArn == "" { + if cfg.AssumeInitialArn == "" { // If not provided as an override, attempt to automatically set this based on OCM url switch cfg.OcmConnection.URL() { case productionOCMUrl: - cfg.BackplaneConfiguration.AssumeInitialArn = productionAssumeInitialArn + cfg.AssumeInitialArn = productionAssumeInitialArn case stagingOCMUrl: - cfg.BackplaneConfiguration.AssumeInitialArn = stagingAssumeInitialArn + cfg.AssumeInitialArn = stagingAssumeInitialArn case integrationOCMUrl: - cfg.BackplaneConfiguration.AssumeInitialArn = integrationAssumeInitialArn + cfg.AssumeInitialArn = integrationAssumeInitialArn default: logger.Infof("failed to automatically set assume-initial-arn based on OCM url: %s", cfg.OcmConnection.URL()) return aws.Credentials{}, errors.New("backplane config is missing required `assume-initial-arn` property") @@ -263,11 +263,11 @@ func (cfg *QueryConfig) getIsolatedCredentials(ocmToken string) (aws.Credentials stagingAssumeInitialArn, integrationAssumeInitialArn, }, - cfg.BackplaneConfiguration.AssumeInitialArn, + cfg.AssumeInitialArn, ) { - logger.Warnf("assume-initial-arn in backplane config is not set to a valid payer ARN, using: %s", cfg.BackplaneConfiguration.AssumeInitialArn) + logger.Warnf("assume-initial-arn in backplane config is not set to a valid payer ARN, using: %s", cfg.AssumeInitialArn) return aws.Credentials{}, fmt.Errorf("invalid assume-initial-arn: %s, must be one of: prod: %s, stage: %s, int: %s", - cfg.BackplaneConfiguration.AssumeInitialArn, + cfg.AssumeInitialArn, productionAssumeInitialArn, stagingAssumeInitialArn, integrationAssumeInitialArn, @@ -276,19 +276,19 @@ func (cfg *QueryConfig) getIsolatedCredentials(ocmToken string) (aws.Credentials } // Use AWS-specific proxy for initial STS client, fallback to regular proxy // Priority: 1) AWS proxy from config; 2) regular proxy from local backplane config - stsProxyURL := cfg.BackplaneConfiguration.GetAwsProxy() + stsProxyURL := cfg.GetAwsProxy() initialClient, err := StsClient(stsProxyURL) if err != nil { return aws.Credentials{}, fmt.Errorf("failed to create sts client: %w", err) } - seedCredentials, err := AssumeRoleWithJWT(ocmToken, cfg.BackplaneConfiguration.AssumeInitialArn, initialClient) + seedCredentials, err := AssumeRoleWithJWT(ocmToken, cfg.AssumeInitialArn, initialClient) if err != nil { return aws.Credentials{}, fmt.Errorf("failed to assume role using JWT: %w", err) } // Verify Sts connection with the seed credentials // Use AWS-specific proxy for STS operations - awsProxyURL := cfg.BackplaneConfiguration.GetAwsProxy() + awsProxyURL := cfg.GetAwsProxy() var stsClientConfig aws.Config if awsProxyURL != nil { @@ -317,7 +317,7 @@ func (cfg *QueryConfig) getIsolatedCredentials(ocmToken string) (aws.Credentials return aws.Credentials{}, fmt.Errorf("unable to connect to AWS STS endpoint (GetCallerIdentity failed): %w", err) } - backplaneClient, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.BackplaneConfiguration.URL, ocmToken, cfg.BackplaneConfiguration.ProxyURL) + backplaneClient, err := backplaneapi.DefaultClientUtils.GetBackplaneClient(cfg.URL, ocmToken, cfg.ProxyURL) if err != nil { return aws.Credentials{}, fmt.Errorf("failed to create backplane client with access token: %w", err) } @@ -386,7 +386,7 @@ func (cfg *QueryConfig) getIsolatedCredentials(ocmToken string) (aws.Credentials // Use AWS-specific proxy for role sequence, fallback to regular proxy // Priority: 1) AWS proxy from config, 2) regular proxy from config - roleSequenceProxyURL := cfg.BackplaneConfiguration.GetAwsProxy() + roleSequenceProxyURL := cfg.GetAwsProxy() targetCredentials, err := AssumeRoleSequence( seedClient, assumeRoleArnSessionSequence, @@ -405,7 +405,7 @@ func verifyTrustedIPAndGetPolicy(cfg *QueryConfig) (awsutil.PolicyDocument, erro // Use AWS-specific proxy for egress IP check, fallback to regular proxy // Priority: 1) AWS proxy from config, 2) regular proxy from config var egressProxyURL *url.URL - if proxyURLString := cfg.BackplaneConfiguration.GetAwsProxy(); proxyURLString != nil { + if proxyURLString := cfg.GetAwsProxy(); proxyURLString != nil { var err error egressProxyURL, err = url.Parse(*proxyURLString) if err != nil { @@ -453,7 +453,7 @@ func checkEgressIPImpl(client *http.Client, url string) (net.IP, error) { if err != nil { return nil, fmt.Errorf("failed to fetch IP: %w", err) } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() body, err := io.ReadAll(resp.Body) if err != nil { diff --git a/cmd/ocm-backplane/cloud/common_test.go b/cmd/ocm-backplane/cloud/common_test.go index 9a71a0b9..c81e1a02 100644 --- a/cmd/ocm-backplane/cloud/common_test.go +++ b/cmd/ocm-backplane/cloud/common_test.go @@ -104,7 +104,7 @@ var _ = Describe("getIsolatedCredentials", func() { Expect(err).To(Equal(fmt.Errorf("must provide non-empty cluster ID"))) }) It("should fail if wrong assume initial ARN is provided", func() { - testQueryConfig.BackplaneConfiguration.AssumeInitialArn = "arn:aws:iam::10000000:role/TEST_USER" + testQueryConfig.AssumeInitialArn = "arn:aws:iam::10000000:role/TEST_USER" _, err := testQueryConfig.getIsolatedCredentials(testOcmToken) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("invalid assume-initial-arn: arn:aws:iam::10000000:role/TEST_USER, must be one of:")) @@ -299,7 +299,7 @@ var _ = Describe("getIsolatedCredentials", func() { }) It("should return an error when response body is not a valid IP", func() { server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "not-an-ip") + _, _ = fmt.Fprint(w, "not-an-ip") })) client = server.Client() @@ -453,7 +453,7 @@ var _ = Describe("getIsolatedCredentials", func() { It("should successfully verify IP and return policy when IP is in trusted range", func() { // Mock the IP check to return a valid IP server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "209.10.10.10") // IP that matches our test trusted range + _, _ = fmt.Fprint(w, "209.10.10.10") // IP that matches our test trusted range })) defer server.Close() @@ -484,7 +484,7 @@ var _ = Describe("getIsolatedCredentials", func() { It("should fail when client IP is not in trusted range", func() { // Mock the IP check to return an untrusted IP server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "192.168.1.1") // IP that doesn't match our test trusted range + _, _ = fmt.Fprint(w, "192.168.1.1") // IP that doesn't match our test trusted range })) defer server.Close() @@ -513,7 +513,7 @@ var _ = Describe("getIsolatedCredentials", func() { It("should fail when AWS proxy URL is invalid", func() { // Set an invalid AWS proxy URL in configuration - testQueryConfig.BackplaneConfiguration.AwsProxy = aws.String("://invalid-url") + testQueryConfig.AwsProxy = aws.String("://invalid-url") // Call the function _, err := verifyTrustedIPAndGetPolicy(&testQueryConfig) @@ -526,7 +526,7 @@ var _ = Describe("getIsolatedCredentials", func() { Context("Execute getIsolatedCredentials with AwsProxy", func() { It("should use AwsProxy configuration for AWS STS calls", func() { // Set AWS proxy in configuration - testQueryConfig.BackplaneConfiguration.AwsProxy = aws.String("http://aws-proxy:8080") + testQueryConfig.AwsProxy = aws.String("http://aws-proxy:8080") // Mock CheckEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP @@ -595,8 +595,8 @@ var _ = Describe("getIsolatedCredentials", func() { It("should use AWS proxy when both ProxyURL and AwsProxy are configured", func() { // Set both explicit proxy and AWS proxy in configuration - testQueryConfig.BackplaneConfiguration.ProxyURL = aws.String("http://regular-proxy:9090") - testQueryConfig.BackplaneConfiguration.AwsProxy = aws.String("http://aws-proxy:8080") + testQueryConfig.ProxyURL = aws.String("http://regular-proxy:9090") + testQueryConfig.AwsProxy = aws.String("http://aws-proxy:8080") // Mock CheckEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP @@ -662,8 +662,8 @@ var _ = Describe("getIsolatedCredentials", func() { It("should use regular proxy when AwsProxy is not configured", func() { // Ensure AwsProxy is not set (should be nil by default) - testQueryConfig.BackplaneConfiguration.AwsProxy = nil - testQueryConfig.BackplaneConfiguration.ProxyURL = aws.String("http://regular-proxy:8080") + testQueryConfig.AwsProxy = nil + testQueryConfig.ProxyURL = aws.String("http://regular-proxy:8080") // Mock CheckEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP @@ -732,8 +732,8 @@ var _ = Describe("getIsolatedCredentials", func() { Context("Proxy separation verification", func() { It("should demonstrate traffic separation between AWS and Backplane API calls", func() { // Set different proxies for AWS and Backplane - testQueryConfig.BackplaneConfiguration.ProxyURL = aws.String("http://backplane-proxy:8080") - testQueryConfig.BackplaneConfiguration.AwsProxy = aws.String("http://aws-proxy:8080") + testQueryConfig.ProxyURL = aws.String("http://backplane-proxy:8080") + testQueryConfig.AwsProxy = aws.String("http://aws-proxy:8080") // Mock CheckEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP @@ -814,7 +814,7 @@ var _ = Describe("getIsolatedCredentials", func() { It("should handle proxy separation in verifyTrustedIPAndGetPolicy", func() { // Set AWS-specific proxy in configuration - testQueryConfig.BackplaneConfiguration.AwsProxy = aws.String("http://aws-proxy:8080") + testQueryConfig.AwsProxy = aws.String("http://aws-proxy:8080") // Mock checkEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP @@ -840,10 +840,10 @@ var _ = Describe("getIsolatedCredentials", func() { It("should fallback to regular proxy when AwsProxy is not configured (regression test)", func() { // Ensure AwsProxy is not set (should be nil by default) - testQueryConfig.BackplaneConfiguration.AwsProxy = nil + testQueryConfig.AwsProxy = nil // Should fall back to regular proxy behavior - testQueryConfig.BackplaneConfiguration.ProxyURL = aws.String("http://regular-proxy:8080") + testQueryConfig.ProxyURL = aws.String("http://regular-proxy:8080") // Mock CheckEgressIP to avoid real HTTP calls originalCheckEgressIP := CheckEgressIP diff --git a/cmd/ocm-backplane/cloud/console_test.go b/cmd/ocm-backplane/cloud/console_test.go index 31a4c601..683cbddb 100644 --- a/cmd/ocm-backplane/cloud/console_test.go +++ b/cmd/ocm-backplane/cloud/console_test.go @@ -78,11 +78,11 @@ var _ = Describe("Cloud console command", func() { // Disabled log output log.SetOutput(io.Discard) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) }) diff --git a/cmd/ocm-backplane/cloud/credentials_test.go b/cmd/ocm-backplane/cloud/credentials_test.go index 4b2ad746..eaed8363 100644 --- a/cmd/ocm-backplane/cloud/credentials_test.go +++ b/cmd/ocm-backplane/cloud/credentials_test.go @@ -135,11 +135,11 @@ var _ = Describe("Cloud console command", func() { // Disabled log output log.SetOutput(io.Discard) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/cloud/ssm.go b/cmd/ocm-backplane/cloud/ssm.go index 09167665..29552adc 100644 --- a/cmd/ocm-backplane/cloud/ssm.go +++ b/cmd/ocm-backplane/cloud/ssm.go @@ -182,9 +182,9 @@ func startSSMsession(cmd *cobra.Command, execCommand []string) error { } // Set AWS credentials in environment variables - os.Setenv("AWS_ACCESS_KEY_ID", creds.AccessKeyID) - os.Setenv("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey) - os.Setenv("AWS_SESSION_TOKEN", creds.SessionToken) + _ = os.Setenv("AWS_ACCESS_KEY_ID", creds.AccessKeyID) + _ = os.Setenv("AWS_SECRET_ACCESS_KEY", creds.SecretAccessKey) + _ = os.Setenv("AWS_SESSION_TOKEN", creds.SessionToken) // Load AWS SDK configuration with the custom HTTP client cfg, err := awsConfig.LoadDefaultConfig( diff --git a/cmd/ocm-backplane/cloud/ssm_test.go b/cmd/ocm-backplane/cloud/ssm_test.go index 7c12a578..b3145a7e 100644 --- a/cmd/ocm-backplane/cloud/ssm_test.go +++ b/cmd/ocm-backplane/cloud/ssm_test.go @@ -192,9 +192,9 @@ var _ = Describe("SSM command", func() { AfterEach(func() { ExecCommand = originalExecCommand ssmArgs.node = "" - os.Unsetenv("AWS_ACCESS_KEY_ID") - os.Unsetenv("AWS_SECRET_ACCESS_KEY") - os.Unsetenv("AWS_SESSION_TOKEN") + _ = os.Unsetenv("AWS_ACCESS_KEY_ID") + _ = os.Unsetenv("AWS_SECRET_ACCESS_KEY") + _ = os.Unsetenv("AWS_SESSION_TOKEN") }) Context("startSSMsession", func() { diff --git a/cmd/ocm-backplane/config/troubleshoot_test.go b/cmd/ocm-backplane/config/troubleshoot_test.go index 236945e2..0896ecf4 100644 --- a/cmd/ocm-backplane/config/troubleshoot_test.go +++ b/cmd/ocm-backplane/config/troubleshoot_test.go @@ -53,7 +53,7 @@ var _ = Describe("troubleshoot command", func() { Expect(err).To(BeNil()) // set backplane config env with temp config file - os.Setenv("BACKPLANE_CONFIG", f.Name()) + _ = os.Setenv("BACKPLANE_CONFIG", f.Name()) } BeforeEach(func() { @@ -146,7 +146,7 @@ var _ = Describe("troubleshoot command", func() { CurrentContext: "default/test123/anonymous", } It("should print error if anything wrong in oc config", func() { - os.Setenv("KUBECONFIG", "/fake/path") + _ = os.Setenv("KUBECONFIG", "/fake/path") o := troubleshootOptions{} err := o.checkOC() Expect(err).To(BeNil()) diff --git a/cmd/ocm-backplane/console/console_test.go b/cmd/ocm-backplane/console/console_test.go index 544d47ce..3919f4cf 100644 --- a/cmd/ocm-backplane/console/console_test.go +++ b/cmd/ocm-backplane/console/console_test.go @@ -52,7 +52,7 @@ var _ = Describe("console command", func() { mockEngine = ceMock.NewMockContainerEngine(mockCtrl) ocm.DefaultOCMInterface = mockOcmInterface - os.Setenv("CONTAINER_ENGINE", PODMAN) + _ = os.Setenv("CONTAINER_ENGINE", PODMAN) pullSecret = "testpullsecret" clusterID = "cluster123" @@ -95,7 +95,7 @@ var _ = Describe("console command", func() { }) AfterEach(func() { - os.Setenv("HTTPS_PROXY", "") + _ = os.Setenv("HTTPS_PROXY", "") mockCtrl.Finish() utils.RemoveTempKubeConfig() }) @@ -136,27 +136,27 @@ var _ = Describe("console command", func() { Context("when console command executes", func() { It("should read the openbrowser variable from environment variables and it is true", func() { setupConfig() - os.Setenv(EnvBrowserDefault, "true") + _ = os.Setenv(EnvBrowserDefault, "true") o := newConsoleOptions() err := o.determineOpenBrowser() - os.Setenv(EnvBrowserDefault, "") + _ = os.Setenv(EnvBrowserDefault, "") Expect(err).To(BeNil()) Expect(o.openBrowser).To(BeTrue()) }) It("should read the openbrowser variable from environment variables and it is false", func() { setupConfig() - os.Setenv(EnvBrowserDefault, "false") + _ = os.Setenv(EnvBrowserDefault, "false") o := newConsoleOptions() err := o.determineOpenBrowser() - os.Setenv(EnvBrowserDefault, "") + _ = os.Setenv(EnvBrowserDefault, "") Expect(err).To(BeNil()) Expect(o.openBrowser).To(BeFalse()) }) It("should read the openbrowser variable from environment variables and we it is undefined", func() { setupConfig() - os.Setenv(EnvBrowserDefault, "") + _ = os.Setenv(EnvBrowserDefault, "") o := newConsoleOptions() err := o.determineOpenBrowser() Expect(err).To(MatchError(ContainSubstring("unable to parse boolean value from environment variable"))) @@ -453,7 +453,7 @@ var _ = Describe("console command", func() { OpenshiftVersion("4.13.0").Build() // Set Browser opening to false - os.Setenv("BACKPLANE_DEFAULT_OPEN_BROWSER", "FALSE") + _ = os.Setenv("BACKPLANE_DEFAULT_OPEN_BROWSER", "FALSE") setupConfig() // Set some mock varibles, @@ -483,7 +483,7 @@ var _ = Describe("console command", func() { o.runContainers(ce, errs) Expect(errs).To(BeEmpty()) - os.Setenv("BACKPLANE_DEFAULT_OPEN_BROWSER", "") + _ = os.Setenv("BACKPLANE_DEFAULT_OPEN_BROWSER", "") setPath(oldpath) }) }) @@ -631,7 +631,7 @@ func createPathDocker() string { func createPath(binary string) string { oldpath := os.Getenv("PATH") setPath(oldpath + ":/tmp/tmp_bin") - err := os.MkdirAll("/tmp/tmp_bin", 0777) + err := os.MkdirAll("/tmp/tmp_bin", 0777) //nolint:gosec if err != nil { fmt.Printf("Failed to create the directory: %v\n", err) } @@ -642,7 +642,7 @@ func createPath(binary string) string { if err := os.Rename(dFile.Name(), "/tmp/tmp_bin/"+binary); err != nil { fmt.Printf("Failed to rename the file: %v\n", err) } - if err := os.Chmod("/tmp/tmp_bin/"+binary, 0777); err != nil { + if err := os.Chmod("/tmp/tmp_bin/"+binary, 0777); err != nil { //nolint:gosec fmt.Printf("Failed to chmod the file: %v\n", err) } return oldpath diff --git a/cmd/ocm-backplane/login/login_test.go b/cmd/ocm-backplane/login/login_test.go index 96e95095..955d8e00 100644 --- a/cmd/ocm-backplane/login/login_test.go +++ b/cmd/ocm-backplane/login/login_test.go @@ -119,9 +119,9 @@ var _ = Describe("Login command", func() { globalOpts.Service = false globalOpts.BackplaneURL = "" globalOpts.ProxyURL = "" - os.Setenv("HTTPS_PROXY", "") - os.Unsetenv("BACKPLANE_CONFIG") - os.Remove(bpConfigPath) + _ = os.Setenv("HTTPS_PROXY", "") + _ = os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Remove(bpConfigPath) mockCtrl.Finish() utils.RemoveTempKubeConfig() }) @@ -191,7 +191,7 @@ var _ = Describe("Login command", func() { err := utils.CreateTempKubeConfig(nil) Expect(err).To(BeNil()) globalOpts.ProxyURL = "https://squid.myproxy.com" - os.Setenv("HTTPS_PROXY", "https://squid.myproxy.com") + _ = os.Setenv("HTTPS_PROXY", "https://squid.myproxy.com") mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes() mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil) mockOcmInterface.EXPECT().GetTargetCluster(testClusterID).Return(trueClusterID, testClusterID, nil) @@ -496,7 +496,7 @@ var _ = Describe("Login command", func() { // Create a temporary JSON configuration file in the temp directory for testing purposes. tempDir := os.TempDir() bpConfigPath = filepath.Join(tempDir, "mock.json") - tempFile, err := os.Create(bpConfigPath) + tempFile, err := os.Create(bpConfigPath) //nolint:gosec Expect(err).To(BeNil()) testData := config.BackplaneConfiguration{ @@ -513,7 +513,7 @@ var _ = Describe("Login command", func() { _, err = tempFile.Write(jsonData) Expect(err).To(BeNil()) - os.Setenv("BACKPLANE_CONFIG", bpConfigPath) + _ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath) err = runLogin(nil, nil) @@ -532,7 +532,7 @@ var _ = Describe("Login command", func() { // Create a temporary JSON configuration file in the temp directory for testing purposes. tempDir := os.TempDir() bpConfigPath = filepath.Join(tempDir, "mock.json") - tempFile, err := os.Create(bpConfigPath) + tempFile, err := os.Create(bpConfigPath) //nolint:gosec Expect(err).To(BeNil()) testData := config.BackplaneConfiguration{ @@ -549,7 +549,7 @@ var _ = Describe("Login command", func() { _, err = tempFile.Write(jsonData) Expect(err).To(BeNil()) - os.Setenv("BACKPLANE_CONFIG", bpConfigPath) + _ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath) err = runLogin(nil, nil) @@ -568,7 +568,7 @@ var _ = Describe("Login command", func() { // Create a temporary JSON configuration file in the temp directory for testing purposes. tempDir := os.TempDir() bpConfigPath = filepath.Join(tempDir, "mock.json") - tempFile, err := os.Create(bpConfigPath) + tempFile, err := os.Create(bpConfigPath) //nolint:gosec Expect(err).To(BeNil()) testData := config.BackplaneConfiguration{ @@ -583,7 +583,7 @@ var _ = Describe("Login command", func() { _, err = tempFile.Write(jsonData) Expect(err).To(BeNil()) - os.Setenv("BACKPLANE_CONFIG", bpConfigPath) + _ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath) err = runLogin(nil, nil) diff --git a/cmd/ocm-backplane/logout/logout_test.go b/cmd/ocm-backplane/logout/logout_test.go index ceb10df6..fb7d1c83 100644 --- a/cmd/ocm-backplane/logout/logout_test.go +++ b/cmd/ocm-backplane/logout/logout_test.go @@ -116,13 +116,13 @@ var _ = Describe("Logout command", func() { CurrentContext: "default/myopenshiftcluster/example.openshift", } - os.Setenv(info.BackplaneURLEnvName, backplaneAPIURI) + _ = os.Setenv(info.BackplaneURLEnvName, backplaneAPIURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { utils.RemoveTempKubeConfig() - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/managedJob/createManagedJob.go b/cmd/ocm-backplane/managedJob/createManagedJob.go index 63778cbe..3eaade46 100644 --- a/cmd/ocm-backplane/managedJob/createManagedJob.go +++ b/cmd/ocm-backplane/managedJob/createManagedJob.go @@ -136,22 +136,22 @@ func runCreateManagedJob(cmd *cobra.Command, args []string) (err error) { // wait for job to be finished if options.wait { - fmt.Fprintf(cmd.OutOrStdout(), "\nWaiting for %s to be finished ...", *job.JobId) + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "\nWaiting for %s to be finished ...", *job.JobId) statusMessage, err := waitForCreateJob(client, job) if err != nil { return err } - fmt.Fprintf(cmd.OutOrStdout(), "\n%s\n.", statusMessage) + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "\n%s\n.", statusMessage) } // stream logs if flag set if options.logs { - fmt.Fprintf(cmd.OutOrStdout(), "fetching logs for job %s", *job.JobId) + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "fetching logs for job %s", *job.JobId) err := fetchJobLogs(client, job) if err != nil { return err } - fmt.Fprintf(cmd.OutOrStdout(), "") + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "") } return nil diff --git a/cmd/ocm-backplane/managedJob/createManagedJob_test.go b/cmd/ocm-backplane/managedJob/createManagedJob_test.go index 83ba515a..e47b64cb 100644 --- a/cmd/ocm-backplane/managedJob/createManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/createManagedJob_test.go @@ -115,12 +115,12 @@ var _ = Describe("managedJob create command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go b/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go index 63b20978..3546d73b 100644 --- a/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/deleteManagedJob_test.go @@ -68,12 +68,12 @@ var _ = Describe("managedJob delete command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/managedJob/getManagedJob_test.go b/cmd/ocm-backplane/managedJob/getManagedJob_test.go index aa125b7a..bb746d35 100644 --- a/cmd/ocm-backplane/managedJob/getManagedJob_test.go +++ b/cmd/ocm-backplane/managedJob/getManagedJob_test.go @@ -123,12 +123,12 @@ var _ = Describe("managedJob get command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/remediation/remediation_test.go b/cmd/ocm-backplane/remediation/remediation_test.go index ceb3047a..0cb52f68 100644 --- a/cmd/ocm-backplane/remediation/remediation_test.go +++ b/cmd/ocm-backplane/remediation/remediation_test.go @@ -90,10 +90,10 @@ var _ = Describe("New Remediation command", func() { globalOpts.Service = false globalOpts.BackplaneURL = "" globalOpts.ProxyURL = "" - os.Setenv("HTTPS_PROXY", "") - os.Setenv("HTTP_PROXY", "") - os.Unsetenv("BACKPLANE_CONFIG") - os.Remove(bpConfigPath) + _ = os.Setenv("HTTPS_PROXY", "") + _ = os.Setenv("HTTP_PROXY", "") + _ = os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Remove(bpConfigPath) mockCtrl.Finish() utils.RemoveTempKubeConfig() }) @@ -128,7 +128,7 @@ var _ = Describe("New Remediation command", func() { It("Should use the Proxy URL set in global opts", func() { globalOpts.ProxyURL = "https://squid.example.com" - os.Setenv("HTTPS_PROXY", "https://squid.example.com") + _ = os.Setenv("HTTPS_PROXY", "https://squid.example.com") mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes() mockClientUtil.EXPECT().SetClientProxyURL(globalOpts.ProxyURL).Return(nil) diff --git a/cmd/ocm-backplane/script/describeScript_test.go b/cmd/ocm-backplane/script/describeScript_test.go index 281e9780..11e4f5cc 100644 --- a/cmd/ocm-backplane/script/describeScript_test.go +++ b/cmd/ocm-backplane/script/describeScript_test.go @@ -84,12 +84,12 @@ var _ = Describe("describe script command", func() { // Clear config file _ = clientcmd.ModifyConfig(clientcmd.NewDefaultPathOptions(), api.Config{}, true) - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/script/listScripts_test.go b/cmd/ocm-backplane/script/listScripts_test.go index 4b112b14..8dfb93c3 100644 --- a/cmd/ocm-backplane/script/listScripts_test.go +++ b/cmd/ocm-backplane/script/listScripts_test.go @@ -79,12 +79,12 @@ var _ = Describe("list script command", func() { } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") utils.RemoveTempKubeConfig() mockCtrl.Finish() }) diff --git a/cmd/ocm-backplane/testJob/createTestJob.go b/cmd/ocm-backplane/testJob/createTestJob.go index 5840a695..d8340a2c 100644 --- a/cmd/ocm-backplane/testJob/createTestJob.go +++ b/cmd/ocm-backplane/testJob/createTestJob.go @@ -244,7 +244,7 @@ func createTestScriptFromFiles(sourceDir string, dryRun bool, jobParams map[stri metaFile := sourceDir + "metadata.yaml" // Read the yaml file from cwd - yamlFile, err := os.ReadFile(metaFile) + yamlFile, err := os.ReadFile(metaFile) //nolint:gosec if err != nil { logger.Errorf("Error reading metadata yaml: %v, ensure either you are in a script directory or you have specified the correct source dir", err) return nil, err @@ -288,7 +288,7 @@ func createTestScriptFromFiles(sourceDir string, dryRun bool, jobParams map[stri scriptFile := sourceDir + scriptMeta.File - fileBody, err := os.ReadFile(scriptFile) + fileBody, err := os.ReadFile(scriptFile) //nolint:gosec fileBodyStr := string(fileBody) @@ -367,7 +367,7 @@ func inlineLibrarySourceFiles(script string, scriptPath string) (string, error) managedScriptsDir := strings.TrimSpace(out.String()) - fileBody, err := os.ReadFile(managedScriptsDir + "/scripts/" + libraryPath) + fileBody, err := os.ReadFile(managedScriptsDir + "/scripts/" + libraryPath) //nolint:gosec if err != nil { return "", err } diff --git a/cmd/ocm-backplane/testJob/createTestJob_test.go b/cmd/ocm-backplane/testJob/createTestJob_test.go index ed85372b..16dfa468 100644 --- a/cmd/ocm-backplane/testJob/createTestJob_test.go +++ b/cmd/ocm-backplane/testJob/createTestJob_test.go @@ -118,12 +118,12 @@ var _ = Describe("testJob create command", func() { StatusCode: http.StatusOK, } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") _ = os.RemoveAll(tempDir) // Clear kube config file utils.RemoveTempKubeConfig() @@ -187,7 +187,7 @@ var _ = Describe("testJob create command", func() { sourceDir, _ = os.MkdirTemp("", "manualScriptDir") _ = os.WriteFile(path.Join(sourceDir, "metadata.yaml"), []byte(MetadataYaml), 0600) _ = os.WriteFile(path.Join(sourceDir, "script.sh"), []byte("echo hello"), 0600) - defer os.RemoveAll(sourceDir) + defer func() { _ = os.RemoveAll(sourceDir) }() _ = os.Chdir(workingDir) @@ -224,7 +224,7 @@ var _ = Describe("testJob create command", func() { }) It("Should able use the current logged in cluster if non specified and retrieve from config file", func() { - os.Setenv(info.BackplaneURLEnvName, "https://api-backplane.apps.something.com") + _ = os.Setenv(info.BackplaneURLEnvName, "https://api-backplane.apps.something.com") mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes() mockOcmInterface.EXPECT().IsProduction().Return(false, nil) err := utils.CreateTempKubeConfig(nil) @@ -339,10 +339,10 @@ echo_touch "Hello" } `, tempDir) - GetGitRepoPath = exec.Command("echo", tempDir) + GetGitRepoPath = exec.Command("echo", tempDir) //nolint:gosec // tmp/createJobTest3397561583 _ = os.WriteFile(path.Join(tempDir, "script.sh"), []byte(script), 0600) - _ = os.Mkdir(path.Join(tempDir, "scripts"), 0755) + _ = os.Mkdir(path.Join(tempDir, "scripts"), 0755) //nolint:gosec _ = os.WriteFile(path.Join(tempDir, "scripts", "lib.sh"), []byte(lib), 0600) mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes() mockOcmInterface.EXPECT().IsProduction().Return(false, nil) diff --git a/cmd/ocm-backplane/testJob/getTestJob_test.go b/cmd/ocm-backplane/testJob/getTestJob_test.go index 64dd8f96..4fcd3895 100644 --- a/cmd/ocm-backplane/testJob/getTestJob_test.go +++ b/cmd/ocm-backplane/testJob/getTestJob_test.go @@ -76,12 +76,12 @@ var _ = Describe("testJob get command", func() { StatusCode: http.StatusOK, } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BackplaneURLEnvName, proxyURI) + _ = os.Setenv(info.BackplaneURLEnvName, proxyURI) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) AfterEach(func() { - os.Setenv(info.BackplaneURLEnvName, "") + _ = os.Setenv(info.BackplaneURLEnvName, "") _ = os.RemoveAll(tempDir) mockCtrl.Finish() }) diff --git a/internal/github/github.go b/internal/github/github.go index bb70e3cc..9358e086 100644 --- a/internal/github/github.go +++ b/internal/github/github.go @@ -107,7 +107,7 @@ func (c *Client) get(ctx context.Context, url string) ([]byte, error) { return nil, fmt.Errorf("running request for %q: %w", url, err) } - defer res.Body.Close() + defer func() { _ = res.Body.Close() }() if res.StatusCode != http.StatusOK { return nil, ErrRequestFailed diff --git a/internal/upgrade/upgrade.go b/internal/upgrade/upgrade.go index 8112a938..23d4b8c4 100644 --- a/internal/upgrade/upgrade.go +++ b/internal/upgrade/upgrade.go @@ -96,10 +96,9 @@ func (c *Cmd) UpgradePlugin(ctx context.Context, currentVersion string) error { if err := c.cfg.Writer.Write(binPath, latestBin); err != nil { return fmt.Errorf("writing new binary: %w", err) - } else { - successMessage := fmt.Sprintf("Backplane CLI has been upgraded to %s", latestVersion.TagName) - fmt.Fprintln(c.cfg.Out, successMessage) } + successMessage := fmt.Sprintf("Backplane CLI has been upgraded to %s", latestVersion.TagName) + _, _ = fmt.Fprintln(c.cfg.Out, successMessage) return nil } @@ -159,7 +158,7 @@ func confirmUpgrade(latest Release, c *Cmd) bool { message := fmt.Sprintf( "A newer version %q is available.\nWould you like to upgrade? (y/N)", latest.TagName, ) - fmt.Fprintln(c.cfg.Out, message) + _, _ = fmt.Fprintln(c.cfg.Out, message) input, _ := c.cfg.Reader.ReadString('\n') diff --git a/make.Dockerfile b/make.Dockerfile index e65dfc8a..5b0d9b66 100644 --- a/make.Dockerfile +++ b/make.Dockerfile @@ -3,11 +3,12 @@ ARG GOLANGCI_LINT_VERSION FROM registry.access.redhat.com/ubi8/ubi RUN yum install -y ca-certificates git go-toolset make -ENV PATH="/root/go/bin:${PATH}" + +ENV GOPATH=/go +ENV PATH="$GOPATH/bin:${PATH}" +RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b ${GOPATH}/bin ${GOLANGCI_LINT_VERSION} ADD https://password.corp.redhat.com/RH-IT-Root-CA.crt /etc/pki/ca-trust/source/anchors/ RUN update-ca-trust extract -RUN curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin ${GOLANGCI_LINT_VERSION} - RUN go install github.com/golang/mock/mockgen@v1.6.0 diff --git a/pkg/accessrequest/accessRequest.go b/pkg/accessrequest/accessRequest.go index aac6ff5c..8cffdabe 100644 --- a/pkg/accessrequest/accessRequest.go +++ b/pkg/accessrequest/accessRequest.go @@ -65,10 +65,10 @@ func PrintAccessRequest(clusterID string, accessRequest *acctrspv1.AccessRequest fmt.Printf("Active access request for cluster '%s':\n", clusterID) fmt.Printf(" Status : %s\n", accessRequestStatusState) - switch { - case accessRequestStatusState == acctrspv1.AccessRequestStateApproved: + switch accessRequestStatusState { + case acctrspv1.AccessRequestStateApproved: fmt.Printf(" Approval expires at : %s\n", accessRequestStatus.ExpiresAt()) - case accessRequestStatusState == acctrspv1.AccessRequestStatePending: + case acctrspv1.AccessRequestStatePending: fmt.Printf(" Expires at : %s\n", accessRequest.DeadlineAt()) fmt.Printf(" Requested approval duration: %s\n", accessRequest.Duration()) } diff --git a/pkg/accessrequest/accessRequest_test.go b/pkg/accessrequest/accessRequest_test.go index abc6d884..3c410b26 100644 --- a/pkg/accessrequest/accessRequest_test.go +++ b/pkg/accessrequest/accessRequest_test.go @@ -43,13 +43,13 @@ func (matcher IssueMatcher) String() string { func writeConfig(jsonData []byte) { tempDir := os.TempDir() bpConfigPath := filepath.Join(tempDir, "mock.json") - tempFile, err := os.Create(bpConfigPath) + tempFile, err := os.Create(bpConfigPath) //nolint:gosec Expect(err).To(BeNil()) _, err = tempFile.Write(jsonData) Expect(err).To(BeNil()) - os.Setenv("BACKPLANE_CONFIG", bpConfigPath) + _ = os.Setenv("BACKPLANE_CONFIG", bpConfigPath) } var _ = Describe(testDesc, func() { diff --git a/pkg/ai/mcp/backplane_cluster_resource.go b/pkg/ai/mcp/backplane_cluster_resource.go index 0817f9ae..f3f07c18 100644 --- a/pkg/ai/mcp/backplane_cluster_resource.go +++ b/pkg/ai/mcp/backplane_cluster_resource.go @@ -69,7 +69,7 @@ func BackplaneClusterResource(ctx context.Context, request *mcp.CallToolRequest, } // Execute the oc command - cmd := exec.CommandContext(ctx, "oc", args...) + cmd := exec.CommandContext(ctx, "oc", args...) //nolint:gosec // Capture both stdout and stderr output, err := cmd.CombinedOutput() diff --git a/pkg/ai/mcp/backplane_info_test.go b/pkg/ai/mcp/backplane_info_test.go index 35465d1c..356b3feb 100644 --- a/pkg/ai/mcp/backplane_info_test.go +++ b/pkg/ai/mcp/backplane_info_test.go @@ -31,10 +31,10 @@ var _ = Describe("BackplaneInfo", func() { info.DefaultInfoService = mockInfoService // Clear all environment variables that might affect configuration - os.Unsetenv("BACKPLANE_URL") - os.Unsetenv("HTTPS_PROXY") - os.Unsetenv("BACKPLANE_AWS_PROXY") - os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Unsetenv("BACKPLANE_URL") + _ = os.Unsetenv("HTTPS_PROXY") + _ = os.Unsetenv("BACKPLANE_AWS_PROXY") + _ = os.Unsetenv("BACKPLANE_CONFIG") // Clear viper settings to ensure clean state viper.Reset() @@ -47,11 +47,11 @@ var _ = Describe("BackplaneInfo", func() { info.DefaultInfoService = originalInfoService // Clean up environment variables - os.Unsetenv("BACKPLANE_URL") - os.Unsetenv("HTTPS_PROXY") - os.Unsetenv("BACKPLANE_AWS_PROXY") - os.Unsetenv("BACKPLANE_CONFIG") - os.Unsetenv("SHELL") + _ = os.Unsetenv("BACKPLANE_URL") + _ = os.Unsetenv("HTTPS_PROXY") + _ = os.Unsetenv("BACKPLANE_AWS_PROXY") + _ = os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Unsetenv("SHELL") // Clear viper settings viper.Reset() @@ -63,9 +63,9 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("1.2.3").Times(1) // Set up environment for configuration - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") - os.Setenv("HTTPS_PROXY", "https://proxy.example.com:8080") - os.Setenv("BACKPLANE_AWS_PROXY", "https://aws-proxy.example.com:8080") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("HTTPS_PROXY", "https://proxy.example.com:8080") + _ = os.Setenv("BACKPLANE_AWS_PROXY", "https://aws-proxy.example.com:8080") // Set up viper configuration viper.Set("session-dir", "custom-session") @@ -99,9 +99,9 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("2.0.0").Times(1) // Set up minimal environment for configuration - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") // Explicitly set empty proxy to override system defaults - os.Setenv("HTTPS_PROXY", "") + _ = os.Setenv("HTTPS_PROXY", "") // Set up viper configuration viper.Set("govcloud", false) @@ -127,7 +127,7 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("unknown").Times(1) // Set up minimal environment - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) // Execute the function @@ -148,8 +148,8 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("3.0.0").Times(1) // Set up minimal environment - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") - os.Setenv("SHELL", "/bin/zsh") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("SHELL", "/bin/zsh") viper.Set("govcloud", false) // Execute the function @@ -173,7 +173,7 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("1.1.0").Times(1) // Set up environment - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) // Don't set session-dir, should use default @@ -197,7 +197,7 @@ var _ = Describe("BackplaneInfo", func() { mockInfoService.EXPECT().GetVersion().Return("1.0.0").Times(1) // Set up minimal environment - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) // Execute with empty input diff --git a/pkg/ai/mcp/mcp_tool_integration_test.go b/pkg/ai/mcp/mcp_tool_integration_test.go index 6474828d..7ef43be2 100644 --- a/pkg/ai/mcp/mcp_tool_integration_test.go +++ b/pkg/ai/mcp/mcp_tool_integration_test.go @@ -40,10 +40,10 @@ var _ = Describe("MCP Tool Integration", func() { info.DefaultInfoService = mockInfoService // Clear environment and viper for clean tests - os.Unsetenv("BACKPLANE_URL") - os.Unsetenv("HTTPS_PROXY") - os.Unsetenv("BACKPLANE_AWS_PROXY") - os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Unsetenv("BACKPLANE_URL") + _ = os.Unsetenv("HTTPS_PROXY") + _ = os.Unsetenv("BACKPLANE_AWS_PROXY") + _ = os.Unsetenv("BACKPLANE_CONFIG") viper.Reset() }) @@ -56,11 +56,11 @@ var _ = Describe("MCP Tool Integration", func() { info.DefaultInfoService = originalInfoService // Clean up environment - os.Unsetenv("BACKPLANE_URL") - os.Unsetenv("HTTPS_PROXY") - os.Unsetenv("BACKPLANE_AWS_PROXY") - os.Unsetenv("BACKPLANE_CONFIG") - os.Unsetenv("SHELL") + _ = os.Unsetenv("BACKPLANE_URL") + _ = os.Unsetenv("HTTPS_PROXY") + _ = os.Unsetenv("BACKPLANE_AWS_PROXY") + _ = os.Unsetenv("BACKPLANE_CONFIG") + _ = os.Unsetenv("SHELL") viper.Reset() }) @@ -164,8 +164,8 @@ var _ = Describe("MCP Tool Integration", func() { mockInfoService.EXPECT().GetVersion().Return("1.5.0").Times(1) // Set up environment for configuration - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") - os.Setenv("HTTPS_PROXY", "https://proxy.example.com:8080") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("HTTPS_PROXY", "https://proxy.example.com:8080") viper.Set("govcloud", false) viper.Set("display-cluster-info", true) @@ -197,7 +197,7 @@ var _ = Describe("MCP Tool Integration", func() { mockInfoService.EXPECT().GetVersion().Return("2.0.0").Times(1) // Set up minimal environment - os.Setenv("BACKPLANE_URL", "https://test.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://test.backplane.example.com") viper.Set("govcloud", false) input := mcptools.BackplaneInfoInput{} @@ -217,7 +217,7 @@ var _ = Describe("MCP Tool Integration", func() { // Mock version service for actual call mockInfoService.EXPECT().GetVersion().Return("schema-test").Times(1) - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) // The BackplaneInfoInput struct should work with MCP even though it's empty @@ -255,9 +255,9 @@ var _ = Describe("MCP Tool Integration", func() { mockInfoService.EXPECT().GetVersion().Return("3.1.0").Times(1) // Set up comprehensive configuration - os.Setenv("BACKPLANE_URL", "https://prod.backplane.example.com") - os.Setenv("HTTPS_PROXY", "https://corporate-proxy.example.com:8080") - os.Setenv("SHELL", "/bin/zsh") + _ = os.Setenv("BACKPLANE_URL", "https://prod.backplane.example.com") + _ = os.Setenv("HTTPS_PROXY", "https://corporate-proxy.example.com:8080") + _ = os.Setenv("SHELL", "/bin/zsh") viper.Set("session-dir", "custom-backplane-sessions") viper.Set("display-cluster-info", true) viper.Set("govcloud", false) @@ -311,7 +311,7 @@ var _ = Describe("MCP Tool Integration", func() { mockInfoService.EXPECT().GetVersion().Return("perf-test").Times(3) // Set up minimal environment - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) input := mcptools.BackplaneInfoInput{} @@ -339,7 +339,7 @@ var _ = Describe("MCP Tool Integration", func() { // Mock info service mockInfoService.EXPECT().GetVersion().Return("consistency-test").Times(2) - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) // Alternate between login and info calls @@ -440,7 +440,7 @@ var _ = Describe("MCP Tool Integration", func() { // Test info tool mockInfoService.EXPECT().GetVersion().Return("protocol-test").Times(1) - os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") + _ = os.Setenv("BACKPLANE_URL", "https://api.backplane.example.com") viper.Set("govcloud", false) infoInput := mcptools.BackplaneInfoInput{} diff --git a/pkg/awsutil/sts.go b/pkg/awsutil/sts.go index e3fe717b..1af29c73 100644 --- a/pkg/awsutil/sts.go +++ b/pkg/awsutil/sts.go @@ -244,7 +244,7 @@ func GetSigninToken(awsCredentials aws.Credentials, region string) (*AWSSigninTo if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("failed to get signin token from %v, status code %d", baseFederationURL, res.StatusCode) } - defer res.Body.Close() + defer func() { _ = res.Body.Close() }() body, err := io.ReadAll(res.Body) if err != nil { diff --git a/pkg/cli/config/config_test.go b/pkg/cli/config/config_test.go index 91f6c49f..818fc574 100644 --- a/pkg/cli/config/config_test.go +++ b/pkg/cli/config/config_test.go @@ -172,9 +172,9 @@ func TestValidateConfig(t *testing.T) { // Set up environment variable if tt.envProxy != "" { - os.Setenv(info.BackplaneProxyEnvName, tt.envProxy) + _ = os.Setenv(info.BackplaneProxyEnvName, tt.envProxy) } else { - os.Unsetenv(info.BackplaneProxyEnvName) + _ = os.Unsetenv(info.BackplaneProxyEnvName) } // Validate config diff --git a/pkg/cli/session/session.go b/pkg/cli/session/session.go index e129b28d..f19b8130 100644 --- a/pkg/cli/session/session.go +++ b/pkg/cli/session/session.go @@ -175,7 +175,7 @@ func (e *BackplaneSession) Start() error { if shell != "" { fmt.Print("Switching to Backplane session " + e.Options.Alias + "\n") - cmd := exec.Command(shell) + cmd := exec.Command(shell) //nolint:gosec path := filepath.Clean(e.Path + "/.ocenv") file, err := os.Open(path) @@ -222,7 +222,7 @@ func (e *BackplaneSession) Delete() error { // ensureEnvDir create session dirs if it's not exist func (e *BackplaneSession) ensureEnvDir() error { if _, err := os.Stat(e.Path); errors.Is(err, os.ErrNotExist) { - err := os.MkdirAll(e.Path, os.ModePerm) + err := os.MkdirAll(e.Path, 0750) if err != nil { return err } @@ -253,7 +253,7 @@ PATH=` + e.Path + `/bin:` + os.Getenv("PATH") + ` log.Fatal(err) } defer func(dirEnvFile *os.File) { - dirEnvFile.Close() + _ = dirEnvFile.Close() }(dirEnvFile) zshEnvFile, err := e.ensureFile(e.Path + "/.zshenv") @@ -294,7 +294,7 @@ func (e *BackplaneSession) createHistoryFile() error { // createBins create bins inside the session folder bin dir func (e *BackplaneSession) createBins() error { if _, err := os.Stat(e.binPath()); errors.Is(err, os.ErrNotExist) { - err := os.Mkdir(e.binPath(), os.ModePerm) + err := os.Mkdir(e.binPath(), 0750) if err != nil { log.Fatal(err) } @@ -334,7 +334,7 @@ func (e *BackplaneSession) createBin(cmd string, content string) error { if err != nil { return fmt.Errorf("error writing to file %s: %v", path, err) } - err = os.Chmod(path, 0700) + err = os.Chmod(path, 0700) //nolint:gosec if err != nil { return fmt.Errorf("can't update permissions on file %s: %v", path, err) } diff --git a/pkg/cli/session/session_test.go b/pkg/cli/session/session_test.go index e771b5d0..1868b156 100644 --- a/pkg/cli/session/session_test.go +++ b/pkg/cli/session/session_test.go @@ -84,7 +84,7 @@ var _ = Describe("Backplane Session Unit test", func() { } fakeResp.Header.Add("Content-Type", "json") - os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) + _ = os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) diff --git a/pkg/container/container_docker.go b/pkg/container/container_docker.go index efecd3b6..b2b0db36 100644 --- a/pkg/container/container_docker.go +++ b/pkg/container/container_docker.go @@ -185,7 +185,7 @@ func dockerPutFileToMount(filename string, content []byte) error { } // change permission as a work around to gosec - if err = os.Chmod(dstFileName, 0644); err != nil { + if err = os.Chmod(dstFileName, 0644); err != nil { //nolint:gosec logger.Debugf("change permission to 0644 for %s", dstFileName) return err } diff --git a/pkg/container/container_podman.go b/pkg/container/container_podman.go index f99991d6..f504871e 100644 --- a/pkg/container/container_podman.go +++ b/pkg/container/container_podman.go @@ -153,7 +153,7 @@ func (ce *podmanLinux) RunMonitorPlugin(containerName string, consoleContainerNa // filename should be name only, not a path func (ce *podmanLinux) PutFileToMount(filename string, content []byte) error { // ensure the directory exists - err := os.MkdirAll(ce.fileMountDir, os.ModePerm) + err := os.MkdirAll(ce.fileMountDir, os.ModePerm) //nolint:gosec if err != nil { return err } @@ -174,7 +174,7 @@ func (ce *podmanLinux) PutFileToMount(filename string, content []byte) error { } // change permission as a work around to gosec - if err = os.Chmod(dstFileName, 0640); err != nil { + if err = os.Chmod(dstFileName, 0640); err != nil { //nolint:gosec logger.Debugf("change permission to 0640 for %s", dstFileName) return err } diff --git a/pkg/container/container_test.go b/pkg/container/container_test.go index f4c75480..22f27e17 100644 --- a/pkg/container/container_test.go +++ b/pkg/container/container_test.go @@ -33,7 +33,7 @@ var _ = Describe("console container implementation", func() { mockOcmInterface = ocmMock.NewMockOCMInterface(mockCtrl) ocm.DefaultOCMInterface = mockOcmInterface - os.Setenv("CONTAINER_ENGINE", PODMAN) + _ = os.Setenv("CONTAINER_ENGINE", PODMAN) capturedCommands = nil createCommand = func(prog string, args ...string) *exec.Cmd { @@ -58,7 +58,7 @@ var _ = Describe("console container implementation", func() { }) AfterEach(func() { - os.Setenv("HTTPS_PROXY", "") + _ = os.Setenv("HTTPS_PROXY", "") mockCtrl.Finish() utils.RemoveTempKubeConfig() }) diff --git a/pkg/elevate/elevate.go b/pkg/elevate/elevate.go index af48e1ce..523b8b1a 100644 --- a/pkg/elevate/elevate.go +++ b/pkg/elevate/elevate.go @@ -58,10 +58,10 @@ func RunElevate(argv []string) error { defer func() { if oldKubeconfigDefined { logger.Debugln("Will set KUBECONFIG variable to original", oldKubeconfigPath) - os.Setenv("KUBECONFIG", oldKubeconfigPath) + _ = os.Setenv("KUBECONFIG", oldKubeconfigPath) } else { logger.Debugln("Will unset KUBECONFIG variable") - os.Unsetenv("KUBECONFIG") + _ = os.Unsetenv("KUBECONFIG") } }() diff --git a/pkg/elevate/elevate_test.go b/pkg/elevate/elevate_test.go index 0ced580e..0b9dad68 100644 --- a/pkg/elevate/elevate_test.go +++ b/pkg/elevate/elevate_test.go @@ -84,7 +84,7 @@ func TestHelperProcessSuccess(t *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } - fmt.Fprintf(os.Stdout, "") + _, _ = fmt.Fprintf(os.Stdout, "") os.Exit(0) } @@ -118,7 +118,7 @@ func TestRunElevate(t *testing.T) { if err != nil { t.Fatal(err) } - defer os.RemoveAll(tmpDir) + defer func() { _ = os.RemoveAll(tmpDir) }() // We utilize the fact that elevate honors KUBECONFIG in order to not clobber the users real ~/.kube/config kubeconfigPath := tmpDir + "config" diff --git a/pkg/login/additional_login_detector.go b/pkg/login/additional_login_detector.go index 9136307b..2287dc27 100644 --- a/pkg/login/additional_login_detector.go +++ b/pkg/login/additional_login_detector.go @@ -107,13 +107,13 @@ func FindOtherSessions(clientset kubernetes.Interface, config *rest.Config, user func PrintSessions(w io.Writer, sessions map[string]int) { if len(sessions) == 0 { - fmt.Fprintf(w, "There are no other backplane users logged in.\n") + _, _ = fmt.Fprintf(w, "There are no other backplane users logged in.\n") return } - fmt.Fprintf(w, "Checking for other backplane sessions:\n") + _, _ = fmt.Fprintf(w, "Checking for other backplane sessions:\n") for sessionRole, sessionCount := range sessions { - fmt.Fprintf(w, " - There are %d other users logged in under the %s role.\n", sessionCount, sessionRole) + _, _ = fmt.Fprintf(w, " - There are %d other users logged in under the %s role.\n", sessionCount, sessionRole) } } diff --git a/pkg/login/additional_login_detector_test.go b/pkg/login/additional_login_detector_test.go index 7cc73708..3ad26430 100644 --- a/pkg/login/additional_login_detector_test.go +++ b/pkg/login/additional_login_detector_test.go @@ -101,7 +101,7 @@ var _ = Describe("AdditionalLoginDetector", func() { // Create a temp dir and defer the cleanup of it dir, err := os.MkdirTemp("", "testBearerToken") Expect(err).NotTo(HaveOccurred()) - defer os.RemoveAll(dir) // clean up + defer func() { _ = os.RemoveAll(dir) }() // clean up // create the bearer token file in the tmp dir file := filepath.Join(dir, "bearerTokenfile") diff --git a/pkg/login/kubeConfig.go b/pkg/login/kubeConfig.go index bf58144e..d8ca91b3 100644 --- a/pkg/login/kubeConfig.go +++ b/pkg/login/kubeConfig.go @@ -66,7 +66,7 @@ func CreateClusterKubeConfig(clusterID string, kubeConfig api.Config) (string, e // Create cluster folder path := filepath.Join(basePath, clusterID) if _, err = os.Stat(path); errors.Is(err, os.ErrNotExist) { - err := os.MkdirAll(path, os.ModePerm) + err := os.MkdirAll(path, os.ModePerm) //nolint:gosec if err != nil { return "", err } @@ -74,12 +74,12 @@ func CreateClusterKubeConfig(clusterID string, kubeConfig api.Config) (string, e // Write kube config filename := filepath.Join(path, "config") - f, err := os.Create(filename) + f, err := os.Create(filename) //nolint:gosec if err != nil { return "", err } defer func() { - f.Close() + _ = f.Close() }() err = clientcmd.WriteToFile(kubeConfig, f.Name()) @@ -108,7 +108,7 @@ func RemoveClusterKubeConfig(clusterID string) error { _, err = os.Stat(path) if !errors.Is(err, os.ErrNotExist) { - os.RemoveAll(path) + _ = os.RemoveAll(path) } return nil } diff --git a/pkg/login/printClusterInfo_test.go b/pkg/login/printClusterInfo_test.go index ec63ef33..b4d45274 100644 --- a/pkg/login/printClusterInfo_test.go +++ b/pkg/login/printClusterInfo_test.go @@ -74,7 +74,7 @@ var _ = Describe("PrintClusterInfo", func() { Expect(err).To(BeNil()) // Capture the output - w.Close() + _ = w.Close() os.Stdout = oldStdout _, _ = buf.ReadFrom(r) @@ -97,7 +97,7 @@ var _ = Describe("PrintClusterInfo", func() { Expect(err).To(BeNil()) // Capture the output - w.Close() + _ = w.Close() os.Stdout = oldStdout _, _ = buf.ReadFrom(r) @@ -140,7 +140,7 @@ var _ = Describe("PrintClusterInfo", func() { Expect(err).To(BeNil()) // Capture the output - w.Close() + _ = w.Close() os.Stdout = oldStdout _, _ = buf.ReadFrom(r) @@ -182,7 +182,7 @@ var _ = Describe("PrintClusterInfo", func() { Expect(err).To(BeNil()) // Capture the output - w.Close() + _ = w.Close() os.Stdout = oldStdout _, _ = buf.ReadFrom(r) diff --git a/pkg/monitoring/monitoring.go b/pkg/monitoring/monitoring.go index 79b84acb..edd9d3de 100644 --- a/pkg/monitoring/monitoring.go +++ b/pkg/monitoring/monitoring.go @@ -154,7 +154,7 @@ func (c Client) RunMonitoring(monitoringType string) error { log.Fatalln(err) } - defer resp.Body.Close() + defer func() { _ = resp.Body.Close() }() if resp.StatusCode >= 400 { responseBody, _ := io.ReadAll(resp.Body) diff --git a/pkg/monitoring/monitoring_test.go b/pkg/monitoring/monitoring_test.go index ed243bb0..06f62da2 100644 --- a/pkg/monitoring/monitoring_test.go +++ b/pkg/monitoring/monitoring_test.go @@ -116,7 +116,7 @@ var _ = Describe("Backplane Monitoring Unit test", func() { err := utils.CreateTempKubeConfig(&testKubeCfg) Expect(err).To(BeNil()) - os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) + _ = os.Setenv(info.BackplaneURLEnvName, backplaneAPIUri) ocmEnv, _ = cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() }) diff --git a/pkg/ocm/ocm.go b/pkg/ocm/ocm.go index 9e8db0bd..b29998f6 100644 --- a/pkg/ocm/ocm.go +++ b/pkg/ocm/ocm.go @@ -67,7 +67,7 @@ func (o *DefaultOCMInterfaceImpl) createConnection() (*ocmsdk.Connection, error) if err != nil { return nil, err } - os.Setenv("OCM_URL", ocmURL) + _ = os.Setenv("OCM_URL", ocmURL) logger.Debugf("reset the OCM_URL to %s", ocmURL) } @@ -94,7 +94,7 @@ func (o *DefaultOCMInterfaceImpl) initiateCloseConnection(ctx context.Context, c defer o.ocmConnectionMutex.Unlock() if o.ocmConnection != nil && conn == o.ocmConnection { logger.Debugln(fmt.Sprintf("closing ocm connection after %v", o.OcmConnectionTimeout)) - o.ocmConnection.Close() + _ = o.ocmConnection.Close() o.ocmConnection = nil } // cancel the context to release resources diff --git a/pkg/ocm/ocm_test.go b/pkg/ocm/ocm_test.go index 96bef2a6..82a11787 100644 --- a/pkg/ocm/ocm_test.go +++ b/pkg/ocm/ocm_test.go @@ -89,7 +89,7 @@ var _ = Describe("OCM Wrapper Test", func() { // closed deliberately if conn != nil { - conn.Close() // if someone closes the connection by mistake + _ = conn.Close() // if someone closes the connection by mistake } // Routine for closing connection still runs and closes the connection diff --git a/pkg/utils/cluster_test.go b/pkg/utils/cluster_test.go index bd0ba266..ca71c048 100644 --- a/pkg/utils/cluster_test.go +++ b/pkg/utils/cluster_test.go @@ -213,7 +213,7 @@ func TestGetBackplaneClusterFromClusterKey(t *testing.T) { t.Run("it returns a cluster struct from a valid cluster key", func(_ *testing.T) { ocmEnv, _ := cmv1.NewEnvironment().BackplaneURL("https://dummy.api").Build() mockOcmInterface.EXPECT().GetOCMEnvironment().Return(ocmEnv, nil).AnyTimes() - os.Setenv(info.BackplaneURLEnvName, "https://backplane-url.cluster-key.redhat.com") + _ = os.Setenv(info.BackplaneURLEnvName, "https://backplane-url.cluster-key.redhat.com") mockOcmInterface.EXPECT().GetTargetCluster("cluster-key").Return("1234", "cluster-key", nil) cluster, err := utils.DefaultClusterUtils.GetBackplaneClusterFromClusterKey("cluster-key") diff --git a/pkg/utils/renderingutils.go b/pkg/utils/renderingutils.go index 8e108dad..c287b9f7 100644 --- a/pkg/utils/renderingutils.go +++ b/pkg/utils/renderingutils.go @@ -21,16 +21,16 @@ func RenderTabbedTable(headers []string, data [][]string) { writer := tabwriter.NewWriter(os.Stdout, 0, 0, columnPadding, ' ', tabwriter.TabIndent) // print the headers - fmt.Fprintf(writer, "%s", strings.Join(headers, "\t")) - fmt.Fprintln(writer) + _, _ = fmt.Fprintf(writer, "%s", strings.Join(headers, "\t")) + _, _ = fmt.Fprintln(writer) // print the rows for _, row := range data { - fmt.Fprintf(writer, "%s", strings.Join(truncateColumns(row, maxColumnWidth), "\t")) - fmt.Fprintln(writer) + _, _ = fmt.Fprintf(writer, "%s", strings.Join(truncateColumns(row, maxColumnWidth), "\t")) + _, _ = fmt.Fprintln(writer) } - writer.Flush() + _ = writer.Flush() } // calculateOptimalWidthsForColumns calculates optimal column width for table rendering. diff --git a/pkg/utils/util.go b/pkg/utils/util.go index a406565c..f22702e0 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -65,7 +65,7 @@ func GetFreePort() (int, error) { if err != nil { return 0, err } - defer l.Close() + defer func() { _ = l.Close() }() return l.Addr().(*net.TCPAddr).Port, nil } @@ -219,7 +219,7 @@ func CreateTempKubeConfig(kubeConfig *api.Config) error { } // set kube config env with temp kube config file - os.Setenv("KUBECONFIG", f.Name()) + _ = os.Setenv("KUBECONFIG", f.Name()) return nil } @@ -241,7 +241,7 @@ func ModifyTempKubeConfigFileName(fileName string) error { func RemoveTempKubeConfig() { path, found := os.LookupEnv("KUBECONFIG") if found { - os.Remove(path) + _ = os.Remove(path) } } @@ -299,7 +299,7 @@ func AskQuestionFromPrompt(question string) string { if CheckValidPrompt() { // Create a new scanner to read from stdin scanner := bufio.NewScanner(os.Stdin) - os.Stderr.WriteString(question) + _, _ = os.Stderr.WriteString(question) // Read the entire line (until the user presses Enter) if scanner.Scan() { return scanner.Text()