From 38cf7b014137637c065513b2077eca0c8ef43541 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Thu, 7 Oct 2021 12:37:42 +0800 Subject: [PATCH] refactor: move from io/ioutil to io and os package (#1843) The io/ioutil package has been deprecated as of Go 1.16, see https://golang.org/doc/go1.16#ioutil. This commit replaces the existing io/ioutil functions with their new definitions in io and os packages. Signed-off-by: Eng Zer Jun --- cmd/server_test.go | 5 ++- e2e/e2e.go | 3 +- .../events/azuredevops_request_validator.go | 4 +-- .../controllers/events/events_controller.go | 6 ++-- .../events/events_controller_e2e_test.go | 17 +++++----- .../events/events_controller_test.go | 21 ++++++------ .../events/github_request_validator.go | 4 +-- .../events/gitlab_request_parser_validator.go | 4 +-- server/controllers/status_controller_test.go | 8 ++--- server/core/db/boltdb_test.go | 3 +- server/core/runtime/apply_step_runner.go | 5 ++- server/core/runtime/apply_step_runner_test.go | 13 ++++--- server/core/runtime/init_step_runner_test.go | 8 ++--- server/core/runtime/plan_step_runner.go | 3 +- server/core/runtime/plan_step_runner_test.go | 5 ++- .../runtime/plan_type_step_runner_delegate.go | 4 +-- .../plan_type_step_runner_delegate_test.go | 10 +++--- server/core/runtime/show_step_runner.go | 3 +- server/core/runtime/show_step_runner_test.go | 8 ++--- server/core/terraform/terraform_client.go | 5 ++- .../terraform_client_internal_test.go | 9 +++-- .../core/terraform/terraform_client_test.go | 13 ++++--- server/events/comment_parser.go | 10 +++--- server/events/event_parser_test.go | 34 +++++++++---------- server/events/git_cred_writer.go | 13 ++++--- server/events/git_cred_writer_test.go | 22 ++++++------ server/events/pending_plan_finder.go | 3 +- .../project_command_builder_internal_test.go | 14 ++++---- server/events/project_command_builder_test.go | 10 +++--- server/events/project_finder_test.go | 7 ++-- server/events/vcs/azuredevops_client_test.go | 13 +++---- server/events/vcs/bitbucketcloud/client.go | 5 ++- .../events/vcs/bitbucketcloud/client_test.go | 4 +-- server/events/vcs/bitbucketserver/client.go | 5 ++- .../events/vcs/bitbucketserver/client_test.go | 9 ++--- server/events/vcs/github_client_test.go | 21 ++++++------ server/events/vcs/gitlab_client_test.go | 4 +-- server/events/yaml/parser_validator.go | 5 ++- server/events/yaml/parser_validator_test.go | 15 ++++---- server/events/yaml/valid/global_cfg_test.go | 6 ++-- server/recovery/recovery.go | 4 +-- server/server.go | 3 +- server/server_test.go | 9 ++--- testdrive/testdrive.go | 7 ++-- testdrive/utils.go | 3 +- testing/http.go | 4 +-- testing/temp_files.go | 5 ++- 47 files changed, 189 insertions(+), 207 deletions(-) diff --git a/cmd/server_test.go b/cmd/server_test.go index 388c79541..95d82aa31 100644 --- a/cmd/server_test.go +++ b/cmd/server_test.go @@ -15,7 +15,6 @@ package cmd import ( "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -837,12 +836,12 @@ func setupWithDefaults(flags map[string]interface{}, t *testing.T) *cobra.Comman } func tempFile(t *testing.T, contents string) string { - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") Ok(t, err) newName := f.Name() + ".yaml" err = os.Rename(f.Name(), newName) Ok(t, err) - ioutil.WriteFile(newName, []byte(contents), 0600) // nolint: errcheck + os.WriteFile(newName, []byte(contents), 0600) // nolint: errcheck return newName } diff --git a/e2e/e2e.go b/e2e/e2e.go index ee44a2a73..5addf721e 100644 --- a/e2e/e2e.go +++ b/e2e/e2e.go @@ -15,7 +15,6 @@ package main import ( "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -78,7 +77,7 @@ func (t *E2ETester) Start() (*E2EResult, error) { randomData := []byte(testFileData) filePath := fmt.Sprintf("%s/%s/%s", cloneDir, t.projectType.Name, testFileName) log.Printf("creating file to commit %q", filePath) - err := ioutil.WriteFile(filePath, randomData, 0644) + err := os.WriteFile(filePath, randomData, 0644) if err != nil { return e2eResult, fmt.Errorf("couldn't write file %s: %v", filePath, err) } diff --git a/server/controllers/events/azuredevops_request_validator.go b/server/controllers/events/azuredevops_request_validator.go index 0b6e77e4f..e0786d8eb 100644 --- a/server/controllers/events/azuredevops_request_validator.go +++ b/server/controllers/events/azuredevops_request_validator.go @@ -2,7 +2,7 @@ package events import ( "fmt" - "io/ioutil" + "io" "net/http" "github.com/mcdafydd/go-azuredevops/azuredevops" @@ -47,7 +47,7 @@ func (d *DefaultAzureDevopsRequestValidator) validateWithBasicAuth(r *http.Reque func (d *DefaultAzureDevopsRequestValidator) validateWithoutBasicAuth(r *http.Request) ([]byte, error) { ct := r.Header.Get("Content-Type") if ct == "application/json" || ct == "application/json; charset=utf-8" { - payload, err := ioutil.ReadAll(r.Body) + payload, err := io.ReadAll(r.Body) if err != nil { return nil, fmt.Errorf("could not read body: %s", err) } diff --git a/server/controllers/events/events_controller.go b/server/controllers/events/events_controller.go index 7164d10da..c94f2d648 100644 --- a/server/controllers/events/events_controller.go +++ b/server/controllers/events/events_controller.go @@ -15,7 +15,7 @@ package events import ( "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -163,7 +163,7 @@ func (e *VCSEventsController) handleBitbucketCloudPost(w http.ResponseWriter, r eventType := r.Header.Get(bitbucketEventTypeHeader) reqID := r.Header.Get(bitbucketCloudRequestIDHeader) defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { e.respond(w, logging.Error, http.StatusBadRequest, "Unable to read body: %s %s=%s", err, bitbucketCloudRequestIDHeader, reqID) return @@ -187,7 +187,7 @@ func (e *VCSEventsController) handleBitbucketServerPost(w http.ResponseWriter, r reqID := r.Header.Get(bitbucketServerRequestIDHeader) sig := r.Header.Get(bitbucketServerSignatureHeader) defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { e.respond(w, logging.Error, http.StatusBadRequest, "Unable to read body: %s %s=%s", err, bitbucketServerRequestIDHeader, reqID) return diff --git a/server/controllers/events/events_controller_e2e_test.go b/server/controllers/events/events_controller_e2e_test.go index 06db9b504..6db49d49a 100644 --- a/server/controllers/events/events_controller_e2e_test.go +++ b/server/controllers/events/events_controller_e2e_test.go @@ -3,7 +3,6 @@ package events_test import ( "bytes" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -527,7 +526,7 @@ func TestSimlpleWorkflow_terraformLockFile(t *testing.T) { oldLockFilePath, err := filepath.Abs(filepath.Join("testfixtures", "null_provider_lockfile_old_version")) Ok(t, err) - oldLockFileContent, err := ioutil.ReadFile(oldLockFilePath) + oldLockFileContent, err := os.ReadFile(oldLockFilePath) Ok(t, err) if c.LockFileTracked { @@ -549,7 +548,7 @@ func TestSimlpleWorkflow_terraformLockFile(t *testing.T) { ResponseContains(t, w, 200, "Processing...") // check lock file content - actualLockFileContent, err := ioutil.ReadFile(fmt.Sprintf("%s/repos/runatlantis/atlantis-tests/2/default/.terraform.lock.hcl", atlantisWorkspace.DataDir)) + actualLockFileContent, err := os.ReadFile(fmt.Sprintf("%s/repos/runatlantis/atlantis-tests/2/default/.terraform.lock.hcl", atlantisWorkspace.DataDir)) Ok(t, err) if c.LockFileTracked { if string(oldLockFileContent) != string(actualLockFileContent) { @@ -578,7 +577,7 @@ func TestSimlpleWorkflow_terraformLockFile(t *testing.T) { } // check lock file content - actualLockFileContent, err = ioutil.ReadFile(fmt.Sprintf("%s/repos/runatlantis/atlantis-tests/2/default/.terraform.lock.hcl", atlantisWorkspace.DataDir)) + actualLockFileContent, err = os.ReadFile(fmt.Sprintf("%s/repos/runatlantis/atlantis-tests/2/default/.terraform.lock.hcl", atlantisWorkspace.DataDir)) Ok(t, err) if c.LockFileTracked { if string(oldLockFileContent) != string(actualLockFileContent) { @@ -1086,7 +1085,7 @@ func (w *mockWebhookSender) Send(log logging.SimpleLogging, result webhooks.Appl } func GitHubCommentEvent(t *testing.T, comment string) *http.Request { - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent.json")) Ok(t, err) requestJSON = []byte(strings.Replace(string(requestJSON), "###comment body###", comment, 1)) req, err := http.NewRequest("POST", "/events", bytes.NewBuffer(requestJSON)) @@ -1097,7 +1096,7 @@ func GitHubCommentEvent(t *testing.T, comment string) *http.Request { } func GitHubPullRequestOpenedEvent(t *testing.T, headSHA string) *http.Request { - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "githubPullRequestOpenedEvent.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "githubPullRequestOpenedEvent.json")) Ok(t, err) // Replace sha with expected sha. requestJSONStr := strings.Replace(string(requestJSON), "c31fd9ea6f557ad2ea659944c3844a059b83bc5d", headSHA, -1) @@ -1109,7 +1108,7 @@ func GitHubPullRequestOpenedEvent(t *testing.T, headSHA string) *http.Request { } func GitHubPullRequestClosedEvent(t *testing.T) *http.Request { - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "githubPullRequestClosedEvent.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "githubPullRequestClosedEvent.json")) Ok(t, err) req, err := http.NewRequest("POST", "/events", bytes.NewBuffer(requestJSON)) Ok(t, err) @@ -1219,7 +1218,7 @@ func assertCommentEquals(t *testing.T, expReplies []string, act string, repoDir } for _, expFile := range expReplies { - exp, err := ioutil.ReadFile(filepath.Join(absRepoPath(t, repoDir), expFile)) + exp, err := os.ReadFile(filepath.Join(absRepoPath(t, repoDir), expFile)) Ok(t, err) expStr := string(exp) // My editor adds a newline to all the files, so if the actual comment @@ -1237,7 +1236,7 @@ func assertCommentEquals(t *testing.T, expReplies []string, act string, repoDir t.FailNow() } else { actFile := filepath.Join(absRepoPath(t, repoDir), expFile+".act") - err := ioutil.WriteFile(actFile, []byte(act), 0600) + err := os.WriteFile(actFile, []byte(act), 0600) Ok(t, err) cwd, err := os.Getwd() Ok(t, err) diff --git a/server/controllers/events/events_controller_test.go b/server/controllers/events/events_controller_test.go index 2ff5b1e4a..dff2ffbb8 100644 --- a/server/controllers/events/events_controller_test.go +++ b/server/controllers/events/events_controller_test.go @@ -17,9 +17,10 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "path/filepath" "reflect" "strings" @@ -201,7 +202,7 @@ func TestPost_GitlabCommentNotAllowlisted(t *testing.T) { RepoAllowlistChecker: &events.RepoAllowlistChecker{}, VCSClient: vcsClient, } - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "gitlabMergeCommentEvent_notAllowlisted.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "gitlabMergeCommentEvent_notAllowlisted.json")) Ok(t, err) req, _ := http.NewRequest("GET", "", bytes.NewBuffer(requestJSON)) req.Header.Set(gitlabHeader, "Note Hook") @@ -209,7 +210,7 @@ func TestPost_GitlabCommentNotAllowlisted(t *testing.T) { e.Post(w, req) Equals(t, http.StatusForbidden, w.Result().StatusCode) - body, _ := ioutil.ReadAll(w.Result().Body) + body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) expRepo, _ := models.NewRepo(models.Gitlab, "gitlabhq/gitlab-test", "https://example.com/gitlabhq/gitlab-test.git", "", "") @@ -230,7 +231,7 @@ func TestPost_GitlabCommentNotAllowlistedWithSilenceErrors(t *testing.T) { VCSClient: vcsClient, SilenceAllowlistErrors: true, } - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "gitlabMergeCommentEvent_notAllowlisted.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "gitlabMergeCommentEvent_notAllowlisted.json")) Ok(t, err) req, _ := http.NewRequest("GET", "", bytes.NewBuffer(requestJSON)) req.Header.Set(gitlabHeader, "Note Hook") @@ -238,7 +239,7 @@ func TestPost_GitlabCommentNotAllowlistedWithSilenceErrors(t *testing.T) { e.Post(w, req) Equals(t, http.StatusForbidden, w.Result().StatusCode) - body, _ := ioutil.ReadAll(w.Result().Body) + body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) vcsClient.VerifyWasCalled(Never()).CreateComment(matchers.AnyModelsRepo(), AnyInt(), AnyString(), AnyString()) @@ -258,7 +259,7 @@ func TestPost_GithubCommentNotAllowlisted(t *testing.T) { RepoAllowlistChecker: &events.RepoAllowlistChecker{}, VCSClient: vcsClient, } - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent_notAllowlisted.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent_notAllowlisted.json")) Ok(t, err) req, _ := http.NewRequest("GET", "", bytes.NewBuffer(requestJSON)) req.Header.Set("Content-Type", "application/json") @@ -267,7 +268,7 @@ func TestPost_GithubCommentNotAllowlisted(t *testing.T) { e.Post(w, req) Equals(t, http.StatusForbidden, w.Result().StatusCode) - body, _ := ioutil.ReadAll(w.Result().Body) + body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) expRepo, _ := models.NewRepo(models.Github, "baxterthehacker/public-repo", "https://github.com/baxterthehacker/public-repo.git", "", "") @@ -288,7 +289,7 @@ func TestPost_GithubCommentNotAllowlistedWithSilenceErrors(t *testing.T) { VCSClient: vcsClient, SilenceAllowlistErrors: true, } - requestJSON, err := ioutil.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent_notAllowlisted.json")) + requestJSON, err := os.ReadFile(filepath.Join("testfixtures", "githubIssueCommentEvent_notAllowlisted.json")) Ok(t, err) req, _ := http.NewRequest("GET", "", bytes.NewBuffer(requestJSON)) req.Header.Set("Content-Type", "application/json") @@ -297,7 +298,7 @@ func TestPost_GithubCommentNotAllowlistedWithSilenceErrors(t *testing.T) { e.Post(w, req) Equals(t, http.StatusForbidden, w.Result().StatusCode) - body, _ := ioutil.ReadAll(w.Result().Body) + body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) vcsClient.VerifyWasCalled(Never()).CreateComment(matchers.AnyModelsRepo(), AnyInt(), AnyString(), AnyString()) @@ -645,7 +646,7 @@ func TestPost_BBServerPullClosed(t *testing.T) { } // Build HTTP request. - requestBytes, err := ioutil.ReadFile(filepath.Join("testfixtures", "bb-server-pull-deleted-event.json")) + requestBytes, err := os.ReadFile(filepath.Join("testfixtures", "bb-server-pull-deleted-event.json")) // Replace the eventKey field with our event type. requestJSON := strings.Replace(string(requestBytes), `"eventKey":"pr:deleted",`, fmt.Sprintf(`"eventKey":"%s",`, c.header), -1) Ok(t, err) diff --git a/server/controllers/events/github_request_validator.go b/server/controllers/events/github_request_validator.go index 0d5845c1e..9a7ffc19b 100644 --- a/server/controllers/events/github_request_validator.go +++ b/server/controllers/events/github_request_validator.go @@ -16,7 +16,7 @@ package events import ( "errors" "fmt" - "io/ioutil" + "io" "net/http" "github.com/google/go-github/v31/github" @@ -60,7 +60,7 @@ func (d *DefaultGithubRequestValidator) validateAgainstSecret(r *http.Request, s func (d *DefaultGithubRequestValidator) validateWithoutSecret(r *http.Request) ([]byte, error) { switch ct := r.Header.Get("Content-Type"); ct { case "application/json": - payload, err := ioutil.ReadAll(r.Body) + payload, err := io.ReadAll(r.Body) if err != nil { return nil, fmt.Errorf("could not read body: %s", err) } diff --git a/server/controllers/events/gitlab_request_parser_validator.go b/server/controllers/events/gitlab_request_parser_validator.go index f1bffcceb..9755bd5d9 100644 --- a/server/controllers/events/gitlab_request_parser_validator.go +++ b/server/controllers/events/gitlab_request_parser_validator.go @@ -16,7 +16,7 @@ package events import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" gitlab "github.com/xanzy/go-gitlab" @@ -68,7 +68,7 @@ func (d *DefaultGitlabRequestParserValidator) ParseAndValidate(r *http.Request, // Parse request into a gitlab object based on the object type specified // in the gitlabHeader. - bytes, err := ioutil.ReadAll(r.Body) + bytes, err := io.ReadAll(r.Body) if err != nil { return nil, err } diff --git a/server/controllers/status_controller_test.go b/server/controllers/status_controller_test.go index e809099e1..bc5161155 100644 --- a/server/controllers/status_controller_test.go +++ b/server/controllers/status_controller_test.go @@ -3,7 +3,7 @@ package controllers_test import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -26,7 +26,7 @@ func TestStatusController_Startup(t *testing.T) { d.Get(w, r) var result controllers.StatusResponse - body, err := ioutil.ReadAll(w.Result().Body) + body, err := io.ReadAll(w.Result().Body) Ok(t, err) Equals(t, 200, w.Result().StatusCode) err = json.Unmarshal(body, &result) @@ -49,7 +49,7 @@ func TestStatusController_InProgress(t *testing.T) { d.Get(w, r) var result controllers.StatusResponse - body, err := ioutil.ReadAll(w.Result().Body) + body, err := io.ReadAll(w.Result().Body) Ok(t, err) Equals(t, 200, w.Result().StatusCode) err = json.Unmarshal(body, &result) @@ -72,7 +72,7 @@ func TestStatusController_Shutdown(t *testing.T) { d.Get(w, r) var result controllers.StatusResponse - body, err := ioutil.ReadAll(w.Result().Body) + body, err := io.ReadAll(w.Result().Body) Ok(t, err) Equals(t, 200, w.Result().StatusCode) err = json.Unmarshal(body, &result) diff --git a/server/core/db/boltdb_test.go b/server/core/db/boltdb_test.go index ca41c6c00..24b0342f7 100644 --- a/server/core/db/boltdb_test.go +++ b/server/core/db/boltdb_test.go @@ -14,7 +14,6 @@ package db_test import ( - "io/ioutil" "os" "testing" "time" @@ -769,7 +768,7 @@ func TestPullStatus_UpdateMerge(t *testing.T) { // newTestDB returns a TestDB using a temporary path. func newTestDB() (*bolt.DB, *db.BoltDB) { // Retrieve a temporary path. - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") if err != nil { panic(errors.Wrap(err, "failed to create temp file")) } diff --git a/server/core/runtime/apply_step_runner.go b/server/core/runtime/apply_step_runner.go index 3ce0d79ca..d4bcd90c6 100644 --- a/server/core/runtime/apply_step_runner.go +++ b/server/core/runtime/apply_step_runner.go @@ -2,7 +2,6 @@ package runtime import ( "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -27,7 +26,7 @@ func (a *ApplyStepRunner) Run(ctx models.ProjectCommandContext, extraArgs []stri } planPath := filepath.Join(path, GetPlanFilename(ctx.Workspace, ctx.ProjectName)) - contents, err := ioutil.ReadFile(planPath) + contents, err := os.ReadFile(planPath) if os.IsNotExist(err) { return "", fmt.Errorf("no plan found at path %q and workspace %q–did you run plan?", ctx.RepoRelDir, ctx.Workspace) } @@ -118,7 +117,7 @@ func (a *ApplyStepRunner) runRemoteApply( // The planfile contents are needed to ensure that the plan didn't change // between plan and apply phases. - planfileBytes, err := ioutil.ReadFile(absPlanPath) + planfileBytes, err := os.ReadFile(absPlanPath) if err != nil { return "", errors.Wrap(err, "reading planfile") } diff --git a/server/core/runtime/apply_step_runner_test.go b/server/core/runtime/apply_step_runner_test.go index 2130f4a81..7010f79d6 100644 --- a/server/core/runtime/apply_step_runner_test.go +++ b/server/core/runtime/apply_step_runner_test.go @@ -3,7 +3,6 @@ package runtime_test import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -52,7 +51,7 @@ func TestRun_Success(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, nil, 0600) + err := os.WriteFile(planPath, nil, 0600) Ok(t, err) RegisterMockTestingT(t) @@ -82,7 +81,7 @@ func TestRun_AppliesCorrectProjectPlan(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "projectname-default.tfplan") - err := ioutil.WriteFile(planPath, nil, 0600) + err := os.WriteFile(planPath, nil, 0600) Ok(t, err) RegisterMockTestingT(t) @@ -112,7 +111,7 @@ func TestRun_UsesConfiguredTFVersion(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, nil, 0600) + err := os.WriteFile(planPath, nil, 0600) Ok(t, err) RegisterMockTestingT(t) @@ -197,7 +196,7 @@ func TestRun_UsingTarget(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, nil, 0600) + err := os.WriteFile(planPath, nil, 0600) Ok(t, err) terraform := mocks.NewMockClient() step := runtime.ApplyStepRunner{ @@ -236,7 +235,7 @@ Terraform will perform the following actions: Plan: 0 to add, 0 to change, 1 to destroy.` - err := ioutil.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) + err := os.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) Ok(t, err) RegisterMockTestingT(t) @@ -294,7 +293,7 @@ Terraform will perform the following actions: Plan: 0 to add, 0 to change, 1 to destroy.` - err := ioutil.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) + err := os.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) Ok(t, err) RegisterMockTestingT(t) diff --git a/server/core/runtime/init_step_runner_test.go b/server/core/runtime/init_step_runner_test.go index 496f13f7a..9c839e0e4 100644 --- a/server/core/runtime/init_step_runner_test.go +++ b/server/core/runtime/init_step_runner_test.go @@ -1,7 +1,7 @@ package runtime_test import ( - "io/ioutil" + "os" "os/exec" "path/filepath" "strings" @@ -106,7 +106,7 @@ func TestRun_InitOmitsUpgradeFlagIfLockFileTracked(t *testing.T) { defer cleanup() lockFilePath := filepath.Join(repoDir, ".terraform.lock.hcl") - err := ioutil.WriteFile(lockFilePath, nil, 0600) + err := os.WriteFile(lockFilePath, nil, 0600) Ok(t, err) // commit lock file runCmd(t, repoDir, "git", "add", ".terraform.lock.hcl") @@ -172,7 +172,7 @@ func TestRun_InitKeepUpgradeFlagIfLockFilePresentAndTFLessThanPoint14(t *testing tmpDir, cleanup := TempDir(t) defer cleanup() lockFilePath := filepath.Join(tmpDir, ".terraform.lock.hcl") - err := ioutil.WriteFile(lockFilePath, nil, 0600) + err := os.WriteFile(lockFilePath, nil, 0600) Ok(t, err) RegisterMockTestingT(t) @@ -274,7 +274,7 @@ func TestRun_InitDeletesLockFileIfPresentAndNotTracked(t *testing.T) { defer cleanup() lockFilePath := filepath.Join(repoDir, ".terraform.lock.hcl") - err := ioutil.WriteFile(lockFilePath, nil, 0600) + err := os.WriteFile(lockFilePath, nil, 0600) Ok(t, err) RegisterMockTestingT(t) diff --git a/server/core/runtime/plan_step_runner.go b/server/core/runtime/plan_step_runner.go index ea21139e1..8ac365003 100644 --- a/server/core/runtime/plan_step_runner.go +++ b/server/core/runtime/plan_step_runner.go @@ -2,7 +2,6 @@ package runtime import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -92,7 +91,7 @@ func (p *PlanStepRunner) remotePlan(ctx models.ProjectCommandContext, extraArgs // We also prepend our own remote ops header to the file so during apply we // know this is a remote apply. - err = ioutil.WriteFile(planFile, []byte(remoteOpsHeader+planOutput), 0600) + err = os.WriteFile(planFile, []byte(remoteOpsHeader+planOutput), 0600) if err != nil { return output, errors.Wrap(err, "unable to create planfile for remote ops") } diff --git a/server/core/runtime/plan_step_runner_test.go b/server/core/runtime/plan_step_runner_test.go index d16d531a3..f4a19fbb4 100644 --- a/server/core/runtime/plan_step_runner_test.go +++ b/server/core/runtime/plan_step_runner_test.go @@ -2,7 +2,6 @@ package runtime_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -386,7 +385,7 @@ func TestRun_AddsEnvVarFile(t *testing.T) { err := os.MkdirAll(filepath.Join(tmpDir, "env"), 0700) Ok(t, err) envVarsFile := filepath.Join(tmpDir, "env/workspace.tfvars") - err = ioutil.WriteFile(envVarsFile, nil, 0600) + err = os.WriteFile(envVarsFile, nil, 0600) Ok(t, err) // Using version >= 0.10 here so we don't expect any env commands. @@ -795,7 +794,7 @@ Plan: 0 to add, 0 to change, 1 to destroy.`, output) Equals(t, expRemotePlanArgs, asyncTf.CalledArgs) // Verify that the fake plan file we write has the correct contents. - bytes, err := ioutil.ReadFile(filepath.Join(absProjectPath, "default.tfplan")) + bytes, err := os.ReadFile(filepath.Join(absProjectPath, "default.tfplan")) Ok(t, err) Equals(t, `Atlantis: this plan was created by remote ops diff --git a/server/core/runtime/plan_type_step_runner_delegate.go b/server/core/runtime/plan_type_step_runner_delegate.go index a372cd2e0..d2cef7a2d 100644 --- a/server/core/runtime/plan_type_step_runner_delegate.go +++ b/server/core/runtime/plan_type_step_runner_delegate.go @@ -1,7 +1,7 @@ package runtime import ( - "io/ioutil" + "os" "path/filepath" "github.com/pkg/errors" @@ -40,7 +40,7 @@ type PlanTypeStepRunnerDelegate struct { } func (p *PlanTypeStepRunnerDelegate) isRemotePlan(planFile string) (bool, error) { - data, err := ioutil.ReadFile(planFile) + data, err := os.ReadFile(planFile) if err != nil { return false, errors.Wrapf(err, "unable to read %s", planFile) diff --git a/server/core/runtime/plan_type_step_runner_delegate_test.go b/server/core/runtime/plan_type_step_runner_delegate_test.go index 060e163a6..189f171de 100644 --- a/server/core/runtime/plan_type_step_runner_delegate_test.go +++ b/server/core/runtime/plan_type_step_runner_delegate_test.go @@ -2,7 +2,7 @@ package runtime import ( "errors" - "io/ioutil" + "os" "path/filepath" "testing" @@ -44,7 +44,7 @@ func TestRunDelegate(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) + err := os.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) Ok(t, err) ctx := models.ProjectCommandContext{ @@ -73,7 +73,7 @@ func TestRunDelegate(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) + err := os.WriteFile(planPath, []byte("Atlantis: this plan was created by remote ops\n"+planFileContents), 0600) Ok(t, err) ctx := models.ProjectCommandContext{ @@ -102,7 +102,7 @@ func TestRunDelegate(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, []byte(planFileContents), 0600) + err := os.WriteFile(planPath, []byte(planFileContents), 0600) Ok(t, err) ctx := models.ProjectCommandContext{ @@ -131,7 +131,7 @@ func TestRunDelegate(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() planPath := filepath.Join(tmpDir, "workspace.tfplan") - err := ioutil.WriteFile(planPath, []byte(planFileContents), 0600) + err := os.WriteFile(planPath, []byte(planFileContents), 0600) Ok(t, err) ctx := models.ProjectCommandContext{ diff --git a/server/core/runtime/show_step_runner.go b/server/core/runtime/show_step_runner.go index 7464636ec..a8f0e398e 100644 --- a/server/core/runtime/show_step_runner.go +++ b/server/core/runtime/show_step_runner.go @@ -1,7 +1,6 @@ package runtime import ( - "io/ioutil" "os" "path/filepath" @@ -52,7 +51,7 @@ func (p *ShowStepRunner) Run(ctx models.ProjectCommandContext, extraArgs []strin return "", errors.Wrap(err, "running terraform show") } - if err := ioutil.WriteFile(showResultFile, []byte(output), os.ModePerm); err != nil { + if err := os.WriteFile(showResultFile, []byte(output), os.ModePerm); err != nil { return "", errors.Wrap(err, "writing terraform show result") } diff --git a/server/core/runtime/show_step_runner_test.go b/server/core/runtime/show_step_runner_test.go index a01d8fb50..264d768cc 100644 --- a/server/core/runtime/show_step_runner_test.go +++ b/server/core/runtime/show_step_runner_test.go @@ -2,7 +2,7 @@ package runtime import ( "errors" - "io/ioutil" + "os" "path/filepath" "testing" @@ -16,7 +16,7 @@ import ( func TestShowStepRunnner(t *testing.T) { logger := logging.NewNoopLogger(t) - path, _ := ioutil.TempDir("", "") + path, _ := os.MkdirTemp("", "") resultPath := filepath.Join(path, "test-default.json") envs := map[string]string{"key": "val"} tfVersion, _ := version.NewVersion("0.12") @@ -45,7 +45,7 @@ func TestShowStepRunnner(t *testing.T) { Ok(t, err) - actual, _ := ioutil.ReadFile(resultPath) + actual, _ := os.ReadFile(resultPath) actualStr := string(actual) Assert(t, actualStr == "success", "got expected result") @@ -72,7 +72,7 @@ func TestShowStepRunnner(t *testing.T) { Ok(t, err) - actual, _ := ioutil.ReadFile(resultPath) + actual, _ := os.ReadFile(resultPath) actualStr := string(actual) Assert(t, actualStr == "success", "got expected result") diff --git a/server/core/terraform/terraform_client.go b/server/core/terraform/terraform_client.go index 971eeb3c4..39defed68 100644 --- a/server/core/terraform/terraform_client.go +++ b/server/core/terraform/terraform_client.go @@ -18,7 +18,6 @@ import ( "bufio" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -491,7 +490,7 @@ func generateRCFile(tfeToken string, tfeHostname string, home string) error { // what we would have written to it, then we error out because we don't // want to overwrite anything. if _, err := os.Stat(rcFile); err == nil { - currContents, err := ioutil.ReadFile(rcFile) // nolint: gosec + currContents, err := os.ReadFile(rcFile) // nolint: gosec if err != nil { return errors.Wrapf(err, "trying to read %s to ensure we're not overwriting it", rcFile) } @@ -503,7 +502,7 @@ func generateRCFile(tfeToken string, tfeHostname string, home string) error { return nil } - if err := ioutil.WriteFile(rcFile, []byte(config), 0600); err != nil { + if err := os.WriteFile(rcFile, []byte(config), 0600); err != nil { return errors.Wrapf(err, "writing generated %s file with TFE token to %s", rcFilename, rcFile) } return nil diff --git a/server/core/terraform/terraform_client_internal_test.go b/server/core/terraform/terraform_client_internal_test.go index 8a447fb82..036f08766 100644 --- a/server/core/terraform/terraform_client_internal_test.go +++ b/server/core/terraform/terraform_client_internal_test.go @@ -2,7 +2,6 @@ package terraform import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -24,7 +23,7 @@ func TestGenerateRCFile_WritesFile(t *testing.T) { expContents := `credentials "hostname" { token = "token" }` - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".terraformrc")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".terraformrc")) Ok(t, err) Equals(t, expContents, string(actContents)) } @@ -36,7 +35,7 @@ func TestGenerateRCFile_WillNotOverwrite(t *testing.T) { defer cleanup() rcFile := filepath.Join(tmp, ".terraformrc") - err := ioutil.WriteFile(rcFile, []byte("contents"), 0600) + err := os.WriteFile(rcFile, []byte("contents"), 0600) Ok(t, err) actErr := generateRCFile("token", "hostname", tmp) @@ -54,7 +53,7 @@ func TestGenerateRCFile_NoErrIfContentsSame(t *testing.T) { contents := `credentials "app.terraform.io" { token = "token" }` - err := ioutil.WriteFile(rcFile, []byte(contents), 0600) + err := os.WriteFile(rcFile, []byte(contents), 0600) Ok(t, err) err = generateRCFile("token", "app.terraform.io", tmp) @@ -68,7 +67,7 @@ func TestGenerateRCFile_ErrIfCannotRead(t *testing.T) { defer cleanup() rcFile := filepath.Join(tmp, ".terraformrc") - err := ioutil.WriteFile(rcFile, []byte("can't see me!"), 0000) + err := os.WriteFile(rcFile, []byte("can't see me!"), 0000) Ok(t, err) expErr := fmt.Sprintf("trying to read %s to ensure we're not overwriting it: open %s: permission denied", rcFile, rcFile) diff --git a/server/core/terraform/terraform_client_test.go b/server/core/terraform/terraform_client_test.go index 5ccb2e573..dc8203806 100644 --- a/server/core/terraform/terraform_client_test.go +++ b/server/core/terraform/terraform_client_test.go @@ -15,7 +15,6 @@ package terraform_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -66,7 +65,7 @@ is 0.11.13. You can update by downloading from www.terraform.io/downloads.html // We're testing this by adding our own "fake" terraform binary to path that // outputs what would normally come from terraform version. - err := ioutil.WriteFile(filepath.Join(tmp, "terraform"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 + err := os.WriteFile(filepath.Join(tmp, "terraform"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 Ok(t, err) defer tempSetEnv(t, "PATH", fmt.Sprintf("%s:%s", tmp, os.Getenv("PATH")))() @@ -95,7 +94,7 @@ is 0.11.13. You can update by downloading from www.terraform.io/downloads.html // We're testing this by adding our own "fake" terraform binary to path that // outputs what would normally come from terraform version. - err := ioutil.WriteFile(filepath.Join(tmp, "terraform"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 + err := os.WriteFile(filepath.Join(tmp, "terraform"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 Ok(t, err) defer tempSetEnv(t, "PATH", fmt.Sprintf("%s:%s", tmp, os.Getenv("PATH")))() @@ -134,7 +133,7 @@ func TestNewClient_DefaultTFFlagInPath(t *testing.T) { // We're testing this by adding our own "fake" terraform binary to path that // outputs what would normally come from terraform version. - err := ioutil.WriteFile(filepath.Join(tmp, "terraform0.11.10"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 + err := os.WriteFile(filepath.Join(tmp, "terraform0.11.10"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 Ok(t, err) defer tempSetEnv(t, "PATH", fmt.Sprintf("%s:%s", tmp, os.Getenv("PATH")))() @@ -158,7 +157,7 @@ func TestNewClient_DefaultTFFlagInBinDir(t *testing.T) { defer cleanup() // Add our fake binary to {datadir}/bin/terraform{version}. - err := ioutil.WriteFile(filepath.Join(binDir, "terraform0.11.10"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 + err := os.WriteFile(filepath.Join(binDir, "terraform0.11.10"), []byte(fmt.Sprintf("#!/bin/sh\necho '%s'", fakeBinOut)), 0700) // #nosec G306 Ok(t, err) defer tempSetEnv(t, "PATH", fmt.Sprintf("%s:%s", tmp, os.Getenv("PATH")))() @@ -186,7 +185,7 @@ func TestNewClient_DefaultTFFlagDownload(t *testing.T) { mockDownloader := mocks.NewMockDownloader() When(mockDownloader.GetFile(AnyString(), AnyString())).Then(func(params []pegomock.Param) pegomock.ReturnValues { - err := ioutil.WriteFile(params[0].(string), []byte("#!/bin/sh\necho '\nTerraform v0.11.10\n'"), 0700) // #nosec G306 + err := os.WriteFile(params[0].(string), []byte("#!/bin/sh\necho '\nTerraform v0.11.10\n'"), 0700) // #nosec G306 return []pegomock.ReturnValue{err} }) c, err := terraform.NewClient(logger, binDir, cacheDir, "", "", "0.11.10", cmd.DefaultTFVersionFlag, "https://my-mirror.releases.mycompany.com", mockDownloader, true) @@ -234,7 +233,7 @@ func TestRunCommandWithVersion_DLsTF(t *testing.T) { runtime.GOARCH, baseURL) When(mockDownloader.GetFile(filepath.Join(tmp, "bin", "terraform99.99.99"), expURL)).Then(func(params []pegomock.Param) pegomock.ReturnValues { - err := ioutil.WriteFile(params[0].(string), []byte("#!/bin/sh\necho '\nTerraform v99.99.99\n'"), 0700) // #nosec G306 + err := os.WriteFile(params[0].(string), []byte("#!/bin/sh\necho '\nTerraform v99.99.99\n'"), 0700) // #nosec G306 return []pegomock.ReturnValue{err} }) diff --git a/server/events/comment_parser.go b/server/events/comment_parser.go index 395516895..515737568 100644 --- a/server/events/comment_parser.go +++ b/server/events/comment_parser.go @@ -16,7 +16,7 @@ package events import ( "bytes" "fmt" - "io/ioutil" + "io" "net/url" "path/filepath" "regexp" @@ -183,7 +183,7 @@ func (e *CommentParser) Parse(comment string, vcsHost models.VCSHostType) Commen case models.PlanCommand.String(): name = models.PlanCommand flagSet = pflag.NewFlagSet(models.PlanCommand.String(), pflag.ContinueOnError) - flagSet.SetOutput(ioutil.Discard) + flagSet.SetOutput(io.Discard) flagSet.StringVarP(&workspace, workspaceFlagLong, workspaceFlagShort, "", "Switch to this Terraform workspace before planning.") flagSet.StringVarP(&dir, dirFlagLong, dirFlagShort, "", "Which directory to run plan in relative to root of repo, ex. 'child/dir'.") flagSet.StringVarP(&project, projectFlagLong, projectFlagShort, "", fmt.Sprintf("Which project to run plan for. Refers to the name of the project configured in %s. Cannot be used at same time as workspace or dir flags.", yaml.AtlantisYAMLFilename)) @@ -191,7 +191,7 @@ func (e *CommentParser) Parse(comment string, vcsHost models.VCSHostType) Commen case models.ApplyCommand.String(): name = models.ApplyCommand flagSet = pflag.NewFlagSet(models.ApplyCommand.String(), pflag.ContinueOnError) - flagSet.SetOutput(ioutil.Discard) + flagSet.SetOutput(io.Discard) flagSet.StringVarP(&workspace, workspaceFlagLong, workspaceFlagShort, "", "Apply the plan for this Terraform workspace.") flagSet.StringVarP(&dir, dirFlagLong, dirFlagShort, "", "Apply the plan for this directory, relative to root of repo, ex. 'child/dir'.") flagSet.StringVarP(&project, projectFlagLong, projectFlagShort, "", fmt.Sprintf("Apply the plan for this project. Refers to the name of the project configured in %s. Cannot be used at same time as workspace or dir flags.", yaml.AtlantisYAMLFilename)) @@ -200,12 +200,12 @@ func (e *CommentParser) Parse(comment string, vcsHost models.VCSHostType) Commen case models.ApprovePoliciesCommand.String(): name = models.ApprovePoliciesCommand flagSet = pflag.NewFlagSet(models.ApprovePoliciesCommand.String(), pflag.ContinueOnError) - flagSet.SetOutput(ioutil.Discard) + flagSet.SetOutput(io.Discard) flagSet.BoolVarP(&verbose, verboseFlagLong, verboseFlagShort, false, "Append Atlantis log to comment.") case models.UnlockCommand.String(): name = models.UnlockCommand flagSet = pflag.NewFlagSet(models.UnlockCommand.String(), pflag.ContinueOnError) - flagSet.SetOutput(ioutil.Discard) + flagSet.SetOutput(io.Discard) case models.VersionCommand.String(): name = models.VersionCommand flagSet = pflag.NewFlagSet(models.VersionCommand.String(), pflag.ContinueOnError) diff --git a/server/events/event_parser_test.go b/server/events/event_parser_test.go index 1922de084..c98fcd8ab 100644 --- a/server/events/event_parser_test.go +++ b/server/events/event_parser_test.go @@ -16,7 +16,7 @@ package events_test import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -325,7 +325,7 @@ func TestParseGithubPull(t *testing.T) { func TestParseGitlabMergeEvent(t *testing.T) { t.Log("should properly parse a gitlab merge event") path := filepath.Join("testdata", "gitlab-merge-request-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) var event *gitlab.MergeEvent err = json.Unmarshal(bytes, &event) @@ -382,7 +382,7 @@ func TestParseGitlabMergeEvent(t *testing.T) { // i.e. instead of under an owner/repo it's under an owner/group/subgroup/repo. func TestParseGitlabMergeEvent_Subgroup(t *testing.T) { path := filepath.Join("testdata", "gitlab-merge-request-event-subgroup.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) var event *gitlab.MergeEvent err = json.Unmarshal(bytes, &event) @@ -457,7 +457,7 @@ func TestParseGitlabMergeEvent_ActionType(t *testing.T) { } path := filepath.Join("testdata", "gitlab-merge-request-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) mergeEventJSON := string(bytes) @@ -479,7 +479,7 @@ func TestParseGitlabMergeEvent_ActionType(t *testing.T) { func TestParseGitlabMergeRequest(t *testing.T) { t.Log("should properly parse a gitlab merge request") path := filepath.Join("testdata", "gitlab-get-merge-request.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -517,7 +517,7 @@ func TestParseGitlabMergeRequest(t *testing.T) { func TestParseGitlabMergeRequest_Subgroup(t *testing.T) { path := filepath.Join("testdata", "gitlab-get-merge-request-subgroup.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -552,7 +552,7 @@ func TestParseGitlabMergeRequest_Subgroup(t *testing.T) { func TestParseGitlabMergeCommentEvent(t *testing.T) { t.Log("should properly parse a gitlab merge comment event") path := filepath.Join("testdata", "gitlab-merge-request-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) var event *gitlab.MergeCommentEvent err = json.Unmarshal(bytes, &event) @@ -589,7 +589,7 @@ func TestParseGitlabMergeCommentEvent(t *testing.T) { // Should properly parse a gitlab merge comment event from a subgroup repo. func TestParseGitlabMergeCommentEvent_Subgroup(t *testing.T) { path := filepath.Join("testdata", "gitlab-merge-request-comment-event-subgroup.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) var event *gitlab.MergeCommentEvent err = json.Unmarshal(bytes, &event) @@ -738,7 +738,7 @@ func TestParseBitbucketCloudCommentEvent_EmptyObject(t *testing.T) { func TestParseBitbucketCloudCommentEvent_CommitHashMissing(t *testing.T) { path := filepath.Join("testdata", "bitbucket-cloud-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) emptyCommitHash := strings.Replace(string(bytes), ` "hash": "e0624da46d3a",`, "", -1) _, _, _, _, _, err = parser.ParseBitbucketCloudPullCommentEvent([]byte(emptyCommitHash)) @@ -747,7 +747,7 @@ func TestParseBitbucketCloudCommentEvent_CommitHashMissing(t *testing.T) { func TestParseBitbucketCloudCommentEvent_ValidEvent(t *testing.T) { path := filepath.Join("testdata", "bitbucket-cloud-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) Ok(t, err) pull, baseRepo, headRepo, user, comment, err := parser.ParseBitbucketCloudPullCommentEvent(bytes) Ok(t, err) @@ -792,7 +792,7 @@ func TestParseBitbucketCloudCommentEvent_ValidEvent(t *testing.T) { func TestParseBitbucketCloudCommentEvent_MultipleStates(t *testing.T) { path := filepath.Join("testdata", "bitbucket-cloud-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -831,7 +831,7 @@ func TestParseBitbucketCloudCommentEvent_MultipleStates(t *testing.T) { func TestParseBitbucketCloudPullEvent_ValidEvent(t *testing.T) { path := filepath.Join("testdata", "bitbucket-cloud-pull-event-created.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -894,7 +894,7 @@ func TestParseBitbucketCloudPullEvent_States(t *testing.T) { }, } { path := filepath.Join("testdata", c.JSON) - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -950,7 +950,7 @@ func TestParseBitbucketServerCommentEvent_EmptyObject(t *testing.T) { func TestParseBitbucketServerCommentEvent_CommitHashMissing(t *testing.T) { path := filepath.Join("testdata", "bitbucket-server-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -961,7 +961,7 @@ func TestParseBitbucketServerCommentEvent_CommitHashMissing(t *testing.T) { func TestParseBitbucketServerCommentEvent_ValidEvent(t *testing.T) { path := filepath.Join("testdata", "bitbucket-server-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -1008,7 +1008,7 @@ func TestParseBitbucketServerCommentEvent_ValidEvent(t *testing.T) { func TestParseBitbucketServerCommentEvent_MultipleStates(t *testing.T) { path := filepath.Join("testdata", "bitbucket-server-comment-event.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } @@ -1043,7 +1043,7 @@ func TestParseBitbucketServerCommentEvent_MultipleStates(t *testing.T) { func TestParseBitbucketServerPullEvent_ValidEvent(t *testing.T) { path := filepath.Join("testdata", "bitbucket-server-pull-event-merged.json") - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { Ok(t, err) } diff --git a/server/events/git_cred_writer.go b/server/events/git_cred_writer.go index 1eea384c2..b8e83facb 100644 --- a/server/events/git_cred_writer.go +++ b/server/events/git_cred_writer.go @@ -2,7 +2,6 @@ package events import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -24,7 +23,7 @@ func WriteGitCreds(gitUser string, gitToken string, gitHostname string, home str // If the file doesn't exist, write it. if _, err := os.Stat(credsFile); err != nil { - if err := ioutil.WriteFile(credsFile, []byte(config), 0600); err != nil { + if err := os.WriteFile(credsFile, []byte(config), 0600); err != nil { return errors.Wrapf(err, "writing generated %s file with user, token and hostname to %s", credsFilename, credsFile) } logger.Info("wrote git credentials to %s", credsFile) @@ -68,7 +67,7 @@ func WriteGitCreds(gitUser string, gitToken string, gitHostname string, home str } func fileHasLine(line string, filename string) (bool, error) { - currContents, err := ioutil.ReadFile(filename) // nolint: gosec + currContents, err := os.ReadFile(filename) // nolint: gosec if err != nil { return false, errors.Wrapf(err, "reading %s", filename) } @@ -81,18 +80,18 @@ func fileHasLine(line string, filename string) (bool, error) { } func fileAppend(line string, filename string) error { - currContents, err := ioutil.ReadFile(filename) // nolint: gosec + currContents, err := os.ReadFile(filename) // nolint: gosec if err != nil { return err } if len(currContents) > 0 && !strings.HasSuffix(string(currContents), "\n") { line = "\n" + line } - return ioutil.WriteFile(filename, []byte(string(currContents)+line), 0600) + return os.WriteFile(filename, []byte(string(currContents)+line), 0600) } func fileLineReplace(line, user, host, filename string) error { - currContents, err := ioutil.ReadFile(filename) // nolint: gosec + currContents, err := os.ReadFile(filename) // nolint: gosec if err != nil { return err } @@ -112,5 +111,5 @@ func fileLineReplace(line, user, host, filename string) error { return fileAppend(line, filename) } - return ioutil.WriteFile(filename, []byte(toWrite), 0600) + return os.WriteFile(filename, []byte(toWrite), 0600) } diff --git a/server/events/git_cred_writer_test.go b/server/events/git_cred_writer_test.go index c8fc9a2cc..9d9583abb 100644 --- a/server/events/git_cred_writer_test.go +++ b/server/events/git_cred_writer_test.go @@ -2,7 +2,7 @@ package events_test import ( "fmt" - "io/ioutil" + "os" "os/exec" "path/filepath" "testing" @@ -24,7 +24,7 @@ func TestWriteGitCreds_WriteFile(t *testing.T) { expContents := `https://user:token@hostname` - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".git-credentials")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".git-credentials")) Ok(t, err) Equals(t, expContents, string(actContents)) } @@ -36,14 +36,14 @@ func TestWriteGitCreds_Appends(t *testing.T) { defer cleanup() credsFile := filepath.Join(tmp, ".git-credentials") - err := ioutil.WriteFile(credsFile, []byte("contents"), 0600) + err := os.WriteFile(credsFile, []byte("contents"), 0600) Ok(t, err) err = events.WriteGitCreds("user", "token", "hostname", tmp, logger, false) Ok(t, err) expContents := "contents\nhttps://user:token@hostname" - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".git-credentials")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".git-credentials")) Ok(t, err) Equals(t, expContents, string(actContents)) } @@ -56,12 +56,12 @@ func TestWriteGitCreds_NoModification(t *testing.T) { credsFile := filepath.Join(tmp, ".git-credentials") contents := "line1\nhttps://user:token@hostname\nline2" - err := ioutil.WriteFile(credsFile, []byte(contents), 0600) + err := os.WriteFile(credsFile, []byte(contents), 0600) Ok(t, err) err = events.WriteGitCreds("user", "token", "hostname", tmp, logger, false) Ok(t, err) - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".git-credentials")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".git-credentials")) Ok(t, err) Equals(t, contents, string(actContents)) } @@ -73,13 +73,13 @@ func TestWriteGitCreds_ReplaceApp(t *testing.T) { credsFile := filepath.Join(tmp, ".git-credentials") contents := "line1\nhttps://x-access-token:v1.87dddddddddddddddd@github.com\nline2" - err := ioutil.WriteFile(credsFile, []byte(contents), 0600) + err := os.WriteFile(credsFile, []byte(contents), 0600) Ok(t, err) err = events.WriteGitCreds("x-access-token", "token", "github.com", tmp, logger, true) Ok(t, err) expContets := "line1\nhttps://x-access-token:token@github.com\nline2" - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".git-credentials")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".git-credentials")) Ok(t, err) Equals(t, expContets, string(actContents)) } @@ -91,13 +91,13 @@ func TestWriteGitCreds_AppendApp(t *testing.T) { credsFile := filepath.Join(tmp, ".git-credentials") contents := "" - err := ioutil.WriteFile(credsFile, []byte(contents), 0600) + err := os.WriteFile(credsFile, []byte(contents), 0600) Ok(t, err) err = events.WriteGitCreds("x-access-token", "token", "github.com", tmp, logger, true) Ok(t, err) expContets := "https://x-access-token:token@github.com" - actContents, err := ioutil.ReadFile(filepath.Join(tmp, ".git-credentials")) + actContents, err := os.ReadFile(filepath.Join(tmp, ".git-credentials")) Ok(t, err) Equals(t, expContets, string(actContents)) } @@ -109,7 +109,7 @@ func TestWriteGitCreds_ErrIfCannotRead(t *testing.T) { defer cleanup() credsFile := filepath.Join(tmp, ".git-credentials") - err := ioutil.WriteFile(credsFile, []byte("can't see me!"), 0000) + err := os.WriteFile(credsFile, []byte("can't see me!"), 0000) Ok(t, err) expErr := fmt.Sprintf("open %s: permission denied", credsFile) diff --git a/server/events/pending_plan_finder.go b/server/events/pending_plan_finder.go index bff75b623..38b8bbdec 100644 --- a/server/events/pending_plan_finder.go +++ b/server/events/pending_plan_finder.go @@ -1,7 +1,6 @@ package events import ( - "io/ioutil" "os" "os/exec" "path/filepath" @@ -43,7 +42,7 @@ func (p *DefaultPendingPlanFinder) Find(pullDir string) ([]PendingPlan, error) { } func (p *DefaultPendingPlanFinder) findWithAbsPaths(pullDir string) ([]PendingPlan, []string, error) { - workspaceDirs, err := ioutil.ReadDir(pullDir) + workspaceDirs, err := os.ReadDir(pullDir) if err != nil { return nil, nil, err } diff --git a/server/events/project_command_builder_internal_test.go b/server/events/project_command_builder_internal_test.go index 9d8891907..11dd743b1 100644 --- a/server/events/project_command_builder_internal_test.go +++ b/server/events/project_command_builder_internal_test.go @@ -1,7 +1,7 @@ package events import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -571,7 +571,7 @@ projects: // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") - Ok(t, ioutil.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) + Ok(t, os.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) parser := &yaml.ParserValidator{} globalCfgArgs := valid.GlobalCfgArgs{ AllowRepoCfg: false, @@ -583,7 +583,7 @@ projects: Ok(t, err) if c.repoCfg != "" { - Ok(t, ioutil.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) + Ok(t, os.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) } builder := NewProjectCommandBuilder( @@ -764,13 +764,13 @@ projects: // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") - Ok(t, ioutil.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) + Ok(t, os.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) parser := &yaml.ParserValidator{} globalCfg, err := parser.ParseGlobalCfg(globalCfgPath, valid.NewGlobalCfg(false, false, false)) Ok(t, err) if c.repoCfg != "" { - Ok(t, ioutil.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) + Ok(t, os.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) } builder := NewProjectCommandBuilder( @@ -970,7 +970,7 @@ workflows: // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") - Ok(t, ioutil.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) + Ok(t, os.WriteFile(globalCfgPath, []byte(c.globalCfg), 0600)) parser := &yaml.ParserValidator{} globalCfgArgs := valid.GlobalCfgArgs{ AllowRepoCfg: false, @@ -983,7 +983,7 @@ workflows: Ok(t, err) if c.repoCfg != "" { - Ok(t, ioutil.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) + Ok(t, os.WriteFile(filepath.Join(tmp, "atlantis.yaml"), []byte(c.repoCfg), 0600)) } builder := NewProjectCommandBuilder( diff --git a/server/events/project_command_builder_test.go b/server/events/project_command_builder_test.go index 14b43c362..b7f32c88f 100644 --- a/server/events/project_command_builder_test.go +++ b/server/events/project_command_builder_test.go @@ -2,7 +2,7 @@ package events_test import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -132,7 +132,7 @@ projects: vcsClient := vcsmocks.NewMockClient() When(vcsClient.GetModifiedFiles(matchers.AnyModelsRepo(), matchers.AnyModelsPullRequest())).ThenReturn([]string{"main.tf"}, nil) if c.AtlantisYAML != "" { - err := ioutil.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) + err := os.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) Ok(t, err) } @@ -394,7 +394,7 @@ projects: vcsClient := vcsmocks.NewMockClient() When(vcsClient.GetModifiedFiles(matchers.AnyModelsRepo(), matchers.AnyModelsPullRequest())).ThenReturn([]string{"main.tf"}, nil) if c.AtlantisYAML != "" { - err := ioutil.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) + err := os.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) Ok(t, err) } @@ -545,7 +545,7 @@ projects: vcsClient := vcsmocks.NewMockClient() When(vcsClient.GetModifiedFiles(matchers.AnyModelsRepo(), matchers.AnyModelsPullRequest())).ThenReturn(c.ModifiedFiles, nil) if c.AtlantisYAML != "" { - err := ioutil.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) + err := os.WriteFile(filepath.Join(tmpDir, yaml.AtlantisYAMLFilename), []byte(c.AtlantisYAML), 0600) Ok(t, err) } @@ -703,7 +703,7 @@ projects: - dir: . workspace: staging ` - err := ioutil.WriteFile(filepath.Join(repoDir, yaml.AtlantisYAMLFilename), []byte(yamlCfg), 0600) + err := os.WriteFile(filepath.Join(repoDir, yaml.AtlantisYAMLFilename), []byte(yamlCfg), 0600) Ok(t, err) When(workingDir.Clone( diff --git a/server/events/project_finder_test.go b/server/events/project_finder_test.go index b4e523ae3..8135a5e93 100644 --- a/server/events/project_finder_test.go +++ b/server/events/project_finder_test.go @@ -14,7 +14,6 @@ package events_test import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -46,7 +45,7 @@ func setupTmpRepos(t *testing.T) { // modules/ // main.tf var err error - nestedModules1, err = ioutil.TempDir("", "") + nestedModules1, err = os.MkdirTemp("", "") Ok(t, err) err = os.MkdirAll(filepath.Join(nestedModules1, "project1/modules"), 0700) Ok(t, err) @@ -78,7 +77,7 @@ func setupTmpRepos(t *testing.T) { // main.tf // project2/ // main.tf - topLevelModules, err = ioutil.TempDir("", "") + topLevelModules, err = os.MkdirTemp("", "") Ok(t, err) for _, path := range []string{"modules", "project1", "project2"} { err = os.MkdirAll(filepath.Join(topLevelModules, path), 0700) @@ -93,7 +92,7 @@ func setupTmpRepos(t *testing.T) { // staging.tfvars // production.tfvars // global-env-config.auto.tfvars.json - envDir, err = ioutil.TempDir("", "") + envDir, err = os.MkdirTemp("", "") Ok(t, err) err = os.MkdirAll(filepath.Join(envDir, "env"), 0700) Ok(t, err) diff --git a/server/events/vcs/azuredevops_client_test.go b/server/events/vcs/azuredevops_client_test.go index d7c40ee6c..a9314fd03 100644 --- a/server/events/vcs/azuredevops_client_test.go +++ b/server/events/vcs/azuredevops_client_test.go @@ -3,10 +3,11 @@ package vcs_test import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" @@ -191,7 +192,7 @@ func TestAzureDevopsClient_UpdateStatus(t *testing.T) { case "/owner/project/_apis/git/repositories/repo/pullrequests/22/statuses?api-version=5.1-preview.1": gotRequest = true defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) Ok(t, err) exp := fmt.Sprintf(partResponse, c.expState) if c.supportsIterations == true { @@ -361,10 +362,10 @@ func TestAzureDevopsClient_PullIsMergeable(t *testing.T) { }, } - jsonPullRequestBytes, err := ioutil.ReadFile("fixtures/azuredevops-pr.json") + jsonPullRequestBytes, err := os.ReadFile("fixtures/azuredevops-pr.json") Ok(t, err) - jsonPolicyEvaluationBytes, err := ioutil.ReadFile("fixtures/azuredevops-policyevaluations.json") + jsonPolicyEvaluationBytes, err := os.ReadFile("fixtures/azuredevops-policyevaluations.json") Ok(t, err) pullRequestBody := string(jsonPullRequestBytes) @@ -465,7 +466,7 @@ func TestAzureDevopsClient_PullIsApproved(t *testing.T) { }, } - jsBytes, err := ioutil.ReadFile("fixtures/azuredevops-pr.json") + jsBytes, err := os.ReadFile("fixtures/azuredevops-pr.json") Ok(t, err) json := string(jsBytes) @@ -516,7 +517,7 @@ func TestAzureDevopsClient_PullIsApproved(t *testing.T) { func TestAzureDevopsClient_GetPullRequest(t *testing.T) { // Use a real Azure DevOps json response and edit the mergeable_state field. - jsBytes, err := ioutil.ReadFile("fixtures/azuredevops-pr.json") + jsBytes, err := os.ReadFile("fixtures/azuredevops-pr.json") Ok(t, err) response := string(jsBytes) diff --git a/server/events/vcs/bitbucketcloud/client.go b/server/events/vcs/bitbucketcloud/client.go index 979fcdc56..38dfa56a6 100644 --- a/server/events/vcs/bitbucketcloud/client.go +++ b/server/events/vcs/bitbucketcloud/client.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "github.com/pkg/errors" @@ -236,10 +235,10 @@ func (b *Client) makeRequest(method string, path string, reqBody io.Reader) ([]b requestStr := fmt.Sprintf("%s %s", method, path) if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - respBody, _ := ioutil.ReadAll(resp.Body) + respBody, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("making request %q unexpected status code: %d, body: %s", requestStr, resp.StatusCode, string(respBody)) } - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrapf(err, "reading response from request %q", requestStr) } diff --git a/server/events/vcs/bitbucketcloud/client_test.go b/server/events/vcs/bitbucketcloud/client_test.go index b14c54894..54e5179be 100644 --- a/server/events/vcs/bitbucketcloud/client_test.go +++ b/server/events/vcs/bitbucketcloud/client_test.go @@ -2,9 +2,9 @@ package bitbucketcloud_test import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -181,7 +181,7 @@ func TestClient_PullIsApproved(t *testing.T) { for _, c := range cases { t.Run(c.description, func(t *testing.T) { - json, err := ioutil.ReadFile(filepath.Join("testdata", c.testdata)) + json, err := os.ReadFile(filepath.Join("testdata", c.testdata)) Ok(t, err) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.RequestURI { diff --git a/server/events/vcs/bitbucketserver/client.go b/server/events/vcs/bitbucketserver/client.go index 2a0e67e8f..38a8acac1 100644 --- a/server/events/vcs/bitbucketserver/client.go +++ b/server/events/vcs/bitbucketserver/client.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "regexp" @@ -324,10 +323,10 @@ func (b *Client) makeRequest(method string, path string, reqBody io.Reader) ([]b requestStr := fmt.Sprintf("%s %s", method, path) if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated && resp.StatusCode != 204 { - respBody, _ := ioutil.ReadAll(resp.Body) + respBody, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("making request %q unexpected status code: %d, body: %s", requestStr, resp.StatusCode, string(respBody)) } - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrapf(err, "reading response from request %q", requestStr) } diff --git a/server/events/vcs/bitbucketserver/client_test.go b/server/events/vcs/bitbucketserver/client_test.go index 2443e5f80..73aa8b096 100644 --- a/server/events/vcs/bitbucketserver/client_test.go +++ b/server/events/vcs/bitbucketserver/client_test.go @@ -3,9 +3,10 @@ package bitbucketserver_test import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "path/filepath" "strings" "testing" @@ -138,7 +139,7 @@ func TestClient_GetModifiedFilesPagination(t *testing.T) { // Test that we use the correct version parameter in our call to merge the pull // request. func TestClient_MergePull(t *testing.T) { - pullRequest, err := ioutil.ReadFile(filepath.Join("testdata", "pull-request.json")) + pullRequest, err := os.ReadFile(filepath.Join("testdata", "pull-request.json")) Ok(t, err) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.RequestURI { @@ -187,7 +188,7 @@ func TestClient_MergePull(t *testing.T) { // Test that we delete the source branch in our call to merge the pull // request. func TestClient_MergePullDeleteSourceBranch(t *testing.T) { - pullRequest, err := ioutil.ReadFile(filepath.Join("testdata", "pull-request.json")) + pullRequest, err := os.ReadFile(filepath.Join("testdata", "pull-request.json")) Ok(t, err) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.RequestURI { @@ -201,7 +202,7 @@ func TestClient_MergePullDeleteSourceBranch(t *testing.T) { case "/rest/branch-utils/1.0/projects/ow/repos/repo/branches": Equals(t, "DELETE", r.Method) defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) Ok(t, err) var payload bitbucketserver.DeleteSourceBranch err = json.Unmarshal(b, &payload) diff --git a/server/events/vcs/github_client_test.go b/server/events/vcs/github_client_test.go index 9d90e268b..bb4f55703 100644 --- a/server/events/vcs/github_client_test.go +++ b/server/events/vcs/github_client_test.go @@ -4,10 +4,11 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" @@ -169,7 +170,7 @@ func TestGithubClient_PaginatesComments(t *testing.T) { switch r.Method + " " + r.RequestURI { case "POST /api/graphql": defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { t.Errorf("read body error: %v", err) http.Error(w, "server error", http.StatusInternalServerError) @@ -272,7 +273,7 @@ func TestGithubClient_HideOldComments(t *testing.T) { return } defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { t.Errorf("read body error: %v", err) http.Error(w, "server error", http.StatusInternalServerError) @@ -350,7 +351,7 @@ func TestGithubClient_UpdateStatus(t *testing.T) { http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.RequestURI { case "/api/v3/repos/owner/repo/statuses/": - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) Ok(t, err) exp := fmt.Sprintf(`{"state":"%s","target_url":"https://google.com","description":"description","context":"src"}%s`, c.expState, "\n") Equals(t, exp, string(body)) @@ -516,7 +517,7 @@ func TestGithubClient_PullIsMergeable(t *testing.T) { } // Use a real GitHub json response and edit the mergeable_state field. - jsBytes, err := ioutil.ReadFile("fixtures/github-pull-request.json") + jsBytes, err := os.ReadFile("fixtures/github-pull-request.json") Ok(t, err) json := string(jsBytes) @@ -590,7 +591,7 @@ func TestGithubClient_MergePullHandlesError(t *testing.T) { }, } - jsBytes, err := ioutil.ReadFile("fixtures/github-repo.json") + jsBytes, err := os.ReadFile("fixtures/github-repo.json") Ok(t, err) for _, c := range cases { @@ -602,7 +603,7 @@ func TestGithubClient_MergePullHandlesError(t *testing.T) { w.Write(jsBytes) // nolint: errcheck return case "/api/v3/repos/owner/repo/pulls/1/merge": - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) Ok(t, err) exp := "{\"merge_method\":\"merge\"}\n" Equals(t, exp, string(body)) @@ -700,7 +701,7 @@ func TestGithubClient_MergePullCorrectMethod(t *testing.T) { t.Run(name, func(t *testing.T) { // Modify response. - jsBytes, err := ioutil.ReadFile("fixtures/github-repo.json") + jsBytes, err := os.ReadFile("fixtures/github-repo.json") Ok(t, err) resp := string(jsBytes) resp = strings.Replace(resp, @@ -723,7 +724,7 @@ func TestGithubClient_MergePullCorrectMethod(t *testing.T) { w.Write([]byte(resp)) // nolint: errcheck return case "/api/v3/repos/runatlantis/atlantis/pulls/1/merge": - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) Ok(t, err) defer r.Body.Close() // nolint: errcheck type bodyJSON struct { @@ -806,7 +807,7 @@ func TestGithubClient_SplitComments(t *testing.T) { switch r.Method + " " + r.RequestURI { case "POST /api/v3/repos/runatlantis/atlantis/issues/1/comments": defer r.Body.Close() // nolint: errcheck - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { t.Errorf("read body error: %v", err) http.Error(w, "server error", http.StatusInternalServerError) diff --git a/server/events/vcs/gitlab_client_test.go b/server/events/vcs/gitlab_client_test.go index 9fdc29e0a..ceb393293 100644 --- a/server/events/vcs/gitlab_client_test.go +++ b/server/events/vcs/gitlab_client_test.go @@ -2,7 +2,7 @@ package vcs import ( "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -210,7 +210,7 @@ func TestGitlabClient_UpdateStatus(t *testing.T) { case "/api/v4/projects/runatlantis%2Fatlantis/statuses/sha": gotRequest = true - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) Ok(t, err) exp := fmt.Sprintf(`{"state":"%s","context":"src","target_url":"https://google.com","description":"description"}`, c.expState) Equals(t, exp, string(body)) diff --git a/server/events/yaml/parser_validator.go b/server/events/yaml/parser_validator.go index d21b221cc..00f4592f3 100644 --- a/server/events/yaml/parser_validator.go +++ b/server/events/yaml/parser_validator.go @@ -3,7 +3,6 @@ package yaml import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -46,7 +45,7 @@ func (p *ParserValidator) HasRepoCfg(absRepoDir string) (bool, error) { // If there was no config file, it will return an os.IsNotExist(error). func (p *ParserValidator) ParseRepoCfg(absRepoDir string, globalCfg valid.GlobalCfg, repoID string) (valid.RepoCfg, error) { configFile := p.repoCfgPath(absRepoDir, AtlantisYAMLFilename) - configData, err := ioutil.ReadFile(configFile) // nolint: gosec + configData, err := os.ReadFile(configFile) // nolint: gosec if err != nil { if !os.IsNotExist(err) { @@ -94,7 +93,7 @@ func (p *ParserValidator) ParseRepoCfgData(repoCfgData []byte, globalCfg valid.G // configFile. defaultCfg will be merged into the parsed config. // If there is no file at configFile it will return an error. func (p *ParserValidator) ParseGlobalCfg(configFile string, defaultCfg valid.GlobalCfg) (valid.GlobalCfg, error) { - configData, err := ioutil.ReadFile(configFile) // nolint: gosec + configData, err := os.ReadFile(configFile) // nolint: gosec if err != nil { return valid.GlobalCfg{}, errors.Wrapf(err, "unable to read %s file", configFile) } diff --git a/server/events/yaml/parser_validator_test.go b/server/events/yaml/parser_validator_test.go index a722585e0..a58db826e 100644 --- a/server/events/yaml/parser_validator_test.go +++ b/server/events/yaml/parser_validator_test.go @@ -2,7 +2,6 @@ package yaml_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -68,7 +67,7 @@ func TestParseRepoCfg_FileDoesNotExist(t *testing.T) { func TestParseRepoCfg_BadPermissions(t *testing.T) { tmpDir, cleanup := TempDir(t) defer cleanup() - err := ioutil.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), nil, 0000) + err := os.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), nil, 0000) Ok(t, err) r := yaml.ParserValidator{} @@ -103,7 +102,7 @@ func TestParseCfgs_InvalidYAML(t *testing.T) { for _, c := range cases { t.Run(c.description, func(t *testing.T) { confPath := filepath.Join(tmpDir, "atlantis.yaml") - err := ioutil.WriteFile(confPath, []byte(c.input), 0600) + err := os.WriteFile(confPath, []byte(c.input), 0600) Ok(t, err) r := yaml.ParserValidator{} _, err = r.ParseRepoCfg(tmpDir, globalCfg, "") @@ -1068,7 +1067,7 @@ workflows: for _, c := range cases { t.Run(c.description, func(t *testing.T) { - err := ioutil.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), []byte(c.input), 0600) + err := os.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), []byte(c.input), 0600) Ok(t, err) r := yaml.ParserValidator{} @@ -1096,7 +1095,7 @@ projects: workflow: custom workflows: custom: ~` - err := ioutil.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), []byte(repoCfg), 0600) + err := os.WriteFile(filepath.Join(tmpDir, "atlantis.yaml"), []byte(repoCfg), 0600) Ok(t, err) r := yaml.ParserValidator{} @@ -1474,7 +1473,7 @@ workflows: tmp, cleanup := TempDir(t) defer cleanup() path := filepath.Join(tmp, "conf.yaml") - Ok(t, ioutil.WriteFile(path, []byte(c.input), 0600)) + Ok(t, os.WriteFile(path, []byte(c.input), 0600)) globalCfgArgs := valid.GlobalCfgArgs{ AllowRepoCfg: false, @@ -1735,8 +1734,8 @@ func TestParseRepoCfg_V2ShellParsing(t *testing.T) { apply: steps: - run: %s`, c.in, c.in) - Ok(t, ioutil.WriteFile(v2Path, []byte("version: 2\n"+cfg), 0600)) - Ok(t, ioutil.WriteFile(v3Path, []byte("version: 3\n"+cfg), 0600)) + Ok(t, os.WriteFile(v2Path, []byte("version: 2\n"+cfg), 0600)) + Ok(t, os.WriteFile(v3Path, []byte("version: 3\n"+cfg), 0600)) p := &yaml.ParserValidator{} globalCfgArgs := valid.GlobalCfgArgs{ diff --git a/server/events/yaml/valid/global_cfg_test.go b/server/events/yaml/valid/global_cfg_test.go index f317a8101..d1570ac2e 100644 --- a/server/events/yaml/valid/global_cfg_test.go +++ b/server/events/yaml/valid/global_cfg_test.go @@ -2,7 +2,7 @@ package valid_test import ( "fmt" - "io/ioutil" + "os" "path/filepath" "regexp" "testing" @@ -661,7 +661,7 @@ policies: var global valid.GlobalCfg if c.gCfg != "" { path := filepath.Join(tmp, "config.yaml") - Ok(t, ioutil.WriteFile(path, []byte(c.gCfg), 0600)) + Ok(t, os.WriteFile(path, []byte(c.gCfg), 0600)) var err error globalCfgArgs := valid.GlobalCfgArgs{ AllowRepoCfg: false, @@ -832,7 +832,7 @@ repos: var global valid.GlobalCfg if c.gCfg != "" { path := filepath.Join(tmp, "config.yaml") - Ok(t, ioutil.WriteFile(path, []byte(c.gCfg), 0600)) + Ok(t, os.WriteFile(path, []byte(c.gCfg), 0600)) var err error globalCfgArgs := valid.GlobalCfgArgs{ AllowRepoCfg: false, diff --git a/server/recovery/recovery.go b/server/recovery/recovery.go index aff293fcf..1039ef750 100644 --- a/server/recovery/recovery.go +++ b/server/recovery/recovery.go @@ -22,7 +22,7 @@ package recovery import ( "bytes" "fmt" - "io/ioutil" + "os" "runtime" ) @@ -48,7 +48,7 @@ func Stack(skip int) []byte { // Print this much at least. If we can't find the source, it won't show. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) if file != lastFile { - data, err := ioutil.ReadFile(file) // nolint: gosec + data, err := os.ReadFile(file) // nolint: gosec if err != nil { continue } diff --git a/server/server.go b/server/server.go index dbf399292..5519ed18a 100644 --- a/server/server.go +++ b/server/server.go @@ -20,7 +20,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "log" "net/http" "net/url" @@ -158,7 +157,7 @@ func NewServer(userConfig UserConfig, config Config) (*Server, error) { Token: userConfig.GithubToken, } } else if userConfig.GithubAppID != 0 && userConfig.GithubAppKeyFile != "" { - privateKey, err := ioutil.ReadFile(userConfig.GithubAppKeyFile) + privateKey, err := os.ReadFile(userConfig.GithubAppKeyFile) if err != nil { return nil, err } diff --git a/server/server_test.go b/server/server_test.go index 3b62d35b3..4ed72785a 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -16,10 +16,11 @@ package server_test import ( "bytes" "errors" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" + "os" "testing" "time" @@ -36,7 +37,7 @@ import ( func TestNewServer(t *testing.T) { t.Log("Run through NewServer constructor") - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") Ok(t, err) _, err = server.NewServer(server.UserConfig{ DataDir: tmpDir, @@ -48,7 +49,7 @@ func TestNewServer(t *testing.T) { // todo: test what happens if we set different flags. The generated config should be different. func TestNewServer_InvalidAtlantisURL(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") Ok(t, err) _, err = server.NewServer(server.UserConfig{ DataDir: tmpDir, @@ -138,7 +139,7 @@ func TestHealthz(t *testing.T) { w := httptest.NewRecorder() s.Healthz(w, req) Equals(t, http.StatusOK, w.Result().StatusCode) - body, _ := ioutil.ReadAll(w.Result().Body) + body, _ := io.ReadAll(w.Result().Body) Equals(t, "application/json", w.Result().Header["Content-Type"][0]) Equals(t, `{ diff --git a/testdrive/testdrive.go b/testdrive/testdrive.go index 0e0356fde..8ad0d1f86 100644 --- a/testdrive/testdrive.go +++ b/testdrive/testdrive.go @@ -18,7 +18,6 @@ package testdrive import ( "context" "fmt" - "io/ioutil" "os" "os/exec" "os/signal" @@ -173,11 +172,11 @@ tunnels: proto: http `, ngrokAPIURL, atlantisPort) - ngrokConfigFile, err := ioutil.TempFile("", "") + ngrokConfigFile, err := os.CreateTemp("", "") if err != nil { return errors.Wrap(err, "creating ngrok config file") } - err = ioutil.WriteFile(ngrokConfigFile.Name(), []byte(ngrokConfig), 0600) + err = os.WriteFile(ngrokConfigFile.Name(), []byte(ngrokConfig), 0600) if err != nil { return errors.Wrap(err, "writing ngrok config file") } @@ -211,7 +210,7 @@ tunnels: // Start atlantis server. colorstring.Println("=> starting atlantis server") s.Start() - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") if err != nil { return errors.Wrap(err, "creating a temporary data directory for Atlantis") } diff --git a/testdrive/utils.go b/testdrive/utils.go index 2edafec1b..a64b2c075 100644 --- a/testdrive/utils.go +++ b/testdrive/utils.go @@ -20,7 +20,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "os/exec" @@ -123,7 +122,7 @@ func getTunnelAddr() (string, error) { var t tunnels - body, err := ioutil.ReadAll(response.Body) + body, err := io.ReadAll(response.Body) if err != nil { return "", errors.Wrap(err, "reading ngrok api") } diff --git a/testing/http.go b/testing/http.go index ba19b5408..c6623e10b 100644 --- a/testing/http.go +++ b/testing/http.go @@ -1,7 +1,7 @@ package testing import ( - "io/ioutil" + "io" "net/http/httptest" "strings" "testing" @@ -9,7 +9,7 @@ import ( func ResponseContains(t *testing.T, r *httptest.ResponseRecorder, status int, bodySubstr string) { t.Helper() - body, err := ioutil.ReadAll(r.Result().Body) + body, err := io.ReadAll(r.Result().Body) Ok(t, err) Assert(t, status == r.Result().StatusCode, "exp %d got %d, body: %s", status, r.Result().StatusCode, string(body)) Assert(t, strings.Contains(string(body), bodySubstr), "exp %q to be contained in %q", bodySubstr, string(body)) diff --git a/testing/temp_files.go b/testing/temp_files.go index 6bab8f03a..3ee8b062c 100644 --- a/testing/temp_files.go +++ b/testing/temp_files.go @@ -1,7 +1,6 @@ package testing import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -12,7 +11,7 @@ import ( // dir, cleanup := TempDir() // defer cleanup() func TempDir(t *testing.T) (string, func()) { - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") Ok(t, err) return tmpDir, func() { os.RemoveAll(tmpDir) // nolint: errcheck @@ -65,7 +64,7 @@ func dirStructureGo(t *testing.T, parentDir string, structure map[string]interfa dirStructureGo(t, subDir, dirContents) } else if fileContent, ok := val.(string); ok { // If val is a string then key is a file name and val is the file's content - err := ioutil.WriteFile(filepath.Join(parentDir, key), []byte(fileContent), 0600) + err := os.WriteFile(filepath.Join(parentDir, key), []byte(fileContent), 0600) Ok(t, err) } }