Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move from io/ioutil to io and os package #1843

Merged
merged 1 commit into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions cmd/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ package cmd

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
Expand Down Expand Up @@ -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
}

Expand Down
3 changes: 1 addition & 2 deletions e2e/e2e.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ package main

import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions server/controllers/events/azuredevops_request_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package events

import (
"fmt"
"io/ioutil"
"io"
"net/http"

"github.com/mcdafydd/go-azuredevops/azuredevops"
Expand Down Expand Up @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions server/controllers/events/events_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ package events

import (
"fmt"
"io/ioutil"
"io"
"net/http"
"strings"

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
17 changes: 8 additions & 9 deletions server/controllers/events/events_controller_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package events_test
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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))
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
21 changes: 11 additions & 10 deletions server/controllers/events/events_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
Expand Down Expand Up @@ -201,15 +202,15 @@ 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")
w := httptest.NewRecorder()
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", "", "")
Expand All @@ -230,15 +231,15 @@ 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")
w := httptest.NewRecorder()
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())
Expand All @@ -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")
Expand All @@ -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", "", "")
Expand All @@ -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")
Expand All @@ -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())
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions server/controllers/events/github_request_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ package events
import (
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"

"github.com/google/go-github/v31/github"
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions server/controllers/events/gitlab_request_parser_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ package events
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"

gitlab "github.com/xanzy/go-gitlab"
Expand Down Expand Up @@ -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
}
Expand Down
8 changes: 4 additions & 4 deletions server/controllers/status_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package controllers_test
import (
"bytes"
"encoding/json"
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions server/core/db/boltdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
package db_test

import (
"io/ioutil"
"os"
"testing"
"time"
Expand Down Expand Up @@ -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"))
}
Expand Down
5 changes: 2 additions & 3 deletions server/core/runtime/apply_step_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package runtime

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
Expand All @@ -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)
}
Expand Down Expand Up @@ -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")
}
Expand Down
Loading