diff options
author | Toon Claes <toon@gitlab.com> | 2021-09-20 19:10:39 +0300 |
---|---|---|
committer | Toon Claes <toon@gitlab.com> | 2021-09-20 19:10:39 +0300 |
commit | 5b7382e0251176923f258aa8f8c23a8084f6cae9 (patch) | |
tree | 926cbabc7f5448d4521915424b8dac7ab4979951 | |
parent | 4b403d5d9bf9151b9cec4852b7bdff02202892f3 (diff) | |
parent | bb18ad9cb4e00d69207f856263c65b46aea37046 (diff) |
Merge branch 'pks-go-drop-1.15-support' into 'master'
Drop support for Go 1.15
See merge request gitlab-org/gitaly!3879
165 files changed, 373 insertions, 474 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 242f16730..793573b56 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -5,7 +5,7 @@ stages: - qa default: - image: registry.gitlab.com/gitlab-org/gitlab-build-images:ruby-2.7-golang-1.15-git-2.31 + image: registry.gitlab.com/gitlab-org/gitlab-build-images:ruby-2.7-golang-1.16-git-2.31 tags: - gitlab-org @@ -143,13 +143,13 @@ build: # These definitions are for the non-default Git versions. We do not want # to apply any additional Git patches on top of those given that they may # not cleanly apply and thus set GIT_PATCHES="". - - GO_VERSION: [ "1.15", "1.16", "1.17" ] + - GO_VERSION: [ "1.16", "1.17" ] GIT_VERSION: [ "v2.31.1", "v2.32.0" ] GIT_PATCHES: [ "" ] RUBY_VERSION: [ "2.7" ] # These definitions are for the default Git version where we want to # apply our default set of Git patches. - - GO_VERSION: [ "1.15", "1.16", "1.17" ] + - GO_VERSION: [ "1.16", "1.17" ] GIT_VERSION: [ "v2.33.0" ] RUBY_VERSION: [ "2.7" ] @@ -172,7 +172,7 @@ binaries: expire_in: 6 months parallel: matrix: - - GO_VERSION: [ "1.15", "1.16", "1.17" ] + - GO_VERSION: [ "1.16", "1.17" ] test: <<: *test_definition @@ -195,13 +195,13 @@ test: # These definitions are for the non-default Git versions. We do not want # to apply any additional Git patches on top of those given that they may # not cleanly apply and thus set GIT_PATCHES="". - - GO_VERSION: [ "1.15", "1.16", "1.17" ] + - GO_VERSION: [ "1.16", "1.17" ] GIT_VERSION: [ "v2.31.1", "v2.32.0" ] GIT_PATCHES: [ "" ] TARGET: test # These definitions are for the default Git version where we want to # apply our default set of Git patches. - - GO_VERSION: [ "1.15", "1.16", "1.17" ] + - GO_VERSION: [ "1.16", "1.17" ] GIT_VERSION: [ "v2.33.0" ] TARGET: test - GO_VERSION: "1.17" diff --git a/.golangci.yml b/.golangci.yml index d98c295a5..4b7eeab90 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -11,6 +11,7 @@ linters: - deadcode - errcheck - exportloopref + - depguard - gci - gofumpt - goimports @@ -723,3 +724,10 @@ issues: max-issues-per-linter: 0 # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. max-same-issues: 0 + +linters-settings: + depguard: + list-type: blacklist + include-go-root: true + packages-with-error-message: + - io/ioutil: "ioutil is deprecated starting with Go 1.16" diff --git a/.tool-versions b/.tool-versions index 1f86f8a6d..45f9a2391 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,3 +1,3 @@ # Versions of Gitaly dependencies managed by asdf. -golang 1.16.8 1.15.15 +golang 1.17.1 1.16.8 ruby 2.7.4 @@ -558,15 +558,9 @@ ${PROTOC}: ${TOOLS_DIR}/protoc.zip ${Q}rm -rf ${TOOLS_DIR}/protoc ${Q}unzip -DD -q -d ${TOOLS_DIR}/protoc ${TOOLS_DIR}/protoc.zip -# We're using per-tool go.mod files in order to avoid conflicts in the graph in -# case we used a single go.mod file for all tools. -${TOOLS_DIR}/%/go.mod: | ${TOOLS_DIR} - ${Q}mkdir -p $(dir $@) - ${Q}cd $(dir $@) && go mod init _build - ${TOOLS_DIR}/%: GOBIN = ${TOOLS_DIR} -${TOOLS_DIR}/%: ${TOOLS_DIR}/%.version ${TOOLS_DIR}/.%/go.mod - ${Q}cd ${TOOLS_DIR}/.$* && go get ${TOOL_PACKAGE}@${TOOL_VERSION} +${TOOLS_DIR}/%: ${TOOLS_DIR}/%.version + ${Q}go install ${TOOL_PACKAGE}@${TOOL_VERSION} ${PROTOC_GEN_GITALY}: proto | ${TOOLS_DIR} ${Q}go build -o $@ ${SOURCE_DIR}/proto/go/internal/cmd/protoc-gen-gitaly diff --git a/_support/noticegen/noticegen.go b/_support/noticegen/noticegen.go index 2a43002ad..0d54f221a 100644 --- a/_support/noticegen/noticegen.go +++ b/_support/noticegen/noticegen.go @@ -3,7 +3,6 @@ package main import ( "encoding/json" "flag" - "io/ioutil" "log" "os" "os/exec" @@ -66,7 +65,7 @@ func main() { return nil } - t, err := ioutil.ReadFile(path) + t, err := os.ReadFile(path) if err != nil { log.Fatal(err) } diff --git a/cmd/gitaly-backup/create_test.go b/cmd/gitaly-backup/create_test.go index 68e8dc2bd..bb58c435f 100644 --- a/cmd/gitaly-backup/create_test.go +++ b/cmd/gitaly-backup/create_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "path/filepath" "testing" @@ -59,7 +59,7 @@ func TestCreateSubcommand(t *testing.T) { require.NoError(t, fs.Parse([]string{"-path", path})) require.EqualError(t, - cmd.Run(context.Background(), &stdin, ioutil.Discard), + cmd.Run(context.Background(), &stdin, io.Discard), "create: pipeline: 1 failures encountered") for _, repo := range repos { diff --git a/cmd/gitaly-backup/restore_test.go b/cmd/gitaly-backup/restore_test.go index d5b7be2c3..a5a5e33c4 100644 --- a/cmd/gitaly-backup/restore_test.go +++ b/cmd/gitaly-backup/restore_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "io" "path/filepath" "testing" @@ -66,7 +66,7 @@ func TestRestoreSubcommand(t *testing.T) { require.NoError(t, fs.Parse([]string{"-path", path})) require.EqualError(t, - cmd.Run(context.Background(), &stdin, ioutil.Discard), + cmd.Run(context.Background(), &stdin, io.Discard), "restore: pipeline: 1 failures encountered") for _, repo := range repos { diff --git a/cmd/gitaly-blackbox/main.go b/cmd/gitaly-blackbox/main.go index cd5cc0647..c0d2481ec 100644 --- a/cmd/gitaly-blackbox/main.go +++ b/cmd/gitaly-blackbox/main.go @@ -3,7 +3,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "os" "github.com/prometheus/client_golang/prometheus" @@ -42,7 +41,7 @@ func main() { } func run(configPath string) error { - configRaw, err := ioutil.ReadFile(configPath) + configRaw, err := os.ReadFile(configPath) if err != nil { return err } diff --git a/cmd/gitaly-git2go/apply.go b/cmd/gitaly-git2go/apply.go index d3bcfc597..4c6691218 100644 --- a/cmd/gitaly-git2go/apply.go +++ b/cmd/gitaly-git2go/apply.go @@ -11,7 +11,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -194,7 +193,7 @@ func (cmd *applySubcommand) threeWayMerge( } func (cmd *applySubcommand) buildFakeAncestor(ctx context.Context, repo *git.Repository, diff []byte) (*git.Tree, error) { - dir, err := ioutil.TempDir("", "gitaly-git2go") + dir, err := os.MkdirTemp("", "gitaly-git2go") if err != nil { return nil, fmt.Errorf("create temporary directory: %w", err) } diff --git a/cmd/gitaly-hooks/hooks_test.go b/cmd/gitaly-hooks/hooks_test.go index c71daf429..93d980bdd 100644 --- a/cmd/gitaly-hooks/hooks_test.go +++ b/cmd/gitaly-hooks/hooks_test.go @@ -5,7 +5,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "os" "os/exec" "path" @@ -786,7 +785,7 @@ func writeTemporaryGitalyConfigFile(t testing.TB, tempDir, gitlabURL, user, pass password = %q `, gitlabURL, secretFile, user, password) - require.NoError(t, ioutil.WriteFile(path, []byte(contents), 0o644)) + require.NoError(t, os.WriteFile(path, []byte(contents), 0o644)) return path, func() { require.NoError(t, os.RemoveAll(path)) } diff --git a/cmd/gitaly-wrapper/main.go b/cmd/gitaly-wrapper/main.go index 3ac422070..3fc315b3c 100644 --- a/cmd/gitaly-wrapper/main.go +++ b/cmd/gitaly-wrapper/main.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "io/ioutil" "os" "os/exec" "os/signal" @@ -144,7 +143,7 @@ func forwardSignals(gitaly *os.Process, log *logrus.Entry) { } func getPid() (int, error) { - data, err := ioutil.ReadFile(pidFile()) + data, err := os.ReadFile(pidFile()) if err != nil { return 0, err } diff --git a/cmd/gitaly-wrapper/main_test.go b/cmd/gitaly-wrapper/main_test.go index 50ca5a1bc..8014037bb 100644 --- a/cmd/gitaly-wrapper/main_test.go +++ b/cmd/gitaly-wrapper/main_test.go @@ -2,7 +2,6 @@ package main import ( "errors" - "io/ioutil" "os" "os/exec" "strconv" @@ -19,7 +18,7 @@ func TestStolenPid(t *testing.T) { require.NoError(t, os.Setenv(bootstrap.EnvPidFile, oldValue)) }(os.Getenv(bootstrap.EnvPidFile)) - pidFile, err := ioutil.TempFile("", "pidfile") + pidFile, err := os.CreateTemp("", "pidfile") require.NoError(t, err) defer func() { require.NoError(t, os.Remove(pidFile.Name())) }() @@ -45,4 +45,4 @@ require ( google.golang.org/protobuf v1.26.0 ) -go 1.15 +go 1.16 @@ -241,7 +241,6 @@ github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072/go.mod github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/flosch/pongo2 v0.0.0-20190707114632-bbf5a6c351f4/go.mod h1:T9YF2M40nIgbVgp3rreNmTged+9HrbNTIQf1PsaIiTA= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/form3tech-oss/jwt-go v3.2.2+incompatible h1:TcekIExNqud5crz4xD2pavyTgWiPvpYe4Xau31I0PRk= @@ -250,7 +249,6 @@ github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHqu github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/gavv/httpexpect v2.0.0+incompatible/go.mod h1:x+9tiU1YnrOvnB725RkpoLv1M62hOWzwo5OXotisrKc= github.com/getsentry/raven-go v0.1.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= @@ -674,11 +672,9 @@ github.com/otiai10/copy v1.0.1/go.mod h1:8bMCJrAqOtN/d9oyh5HR7HhLQMvcGMpGdwRDYsf github.com/otiai10/copy v1.4.2 h1:RTiz2sol3eoXPLF4o+YWqEybwfUa/Q2Nkc4ZIUs3fwI= github.com/otiai10/copy v1.4.2/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI= github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= github.com/otiai10/mint v1.2.3/go.mod h1:YnfyPNhBvnY8bW4SGQHCs/aAFhkgySlMZbrF5U0bOVw= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= -github.com/otiai10/mint v1.3.2 h1:VYWnrP5fXmz1MXvjuUvcBrXSjGE6xjON+axB/UrpO3E= github.com/otiai10/mint v1.3.2/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= diff --git a/internal/backchannel/backchannel_test.go b/internal/backchannel/backchannel_test.go index 1191737b5..0fe321a46 100644 --- a/internal/backchannel/backchannel_test.go +++ b/internal/backchannel/backchannel_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net" "sync" "sync/atomic" @@ -33,7 +32,7 @@ func (m mockTransactionServer) VoteTransaction(ctx context.Context, req *gitalyp func newLogger() *logrus.Entry { logger := logrus.New() - logger.Out = ioutil.Discard + logger.Out = io.Discard return logrus.NewEntry(logger) } diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go index 425656435..fd1dd04d8 100644 --- a/internal/backup/backup_test.go +++ b/internal/backup/backup_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -39,7 +38,7 @@ func TestManager_Create(t *testing.T) { RelativePath: "hooks", }) require.NoError(t, os.Mkdir(filepath.Join(hooksRepoPath, "custom_hooks"), os.ModePerm)) - require.NoError(t, ioutil.WriteFile(filepath.Join(hooksRepoPath, "custom_hooks/pre-commit.sample"), []byte("Some hooks"), os.ModePerm)) + require.NoError(t, os.WriteFile(filepath.Join(hooksRepoPath, "custom_hooks/pre-commit.sample"), []byte("Some hooks"), os.ModePerm)) noHooksRepo, _ := gittest.CloneRepo(t, cfg, cfg.Storages[0], gittest.CloneRepoOpts{ RelativePath: "no-hooks", @@ -336,7 +335,7 @@ func TestResolveSink(t *testing.T) { tmpDir := testhelper.TempDir(t) gsCreds := filepath.Join(tmpDir, "gs.creds") - require.NoError(t, ioutil.WriteFile(gsCreds, []byte(` + require.NoError(t, os.WriteFile(gsCreds, []byte(` { "type": "service_account", "project_id": "hostfactory-179005", diff --git a/internal/backup/filesystem_sink_test.go b/internal/backup/filesystem_sink_test.go index feeda5294..f2f257c26 100644 --- a/internal/backup/filesystem_sink_test.go +++ b/internal/backup/filesystem_sink_test.go @@ -2,7 +2,7 @@ package backup import ( "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -19,7 +19,7 @@ func TestFilesystemSink_GetReader(t *testing.T) { dir := testhelper.TempDir(t) const relativePath = "test.dat" - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, relativePath), []byte("test"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, relativePath), []byte("test"), 0o644)) fsSink := NewFilesystemSink(dir) reader, err := fsSink.GetReader(ctx, relativePath) @@ -27,7 +27,7 @@ func TestFilesystemSink_GetReader(t *testing.T) { defer func() { require.NoError(t, reader.Close()) }() - data, err := ioutil.ReadAll(reader) + data, err := io.ReadAll(reader) require.NoError(t, err) require.Equal(t, []byte("test"), data) }) @@ -58,7 +58,7 @@ func TestFilesystemSink_Write(t *testing.T) { require.NoError(t, fsSink.Write(ctx, relativePath, strings.NewReader("test"))) require.FileExists(t, filepath.Join(dir, relativePath)) - data, err := ioutil.ReadFile(filepath.Join(dir, relativePath)) + data, err := os.ReadFile(filepath.Join(dir, relativePath)) require.NoError(t, err) require.Equal(t, []byte("test"), data) }) @@ -85,13 +85,13 @@ func TestFilesystemSink_Write(t *testing.T) { fullPath := filepath.Join(dir, relativePath) require.NoError(t, os.MkdirAll(filepath.Dir(fullPath), 0o755)) - require.NoError(t, ioutil.WriteFile(fullPath, []byte("initial"), 0o655)) + require.NoError(t, os.WriteFile(fullPath, []byte("initial"), 0o655)) fsSink := NewFilesystemSink(dir) require.NoError(t, fsSink.Write(ctx, relativePath, strings.NewReader("test"))) require.FileExists(t, fullPath) - data, err := ioutil.ReadFile(fullPath) + data, err := os.ReadFile(fullPath) require.NoError(t, err) require.Equal(t, []byte("test"), data) }) @@ -102,7 +102,7 @@ func TestFilesystemSink_Write(t *testing.T) { dir := testhelper.TempDir(t) const relativePath = "nested/test.dat" - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "nested"), []byte("lock"), os.ModePerm)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "nested"), []byte("lock"), os.ModePerm)) fsSink := NewFilesystemSink(dir) err := fsSink.Write(ctx, relativePath, strings.NewReader("test")) diff --git a/internal/backup/locator.go b/internal/backup/locator.go index 5e5d4e3f5..6110240b9 100644 --- a/internal/backup/locator.go +++ b/internal/backup/locator.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "path/filepath" "strings" @@ -110,7 +110,7 @@ func (l PointerLocator) findLatestID(ctx context.Context, backupPath string) (st } defer r.Close() - latest, err := ioutil.ReadAll(r) + latest, err := io.ReadAll(r) if err != nil { return "", fmt.Errorf("find latest ID: %w", err) } diff --git a/internal/backup/locator_test.go b/internal/backup/locator_test.go index 64146b35e..f8e97a2e5 100644 --- a/internal/backup/locator_test.go +++ b/internal/backup/locator_test.go @@ -1,7 +1,6 @@ package backup import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -92,7 +91,7 @@ func TestPointerLocator(t *testing.T) { require.ErrorIs(t, err, ErrDoesntExist) require.NoError(t, os.MkdirAll(filepath.Join(backupPath, repo.RelativePath), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(backupPath, repo.RelativePath, "LATEST"), []byte(backupID), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(backupPath, repo.RelativePath, "LATEST"), []byte(backupID), 0o644)) expected := &Full{ BundlePath: filepath.Join(repo.RelativePath, backupID, "full.bundle"), RefPath: filepath.Join(repo.RelativePath, backupID, "full.refs"), @@ -125,7 +124,7 @@ func TestPointerLocator(t *testing.T) { require.Equal(t, expectedFallback, fallbackFull) require.NoError(t, os.MkdirAll(filepath.Join(backupPath, repo.RelativePath), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(backupPath, repo.RelativePath, "LATEST"), []byte(backupID), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(backupPath, repo.RelativePath, "LATEST"), []byte(backupID), 0o644)) expected := &Full{ BundlePath: filepath.Join(repo.RelativePath, backupID, "full.bundle"), RefPath: filepath.Join(repo.RelativePath, backupID, "full.refs"), diff --git a/internal/backup/storage_service_sink_test.go b/internal/backup/storage_service_sink_test.go index 1e7f8a35d..5b740df46 100644 --- a/internal/backup/storage_service_sink_test.go +++ b/internal/backup/storage_service_sink_test.go @@ -3,7 +3,7 @@ package backup import ( "bytes" "fmt" - "io/ioutil" + "io" "testing" "github.com/stretchr/testify/require" @@ -30,7 +30,7 @@ func TestStorageServiceSink(t *testing.T) { require.NoError(t, err) defer func() { require.NoError(t, reader.Close()) }() - retrieved, err := ioutil.ReadAll(reader) + retrieved, err := io.ReadAll(reader) require.NoError(t, err) require.Equal(t, data, retrieved) }) diff --git a/internal/bootstrap/bootstrap_test.go b/internal/bootstrap/bootstrap_test.go index fce265679..8b870395c 100644 --- a/internal/bootstrap/bootstrap_test.go +++ b/internal/bootstrap/bootstrap_test.go @@ -2,8 +2,8 @@ package bootstrap import ( "context" + "errors" "fmt" - "io/ioutil" "net" "net/http" "os" @@ -68,7 +68,7 @@ func TestCreateUnixListener(t *testing.T) { } // simulate a dangling socket - require.NoError(t, ioutil.WriteFile(socketPath, nil, 0o755)) + require.NoError(t, os.WriteFile(socketPath, nil, 0o755)) listen := func(network, addr string) (net.Listener, error) { require.Equal(t, "unix", network) @@ -113,7 +113,7 @@ func TestImmediateTerminationOnSocketError(t *testing.T) { err := waitWithTimeout(t, waitCh, 1*time.Second) require.Error(t, err) - require.Contains(t, err.Error(), "use of closed network connection") + require.True(t, errors.Is(err, net.ErrClosed), "expected closed connection error, got %T: %q", err, err) } func TestImmediateTerminationOnSignal(t *testing.T) { diff --git a/internal/cache/diskcache_test.go b/internal/cache/diskcache_test.go index af858cbc9..04bc54964 100644 --- a/internal/cache/diskcache_test.go +++ b/internal/cache/diskcache_test.go @@ -3,7 +3,6 @@ package cache import ( "context" "io" - "io/ioutil" "strings" "sync" "testing" @@ -49,7 +48,7 @@ func TestStreamDBNaiveKeyer(t *testing.T) { expectGetHit := func(expectStr string, req *gitalypb.InfoRefsRequest) { actualStream, err := cache.GetStream(ctx, req.Repository, req) require.NoError(t, err) - actualBytes, err := ioutil.ReadAll(actualStream) + actualBytes, err := io.ReadAll(actualStream) require.NoError(t, err) require.Equal(t, expectStr, string(actualBytes)) } diff --git a/internal/cache/keyer.go b/internal/cache/keyer.go index dad5df90d..31e810d14 100644 --- a/internal/cache/keyer.go +++ b/internal/cache/keyer.go @@ -1,5 +1,6 @@ package cache +//nolint:depguard import ( "context" "crypto/sha256" @@ -168,7 +169,7 @@ func (keyer leaseKeyer) newPendingLease(repo *gitalypb.Repository) (string, erro return "", err } - f, err := ioutil.TempFile(pDir, "") + f, err := os.CreateTemp(pDir, "") if err != nil { err = fmt.Errorf("creating pending lease failed: %w", err) return "", err @@ -240,7 +241,7 @@ func (keyer leaseKeyer) currentGenID(ctx context.Context, repo *gitalypb.Reposit return "", err } - latestBytes, err := ioutil.ReadFile(latestPath(repoStatePath)) + latestBytes, err := os.ReadFile(latestPath(repoStatePath)) switch { case os.IsNotExist(err): // latest file doesn't exist, so create one diff --git a/internal/cache/walker.go b/internal/cache/walker.go index 41747685c..bfd5fba01 100644 --- a/internal/cache/walker.go +++ b/internal/cache/walker.go @@ -5,6 +5,7 @@ // worker will walk the cache directory every ten minutes. package cache +//nolint:depguard import ( "fmt" "io/ioutil" @@ -65,7 +66,7 @@ func (c *DiskCache) cleanWalk(path string) error { c.walkerRemovalTotal.Inc() } - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { if os.IsNotExist(err) { return nil @@ -133,7 +134,7 @@ func (c *DiskCache) moveAndClear(storage config.Storage) error { return err } - tmpDir, err := ioutil.TempDir(tempPath, "diskcache") + tmpDir, err := os.MkdirTemp(tempPath, "diskcache") if err != nil { return err } diff --git a/internal/cache/walker_test.go b/internal/cache/walker_test.go index 823e1edb2..87e02d8fa 100644 --- a/internal/cache/walker_test.go +++ b/internal/cache/walker_test.go @@ -1,7 +1,6 @@ package cache import ( - "io/ioutil" "os" "os/exec" "path/filepath" @@ -75,7 +74,7 @@ func TestDiskCacheInitialClear(t *testing.T) { canary := filepath.Join(cacheDir, "canary.txt") require.NoError(t, os.MkdirAll(filepath.Dir(canary), 0o755)) - require.NoError(t, ioutil.WriteFile(canary, []byte("chirp chirp"), 0o755)) + require.NoError(t, os.WriteFile(canary, []byte("chirp chirp"), 0o755)) cache := New(cfg, locator, withDisabledWalker()) require.NoError(t, cache.StartWalkers()) @@ -132,7 +131,7 @@ func TestCleanWalkEmptyDirs(t *testing.T) { if strings.HasSuffix(tt.path, "/") { require.NoError(t, os.MkdirAll(p, 0o755)) } else { - require.NoError(t, ioutil.WriteFile(p, nil, 0o655)) + require.NoError(t, os.WriteFile(p, nil, 0o655)) if tt.stale { require.NoError(t, os.Chtimes(p, time.Now(), time.Now().Add(-time.Hour))) } diff --git a/internal/command/command.go b/internal/command/command.go index f8f7e9a0a..d1db84cd1 100644 --- a/internal/command/command.go +++ b/internal/command/command.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "os/exec" "strings" @@ -269,7 +268,7 @@ func (c *Command) wait() { if c.reader != nil { // Prevent the command from blocking on writing to its stdout. - _, _ = io.Copy(ioutil.Discard, c.reader) + _, _ = io.Copy(io.Discard, c.reader) } c.waitError = c.cmd.Wait() diff --git a/internal/git/catfile/batch_cache_test.go b/internal/git/catfile/batch_cache_test.go index 45fbe4c80..9816c0d7d 100644 --- a/internal/git/catfile/batch_cache_test.go +++ b/internal/git/catfile/batch_cache_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "io" - "io/ioutil" "os" "sync" "testing" @@ -218,7 +217,7 @@ func TestCache_BatchProcess(t *testing.T) { // batch processes and trying to read from their stdout. If the cancel did kill the // process as expected, then the stdout should be closed and we'll get an EOF. for _, reader := range []io.Reader{batch.objectInfoReader.cmd, batch.objectReader.cmd} { - output, err := ioutil.ReadAll(reader) + output, err := io.ReadAll(reader) if err != nil { require.True(t, errors.Is(err, os.ErrClosed)) } else { diff --git a/internal/git/catfile/batch_test.go b/internal/git/catfile/batch_test.go index acc4fd3f6..95e62cb96 100644 --- a/internal/git/catfile/batch_test.go +++ b/internal/git/catfile/batch_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "os/exec" "strconv" @@ -123,7 +122,7 @@ func TestBlob(t *testing.T) { require.NoError(t, err) require.Equal(t, tc.objInfo, blobObj.ObjectInfo) - contents, err := ioutil.ReadAll(blobObj.Reader) + contents, err := io.ReadAll(blobObj.Reader) require.NoError(t, err) require.Equal(t, tc.content, contents) }) @@ -155,7 +154,7 @@ func TestCommit(t *testing.T) { commitReader, err := c.Commit(ctx, git.Revision(tc.revision)) require.NoError(t, err) - contents, err := ioutil.ReadAll(commitReader) + contents, err := io.ReadAll(commitReader) require.NoError(t, err) require.Equal(t, tc.output, string(contents)) @@ -218,7 +217,7 @@ func TestTag(t *testing.T) { require.NoError(t, err) require.Equal(t, tc.objInfo, tagObj.ObjectInfo) - contents, err := ioutil.ReadAll(tagObj.Reader) + contents, err := io.ReadAll(tagObj.Reader) require.NoError(t, err) require.Equal(t, tc.content, contents) }) @@ -280,7 +279,7 @@ func TestTree(t *testing.T) { require.NoError(t, err) require.Equal(t, tc.objInfo, treeObj.ObjectInfo) - contents, err := ioutil.ReadAll(treeObj.Reader) + contents, err := io.ReadAll(treeObj.Reader) require.NoError(t, err) require.Equal(t, tc.content, contents) }) @@ -299,7 +298,7 @@ func TestRepeatedCalls(t *testing.T) { tree1Obj, err := c.Tree(ctx, treeOid) require.NoError(t, err) - tree1, err := ioutil.ReadAll(tree1Obj.Reader) + tree1, err := io.ReadAll(tree1Obj.Reader) require.NoError(t, err) require.Equal(t, string(treeBytes), string(tree1)) @@ -310,19 +309,19 @@ func TestRepeatedCalls(t *testing.T) { _, err = c.Tree(ctx, treeOid) require.Error(t, err, "request should fail because of unconsumed blob data") - _, err = io.CopyN(ioutil.Discard, blobReader, 10) + _, err = io.CopyN(io.Discard, blobReader, 10) require.NoError(t, err) _, err = c.Tree(ctx, treeOid) require.Error(t, err, "request should fail because of unconsumed blob data") - _, err = io.Copy(ioutil.Discard, blobReader) + _, err = io.Copy(io.Discard, blobReader) require.NoError(t, err, "blob reading should still work") tree2Obj, err := c.Tree(ctx, treeOid) require.NoError(t, err) - tree2, err := ioutil.ReadAll(tree2Obj.Reader) + tree2, err := io.ReadAll(tree2Obj.Reader) require.NoError(t, err, "request should succeed because blob was consumed") require.Equal(t, string(treeBytes), string(tree2)) diff --git a/internal/git/catfile/commit.go b/internal/git/catfile/commit.go index 32ff48706..3bf3f87c6 100644 --- a/internal/git/catfile/commit.go +++ b/internal/git/catfile/commit.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "strconv" "strings" @@ -80,7 +79,7 @@ func GetCommitMessage(ctx context.Context, c Batch, repo repository.GitRepo, rev } func splitRawCommit(r io.Reader) ([]byte, []byte, error) { - raw, err := ioutil.ReadAll(r) + raw, err := io.ReadAll(r) if err != nil { return nil, nil, err } @@ -143,7 +142,7 @@ func ParseCommit(r io.Reader, oid git.ObjectID) (*gitalypb.GitCommit, error) { } } - body, err := ioutil.ReadAll(b) + body, err := io.ReadAll(b) if err != nil { return nil, fmt.Errorf("parse raw commit: body: %w", err) } diff --git a/internal/git/catfile/object_reader.go b/internal/git/catfile/object_reader.go index 24f74da1f..4d272d041 100644 --- a/internal/git/catfile/object_reader.go +++ b/internal/git/catfile/object_reader.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "sync" "github.com/opentracing/opentracing-go" @@ -129,7 +128,7 @@ func (o *objectReader) reader( if oi.Type != expectedType { // This is a programmer error and it should never happen. But if it does, // we need to leave the cat-file process in a good state - if _, err := io.CopyN(ioutil.Discard, o.stdout, o.n); err != nil { + if _, err := io.CopyN(io.Discard, o.stdout, o.n); err != nil { return nil, err } o.n = 0 diff --git a/internal/git/catfile/object_reader_test.go b/internal/git/catfile/object_reader_test.go index b940f7f2c..50f07c4e2 100644 --- a/internal/git/catfile/object_reader_test.go +++ b/internal/git/catfile/object_reader_test.go @@ -3,7 +3,6 @@ package catfile import ( "fmt" "io" - "io/ioutil" "testing" "github.com/prometheus/client_golang/prometheus" @@ -33,7 +32,7 @@ func TestObjectReader_reader(t *testing.T) { object, err := reader.reader(ctx, "refs/heads/master", "commit") require.NoError(t, err) - data, err := ioutil.ReadAll(object) + data, err := io.ReadAll(object) require.NoError(t, err) require.Equal(t, commitContents, data) }) @@ -45,7 +44,7 @@ func TestObjectReader_reader(t *testing.T) { object, err := reader.reader(ctx, commitID.Revision(), "commit") require.NoError(t, err) - data, err := ioutil.ReadAll(object) + data, err := io.ReadAll(object) require.NoError(t, err) require.Contains(t, string(data), "Merge branch 'cherry-pick-ce369011' into 'master'\n") @@ -62,7 +61,7 @@ func TestObjectReader_reader(t *testing.T) { object, err := reader.reader(ctx, commitID.Revision(), "commit") require.NoError(t, err) - data, err := ioutil.ReadAll(object) + data, err := io.ReadAll(object) require.NoError(t, err) require.Equal(t, commitContents, data) @@ -79,7 +78,7 @@ func TestObjectReader_reader(t *testing.T) { object, err := reader.reader(ctx, commitID.Revision(), "commit") require.NoError(t, err) - data, err := ioutil.ReadAll(object) + data, err := io.ReadAll(object) require.NoError(t, err) require.Equal(t, commitContents, data) @@ -104,7 +103,7 @@ func TestObjectReader_reader(t *testing.T) { object, err := reader.reader(ctx, commitID.Revision(), "commit") require.NoError(t, err) - _, err = io.CopyN(ioutil.Discard, object, 100) + _, err = io.CopyN(io.Discard, object, 100) require.NoError(t, err) // We haven't yet consumed the previous object, so this must now fail. @@ -131,7 +130,7 @@ func TestObjectReader_reader(t *testing.T) { require.Equal(t, float64(1), testutil.ToFloat64(counter.WithLabelValues(objectType))) - _, err = io.Copy(ioutil.Discard, object) + _, err = io.Copy(io.Discard, object) require.NoError(t, err) } }) diff --git a/internal/git/catfile/tag.go b/internal/git/catfile/tag.go index b0ac68d51..74826650a 100644 --- a/internal/git/catfile/tag.go +++ b/internal/git/catfile/tag.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "strings" "gitlab.com/gitlab-org/gitaly/v14/internal/git" @@ -59,7 +58,7 @@ type tagHeader struct { } func splitRawTag(r io.Reader, trimRightNewLine bool) (*tagHeader, []byte, error) { - raw, err := ioutil.ReadAll(r) + raw, err := io.ReadAll(r) if err != nil { return nil, nil, err } diff --git a/internal/git/command_factory_test.go b/internal/git/command_factory_test.go index 566dbe6a1..6b3157791 100644 --- a/internal/git/command_factory_test.go +++ b/internal/git/command_factory_test.go @@ -2,7 +2,7 @@ package git_test import ( "bytes" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -77,7 +77,7 @@ func TestExecCommandFactory_NewWithDir(t *testing.T) { }, git.WithStderr(&stderr)) require.NoError(t, err) - revData, err := ioutil.ReadAll(cmd) + revData, err := io.ReadAll(cmd) require.NoError(t, err) require.NoError(t, cmd.Wait(), stderr.String()) diff --git a/internal/git/dirs.go b/internal/git/dirs.go index 0a192ae3b..16444ed5a 100644 --- a/internal/git/dirs.go +++ b/internal/git/dirs.go @@ -3,7 +3,6 @@ package git import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -65,7 +64,7 @@ func altObjectDirs(ctx context.Context, storagePrefix, objDir string, depth int) dirs := []string{objDir} - alternates, err := ioutil.ReadFile(filepath.Join(objDir, "info", "alternates")) + alternates, err := os.ReadFile(filepath.Join(objDir, "info", "alternates")) if os.IsNotExist(err) { return dirs, nil } diff --git a/internal/git/dirs_test.go b/internal/git/dirs_test.go index 14599a89b..05d0f04e7 100644 --- a/internal/git/dirs_test.go +++ b/internal/git/dirs_test.go @@ -1,7 +1,6 @@ package git import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -76,7 +75,7 @@ func TestObjectDirsOutsideStorage(t *testing.T) { ctx, cancel := testhelper.Context() defer cancel() - require.NoError(t, ioutil.WriteFile(alternatesFile, []byte(tc.alternates), 0o600)) + require.NoError(t, os.WriteFile(alternatesFile, []byte(tc.alternates), 0o600)) out, err := ObjectDirectories(ctx, storageRoot, repoPath) require.Equal(t, expectedErr, err) require.Nil(t, out) diff --git a/internal/git/gitio/hashfile_test.go b/internal/git/gitio/hashfile_test.go index a7a317b91..a18dea7f8 100644 --- a/internal/git/gitio/hashfile_test.go +++ b/internal/git/gitio/hashfile_test.go @@ -1,7 +1,7 @@ package gitio import ( - "io/ioutil" + "io" "strings" "testing" @@ -42,7 +42,7 @@ func TestHashfileReader(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { r := NewHashfileReader(strings.NewReader(tc.in)) - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) if tc.fail { require.Error(t, err, "invalid input should cause error") return diff --git a/internal/git/gitio/trailer_test.go b/internal/git/gitio/trailer_test.go index d01a97119..a8731e331 100644 --- a/internal/git/gitio/trailer_test.go +++ b/internal/git/gitio/trailer_test.go @@ -1,7 +1,7 @@ package gitio import ( - "io/ioutil" + "io" "strings" "testing" @@ -42,7 +42,7 @@ func TestTrailerReaderSuccess(t *testing.T) { tr := NewTrailerReader(strings.NewReader(tc.in), trailerLen) require.Len(t, tc.trailer, trailerLen, "test case trailer sanity check") - out, err := ioutil.ReadAll(tr) + out, err := io.ReadAll(tr) require.NoError(t, err, "read all") require.Equal(t, tc.out, string(out), "compare output") @@ -63,7 +63,7 @@ func TestTrailerReaderFail(t *testing.T) { _, err := tr.Trailer() require.Error(t, err, "Trailer() should fail when called too early") - out, err := ioutil.ReadAll(tr) + out, err := io.ReadAll(tr) require.NoError(t, err, "read") require.Empty(t, out, "read output") diff --git a/internal/git/gitpipe/catfile_object_test.go b/internal/git/gitpipe/catfile_object_test.go index 4c8d4685e..dbf9eafef 100644 --- a/internal/git/gitpipe/catfile_object_test.go +++ b/internal/git/gitpipe/catfile_object_test.go @@ -2,7 +2,7 @@ package gitpipe import ( "errors" - "io/ioutil" + "io" "testing" "github.com/stretchr/testify/require" @@ -107,7 +107,7 @@ func TestCatfileObject(t *testing.T) { // this: it would just be too annoying. require.NotNil(t, result.ObjectReader) - objectData, err := ioutil.ReadAll(result.ObjectReader) + objectData, err := io.ReadAll(result.ObjectReader) require.NoError(t, err) require.Len(t, objectData, int(result.ObjectInfo.Size)) diff --git a/internal/git/gitpipe/pipeline_test.go b/internal/git/gitpipe/pipeline_test.go index 180cc4cb0..6ec16e2a4 100644 --- a/internal/git/gitpipe/pipeline_test.go +++ b/internal/git/gitpipe/pipeline_test.go @@ -3,7 +3,6 @@ package gitpipe import ( "errors" "io" - "io/ioutil" "sync" "testing" @@ -232,7 +231,7 @@ func TestPipeline_revlist(t *testing.T) { // this: it would just be too annoying. require.NotNil(t, result.ObjectReader) - objectData, err := ioutil.ReadAll(result.ObjectReader) + objectData, err := io.ReadAll(result.ObjectReader) require.NoError(t, err) require.Len(t, objectData, int(result.ObjectInfo.Size)) @@ -273,7 +272,7 @@ func TestPipeline_revlist(t *testing.T) { for catfileObjectIter.Next() { i++ - _, err := io.Copy(ioutil.Discard, catfileObjectIter.Result().ObjectReader) + _, err := io.Copy(io.Discard, catfileObjectIter.Result().ObjectReader) require.NoError(t, err) if i == 3 { @@ -317,7 +316,7 @@ func TestPipeline_revlist(t *testing.T) { // the object reader. go func(object CatfileObjectResult) { defer wg.Done() - _, err := io.Copy(ioutil.Discard, object.ObjectReader) + _, err := io.Copy(io.Discard, object.ObjectReader) require.NoError(t, err) }(catfileObjectIter.Result()) } @@ -363,7 +362,7 @@ func TestPipeline_forEachRef(t *testing.T) { // this: it would just be too annoying. require.NotNil(t, result.ObjectReader) - objectData, err := ioutil.ReadAll(result.ObjectReader) + objectData, err := io.ReadAll(result.ObjectReader) require.NoError(t, err) require.Len(t, objectData, int(result.ObjectInfo.Size)) diff --git a/internal/git/gittest/delta_islands.go b/internal/git/gittest/delta_islands.go index 4bd7538b3..c278f0163 100644 --- a/internal/git/gittest/delta_islands.go +++ b/internal/git/gittest/delta_islands.go @@ -3,7 +3,6 @@ package gittest import ( "crypto/rand" "io" - "io/ioutil" "strings" "testing" @@ -17,7 +16,7 @@ import ( // https://github.com/git/git/blob/master/t/t5320-delta-islands.sh . func TestDeltaIslands(t *testing.T, cfg config.Cfg, repoPath string, repack func() error) { // Create blobs that we expect Git to use delta compression on. - blob1, err := ioutil.ReadAll(io.LimitReader(rand.Reader, 100000)) + blob1, err := io.ReadAll(io.LimitReader(rand.Reader, 100000)) require.NoError(t, err) blob2 := append(blob1, "\nblob 2"...) diff --git a/internal/git/gittest/hooks.go b/internal/git/gittest/hooks.go index 2df6450c0..e2867648a 100644 --- a/internal/git/gittest/hooks.go +++ b/internal/git/gittest/hooks.go @@ -2,7 +2,6 @@ package gittest import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -61,7 +60,7 @@ func CaptureHookEnv(t testing.TB) (string, func()) { #!/bin/sh env | grep -e ^GIT -e ^GL_ > ` + hookOutputFile + "\n") - require.NoError(t, ioutil.WriteFile(filepath.Join(hooks.Override, "update"), script, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(hooks.Override, "update"), script, 0o755)) return hookOutputFile, func() { hooks.Override = oldOverride diff --git a/internal/git/gittest/http_server.go b/internal/git/gittest/http_server.go index 11bf4cf4b..bb09276b2 100644 --- a/internal/git/gittest/http_server.go +++ b/internal/git/gittest/http_server.go @@ -4,11 +4,11 @@ import ( "compress/gzip" "context" "fmt" - "io/ioutil" "net" "net/http" "net/http/cgi" "net/http/httptest" + "os" "os/exec" "path/filepath" "testing" @@ -67,7 +67,7 @@ func RemoteUploadPackServer(ctx context.Context, t *testing.T, gitPath, repoName // repository is prepared such that git-http-backend(1) will serve it by // creating the "git-daemon-export-ok" magic file. func GitServer(t testing.TB, cfg config.Cfg, repoPath string, middleware func(http.ResponseWriter, *http.Request, http.Handler)) (int, func() error) { - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, "git-daemon-export-ok"), nil, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, "git-daemon-export-ok"), nil, 0o644)) listener, err := net.Listen("tcp", "127.0.0.1:0") require.NoError(t, err) diff --git a/internal/git/gittest/protocol.go b/internal/git/gittest/protocol.go index eb30bba6d..64b374b17 100644 --- a/internal/git/gittest/protocol.go +++ b/internal/git/gittest/protocol.go @@ -2,7 +2,7 @@ package gittest import ( "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ exec "%s" "$@" cfg.Git.BinPath = gitPath return func() string { - data, err := ioutil.ReadFile(envPath) + data, err := os.ReadFile(envPath) require.NoError(t, err) return string(data) }, cfg diff --git a/internal/git/housekeeping/housekeeping.go b/internal/git/housekeeping/housekeeping.go index b9d3fbe42..2a15d5c30 100644 --- a/internal/git/housekeeping/housekeeping.go +++ b/internal/git/housekeeping/housekeeping.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -321,7 +320,7 @@ func removeRefEmptyDirs(ctx context.Context, repository *localrepo.Repo) error { // we never want to delete the actual "refs" directory, so we start the // recursive functions for each subdirectory - entries, err := ioutil.ReadDir(repoRefsPath) + entries, err := os.ReadDir(repoRefsPath) if err != nil { return err } @@ -356,7 +355,7 @@ func removeEmptyDirs(ctx context.Context, target string) error { return err } - entries, err := ioutil.ReadDir(target) + entries, err := os.ReadDir(target) switch { case os.IsNotExist(err): return nil // race condition: someone else deleted it first @@ -382,7 +381,7 @@ func removeEmptyDirs(ctx context.Context, target string) error { } // recheck entries now that we have potentially removed some dirs - entries, err = ioutil.ReadDir(target) + entries, err = os.ReadDir(target) if err != nil && !os.IsNotExist(err) { return err } diff --git a/internal/git/housekeeping/housekeeping_test.go b/internal/git/housekeeping/housekeeping_test.go index 7c871affb..09b46599d 100644 --- a/internal/git/housekeeping/housekeeping_test.go +++ b/internal/git/housekeeping/housekeeping_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -303,7 +302,7 @@ func TestPerform_references(t *testing.T) { path := filepath.Join(repoPath, ref.name) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - require.NoError(t, ioutil.WriteFile(path, bytes.Repeat([]byte{0}, ref.size), 0o644)) + require.NoError(t, os.WriteFile(path, bytes.Repeat([]byte{0}, ref.size), 0o644)) filetime := time.Now().Add(-ref.age) require.NoError(t, os.Chtimes(path, filetime, filetime)) } diff --git a/internal/git/localrepo/objects_test.go b/internal/git/localrepo/objects_test.go index c6410f6d5..d1d797955 100644 --- a/internal/git/localrepo/objects_test.go +++ b/internal/git/localrepo/objects_test.go @@ -3,7 +3,6 @@ package localrepo import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -91,7 +90,7 @@ func TestRepo_WriteBlob(t *testing.T) { } { t.Run(tc.desc, func(t *testing.T) { require.NoError(t, - ioutil.WriteFile(filepath.Join(repoPath, "info", "attributes"), []byte(tc.attributes), os.ModePerm), + os.WriteFile(filepath.Join(repoPath, "info", "attributes"), []byte(tc.attributes), os.ModePerm), ) sha, err := repo.WriteBlob(ctx, "file-path", tc.input) diff --git a/internal/git/localrepo/refs.go b/internal/git/localrepo/refs.go index 0ebe4aa91..0ac4bf969 100644 --- a/internal/git/localrepo/refs.go +++ b/internal/git/localrepo/refs.go @@ -6,7 +6,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "strings" "gitlab.com/gitlab-org/gitaly/v14/internal/command" @@ -43,7 +43,7 @@ func (repo *Repo) ResolveRevision(ctx context.Context, revision git.Revision) (g Flags: []git.Option{git.Flag{Name: "--verify"}}, Args: []string{revision.String()}, }, - git.WithStderr(ioutil.Discard), + git.WithStderr(io.Discard), git.WithStdout(&stdout), ); err != nil { if _, ok := command.ExitStatus(err); ok { diff --git a/internal/git/localrepo/refs_test.go b/internal/git/localrepo/refs_test.go index ebfde348d..069073e47 100644 --- a/internal/git/localrepo/refs_test.go +++ b/internal/git/localrepo/refs_test.go @@ -1,7 +1,6 @@ package localrepo import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -319,7 +318,7 @@ func TestRepo_GetRemoteReferences(t *testing.T) { require.NoError(t, err) require.Equal(t, tc.expected, refs) - gitSSHCommand, err := ioutil.ReadFile(gitSSHCommandFile) + gitSSHCommand, err := os.ReadFile(gitSSHCommandFile) if !os.IsNotExist(err) { require.NoError(t, err) } diff --git a/internal/git/localrepo/remote_test.go b/internal/git/localrepo/remote_test.go index 38d4f5879..4f1a8276a 100644 --- a/internal/git/localrepo/remote_test.go +++ b/internal/git/localrepo/remote_test.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -449,7 +448,7 @@ func captureGitSSHCommand(t testing.TB, gitBinaryPath string) (string, string) { gitPath := filepath.Join(tmpDir, "git-hook") envPath := filepath.Join(tmpDir, "GIT_SSH_PATH") - require.NoError(t, ioutil.WriteFile( + require.NoError(t, os.WriteFile( gitPath, []byte(fmt.Sprintf( `#!/usr/bin/env bash @@ -587,7 +586,7 @@ func TestRepo_Push(t *testing.T) { } require.NoError(t, err) - gitSSHCommand, err := ioutil.ReadFile(gitSSHCommandFile) + gitSSHCommand, err := os.ReadFile(gitSSHCommandFile) if !os.IsNotExist(err) { require.NoError(t, err) } diff --git a/internal/git/log/last_commit.go b/internal/git/log/last_commit.go index 6690dbc21..118742bbe 100644 --- a/internal/git/log/last_commit.go +++ b/internal/git/log/last_commit.go @@ -2,7 +2,7 @@ package log import ( "context" - "io/ioutil" + "io" "gitlab.com/gitlab-org/gitaly/v14/internal/command" "gitlab.com/gitlab-org/gitaly/v14/internal/git" @@ -24,7 +24,7 @@ func LastCommitForPath(ctx context.Context, gitCmdFactory git.CommandFactory, ba return nil, err } - commitID, err := ioutil.ReadAll(cmd) + commitID, err := io.ReadAll(cmd) if err != nil { return nil, err } diff --git a/internal/git/objectpool/fetch.go b/internal/git/objectpool/fetch.go index 5a6e76859..45fc92de3 100644 --- a/internal/git/objectpool/fetch.go +++ b/internal/git/objectpool/fetch.go @@ -5,7 +5,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "os/exec" "path/filepath" "strconv" @@ -238,7 +238,7 @@ func sizeDir(ctx context.Context, dir string) (int64, error) { return 0, err } - sizeLine, err := ioutil.ReadAll(cmd) + sizeLine, err := io.ReadAll(cmd) if err != nil { return 0, err } diff --git a/internal/git/objectpool/fetch_test.go b/internal/git/objectpool/fetch_test.go index d0dbb2fb7..fd7b11502 100644 --- a/internal/git/objectpool/fetch_test.go +++ b/internal/git/objectpool/fetch_test.go @@ -2,7 +2,7 @@ package objectpool import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -138,7 +138,7 @@ func TestFetchFromOriginBitmapHashCache(t *testing.T) { require.NoError(t, pool.FetchFromOrigin(ctx, testRepo), "seed pool") packDir := filepath.Join(pool.FullPath(), "objects/pack") - packEntries, err := ioutil.ReadDir(packDir) + packEntries, err := os.ReadDir(packDir) require.NoError(t, err) var bitmap string diff --git a/internal/git/objectpool/link.go b/internal/git/objectpool/link.go index 816f673d4..710fbd11c 100644 --- a/internal/git/objectpool/link.go +++ b/internal/git/objectpool/link.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -60,7 +59,7 @@ func (o *ObjectPool) Link(ctx context.Context, repo *gitalypb.Repository) (retur return fmt.Errorf("committing alternates: %w", err) } } else { - tmp, err := ioutil.TempFile(filepath.Dir(altPath), "alternates") + tmp, err := os.CreateTemp(filepath.Dir(altPath), "alternates") if err != nil { return err } @@ -134,7 +133,7 @@ func (o *ObjectPool) removeMemberBitmaps(repo repository.GitRepo) error { func getBitmaps(repoPath string) ([]string, error) { packDir := filepath.Join(repoPath, "objects/pack") - entries, err := ioutil.ReadDir(packDir) + entries, err := os.ReadDir(packDir) if err != nil { return nil, err } diff --git a/internal/git/objectpool/link_test.go b/internal/git/objectpool/link_test.go index 97a7d5d6d..c49cdc3cc 100644 --- a/internal/git/objectpool/link_test.go +++ b/internal/git/objectpool/link_test.go @@ -2,7 +2,7 @@ package objectpool import ( "context" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -115,7 +115,7 @@ func TestLinkRemoveBitmap(t *testing.T) { } func listBitmaps(t *testing.T, repoPath string) []string { - entries, err := ioutil.ReadDir(filepath.Join(repoPath, "objects/pack")) + entries, err := os.ReadDir(filepath.Join(repoPath, "objects/pack")) require.NoError(t, err) var bitmaps []string @@ -161,7 +161,7 @@ func TestLinkAbsoluteLinkExists(t *testing.T) { fullPath := filepath.Join(pool.FullPath(), "objects") - require.NoError(t, ioutil.WriteFile(altPath, []byte(fullPath), 0o644)) + require.NoError(t, os.WriteFile(altPath, []byte(fullPath), 0o644)) require.NoError(t, pool.Link(ctx, testRepo), "we expect this call to change the absolute link to a relative link") diff --git a/internal/git/objectpool/pool_test.go b/internal/git/objectpool/pool_test.go index 68729ff1b..94756ee0c 100644 --- a/internal/git/objectpool/pool_test.go +++ b/internal/git/objectpool/pool_test.go @@ -1,7 +1,6 @@ package objectpool import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -80,7 +79,7 @@ func TestNewFromRepoNoObjectPool(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { alternateFilePath := filepath.Join(testRepoPath, "objects", "info", "alternates") - require.NoError(t, ioutil.WriteFile(alternateFilePath, tc.fileContent, 0o644)) + require.NoError(t, os.WriteFile(alternateFilePath, tc.fileContent, 0o644)) poolFromRepo, err := FromRepo(pool.cfg, pool.locator, pool.gitCmdFactory, nil, nil, testRepo) require.Equal(t, tc.expectedErr, err) require.Nil(t, poolFromRepo) diff --git a/internal/git/packfile/packfile.go b/internal/git/packfile/packfile.go index 63716a18c..67015aa20 100644 --- a/internal/git/packfile/packfile.go +++ b/internal/git/packfile/packfile.go @@ -1,14 +1,14 @@ package packfile import ( - "io/ioutil" + "os" "path/filepath" ) // List returns the packfiles in objDir. func List(objDir string) ([]string, error) { packDir := filepath.Join(objDir, "pack") - entries, err := ioutil.ReadDir(packDir) + entries, err := os.ReadDir(packDir) if err != nil { return nil, err } diff --git a/internal/git/pktline/read_monitor.go b/internal/git/pktline/read_monitor.go index 4f74fda05..1c2f6d354 100644 --- a/internal/git/pktline/read_monitor.go +++ b/internal/git/pktline/read_monitor.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "os" "time" ) @@ -77,6 +76,6 @@ func (m *ReadMonitor) Monitor(pkt []byte, timeout time.Duration, cancelFn func() } // Complete the read loop, then signal completion on pr by closing pw - _, _ = io.Copy(ioutil.Discard, teeReader) + _, _ = io.Copy(io.Discard, teeReader) _ = m.pw.Close() } diff --git a/internal/git/pktline/read_monitor_test.go b/internal/git/pktline/read_monitor_test.go index 5558dd5e5..e34cc2e6a 100644 --- a/internal/git/pktline/read_monitor_test.go +++ b/internal/git/pktline/read_monitor_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "os" "strings" "testing" @@ -41,7 +40,7 @@ func TestReadMonitorTimeout(t *testing.T) { require.True(t, elapsed < time.Second, "Expected context to be cancelled quickly, but it was not") // Verify that pipe is closed - _, err = ioutil.ReadAll(r) + _, err = io.ReadAll(r) require.Error(t, err) require.IsType(t, &os.PathError{}, err) } diff --git a/internal/git/quarantine/quarantine.go b/internal/git/quarantine/quarantine.go index 38cef7e9d..7638a606e 100644 --- a/internal/git/quarantine/quarantine.go +++ b/internal/git/quarantine/quarantine.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -87,7 +86,7 @@ func (d *Dir) Migrate() error { } func migrate(sourcePath, targetPath string) error { - entries, err := ioutil.ReadDir(sourcePath) + entries, err := os.ReadDir(sourcePath) if err != nil { return fmt.Errorf("reading directory: %w", err) } @@ -157,7 +156,7 @@ func finalizeObjectFile(sourcePath, targetPath string) error { // sortEntries sorts packfiles and their associated metafiles such that we copy them over in the // correct order. -func sortEntries(entries []os.FileInfo) { +func sortEntries(entries []os.DirEntry) { sort.SliceStable(entries, func(i, j int) bool { return packCopyPriority(entries[i].Name()) < packCopyPriority(entries[j].Name()) }) diff --git a/internal/git/quarantine/quarantine_test.go b/internal/git/quarantine/quarantine_test.go index f12f92bc6..cf6403390 100644 --- a/internal/git/quarantine/quarantine_test.go +++ b/internal/git/quarantine/quarantine_test.go @@ -1,7 +1,6 @@ package quarantine import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -33,7 +32,7 @@ func (e entry) create(t *testing.T, root string) { child.create(t, filepath.Join(root, name)) } } else { - require.NoError(t, ioutil.WriteFile(root, []byte(e.contents), 0o666)) + require.NoError(t, os.WriteFile(root, []byte(e.contents), 0o666)) } } @@ -113,7 +112,7 @@ func TestQuarantine_Migrate(t *testing.T) { quarantine, err := New(ctx, repo, locator) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(filepath.Join(quarantine.dir.Path(), "file"), []byte("foobar"), 0o666)) + require.NoError(t, os.WriteFile(filepath.Join(quarantine.dir.Path(), "file"), []byte("foobar"), 0o666)) require.NoError(t, quarantine.Migrate()) newContents := listEntries(t, repoPath) @@ -323,7 +322,7 @@ func TestFinalizeObjectFile(t *testing.T) { source := filepath.Join(dir, "a") target := filepath.Join(dir, "b") - require.NoError(t, ioutil.WriteFile(source, []byte("a"), 0o777)) + require.NoError(t, os.WriteFile(source, []byte("a"), 0o777)) require.NoError(t, finalizeObjectFile(source, target)) require.NoFileExists(t, source) @@ -336,7 +335,7 @@ func TestFinalizeObjectFile(t *testing.T) { source := filepath.Join(sourceDir, "a") target := filepath.Join(targetDir, "a") - require.NoError(t, ioutil.WriteFile(source, []byte("a"), 0o777)) + require.NoError(t, os.WriteFile(source, []byte("a"), 0o777)) require.NoError(t, finalizeObjectFile(source, target)) require.NoFileExists(t, source) @@ -347,10 +346,10 @@ func TestFinalizeObjectFile(t *testing.T) { dir := testhelper.TempDir(t) source := filepath.Join(dir, "a") - require.NoError(t, ioutil.WriteFile(source, []byte("a"), 0o777)) + require.NoError(t, os.WriteFile(source, []byte("a"), 0o777)) target := filepath.Join(dir, "b") - require.NoError(t, ioutil.WriteFile(target, []byte("b"), 0o777)) + require.NoError(t, os.WriteFile(target, []byte("b"), 0o777)) // We do not expect an error in case the target file exists: given that objects and // packs are content addressable, a file with the same name should have the same @@ -373,12 +372,12 @@ func TestFinalizeObjectFile(t *testing.T) { }) } -type mockFileInfo struct { - os.FileInfo +type mockDirEntry struct { + os.DirEntry name string } -func (e mockFileInfo) Name() string { +func (e mockDirEntry) Name() string { return e.name } @@ -487,14 +486,14 @@ func TestSortEntries(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - var actualEntries []os.FileInfo + var actualEntries []os.DirEntry for _, entry := range tc.entries { - actualEntries = append(actualEntries, mockFileInfo{name: entry}) + actualEntries = append(actualEntries, mockDirEntry{name: entry}) } - var expectedEntries []os.FileInfo + var expectedEntries []os.DirEntry for _, entry := range tc.expected { - expectedEntries = append(expectedEntries, mockFileInfo{name: entry}) + expectedEntries = append(expectedEntries, mockDirEntry{name: entry}) } sortEntries(actualEntries) diff --git a/internal/git/ssh.go b/internal/git/ssh.go index aff64488f..be411576f 100644 --- a/internal/git/ssh.go +++ b/internal/git/ssh.go @@ -3,7 +3,6 @@ package git import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -19,7 +18,7 @@ func BuildSSHInvocation(ctx context.Context, sshKey, knownHosts string) (string, return sshCommand, func() {}, nil } - tmpDir, err := ioutil.TempDir("", "gitaly-ssh-invocation") + tmpDir, err := os.MkdirTemp("", "gitaly-ssh-invocation") if err != nil { return "", func() {}, fmt.Errorf("create temporary directory: %w", err) } @@ -33,7 +32,7 @@ func BuildSSHInvocation(ctx context.Context, sshKey, knownHosts string) (string, args := []string{sshCommand} if sshKey != "" { sshKeyFile := filepath.Join(tmpDir, "ssh-key") - if err := ioutil.WriteFile(sshKeyFile, []byte(sshKey), 0o400); err != nil { + if err := os.WriteFile(sshKeyFile, []byte(sshKey), 0o400); err != nil { cleanup() return "", nil, fmt.Errorf("create ssh key file: %w", err) } @@ -43,7 +42,7 @@ func BuildSSHInvocation(ctx context.Context, sshKey, knownHosts string) (string, if knownHosts != "" { knownHostsFile := filepath.Join(tmpDir, "known-hosts") - if err := ioutil.WriteFile(knownHostsFile, []byte(knownHosts), 0o400); err != nil { + if err := os.WriteFile(knownHostsFile, []byte(knownHosts), 0o400); err != nil { cleanup() return "", nil, fmt.Errorf("create known hosts file: %w", err) } diff --git a/internal/git/stats/commit_graph.go b/internal/git/stats/commit_graph.go index 6d8902666..221166102 100644 --- a/internal/git/stats/commit_graph.go +++ b/internal/git/stats/commit_graph.go @@ -5,7 +5,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "path/filepath" ) @@ -27,7 +26,7 @@ func IsMissingBloomFilters(repoPath string) (bool, error) { const chunkTableEntrySize = 12 commitGraphsPath := filepath.Join(repoPath, CommitGraphChainRelPath) - commitGraphsData, err := ioutil.ReadFile(commitGraphsPath) + commitGraphsData, err := os.ReadFile(commitGraphsPath) if err != nil { if errors.Is(err, os.ErrNotExist) { return true, nil diff --git a/internal/git/stats/git_test.go b/internal/git/stats/git_test.go index 9b484daf0..96954c01c 100644 --- a/internal/git/stats/git_test.go +++ b/internal/git/stats/git_test.go @@ -3,7 +3,6 @@ package stats import ( "bytes" "encoding/json" - "io/ioutil" "os" "path/filepath" "strings" @@ -55,7 +54,7 @@ func TestLogObjectInfo(t *testing.T) { storagePath, err := locator.GetStorageByName(repo1.GetStorageName()) require.NoError(t, err) - tmpDir, err := ioutil.TempDir(storagePath, "") + tmpDir, err := os.MkdirTemp(storagePath, "") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(tmpDir)) }() diff --git a/internal/git/stats/http_reference_discovery.go b/internal/git/stats/http_reference_discovery.go index 5c69f5674..170034e0c 100644 --- a/internal/git/stats/http_reference_discovery.go +++ b/internal/git/stats/http_reference_discovery.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "time" ) @@ -84,7 +83,7 @@ func performHTTPReferenceDiscovery( return HTTPReferenceDiscovery{}, err } defer func() { - _, _ = io.Copy(ioutil.Discard, resp.Body) + _, _ = io.Copy(io.Discard, resp.Body) _ = resp.Body.Close() }() diff --git a/internal/git/stats/packfile_negotiation.go b/internal/git/stats/packfile_negotiation.go index 72bd015a6..8b27349f5 100644 --- a/internal/git/stats/packfile_negotiation.go +++ b/internal/git/stats/packfile_negotiation.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "strings" "github.com/prometheus/client_golang/prometheus" @@ -47,7 +46,7 @@ func ParsePackfileNegotiation(body io.Reader) (PackfileNegotiation, error) { // have <OID> // flush|done func (n *PackfileNegotiation) Parse(body io.Reader) error { - defer func() { _, _ = io.Copy(ioutil.Discard, body) }() + defer func() { _, _ = io.Copy(io.Discard, body) }() scanner := pktline.NewScanner(body) diff --git a/internal/git/stats/profile.go b/internal/git/stats/profile.go index 2bdc0e9f1..a9a2ced15 100644 --- a/internal/git/stats/profile.go +++ b/internal/git/stats/profile.go @@ -1,5 +1,6 @@ package stats +//nolint:depguard import ( "context" "errors" diff --git a/internal/git/updateref/update_with_hooks_test.go b/internal/git/updateref/update_with_hooks_test.go index a8775efdf..3ba066d30 100644 --- a/internal/git/updateref/update_with_hooks_test.go +++ b/internal/git/updateref/update_with_hooks_test.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "strings" "testing" @@ -137,7 +136,7 @@ func TestUpdaterWithHooks_UpdateReference(t *testing.T) { { desc: "successful update", preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error { - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) require.NoError(t, err) require.Equal(t, fmt.Sprintf("%s %s refs/heads/master\n", oldRev, git.ZeroOID.String()), string(changes)) require.Empty(t, pushOptions) @@ -152,7 +151,7 @@ func TestUpdaterWithHooks_UpdateReference(t *testing.T) { return nil }, postReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error { - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) require.NoError(t, err) require.Equal(t, fmt.Sprintf("%s %s refs/heads/master\n", oldRev, git.ZeroOID.String()), string(changes)) require.Equal(t, env, expectedEnv) @@ -160,7 +159,7 @@ func TestUpdaterWithHooks_UpdateReference(t *testing.T) { return nil }, referenceTransaction: func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error { - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) require.NoError(t, err) require.Equal(t, fmt.Sprintf("%s %s refs/heads/master\n", oldRev, git.ZeroOID.String()), string(changes)) diff --git a/internal/git/version.go b/internal/git/version.go index dddf152ee..7bb02eeb2 100644 --- a/internal/git/version.go +++ b/internal/git/version.go @@ -3,7 +3,7 @@ package git import ( "context" "fmt" - "io/ioutil" + "io" "strconv" "strings" @@ -64,7 +64,7 @@ func CurrentVersionForExecutor(ctx context.Context, executor RepositoryExecutor) } func parseVersionFromCommand(cmd *command.Command) (Version, error) { - versionOutput, err := ioutil.ReadAll(cmd) + versionOutput, err := io.ReadAll(cmd) if err != nil { return Version{}, fmt.Errorf("reading version output: %w", err) } diff --git a/internal/gitaly/config/config.go b/internal/gitaly/config/config.go index e81e6c99e..e196d32f1 100644 --- a/internal/gitaly/config/config.go +++ b/internal/gitaly/config/config.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "os" "os/exec" @@ -208,11 +207,11 @@ func (cfg *Cfg) setDefaults() error { if cfg.InternalSocketDir == "" { // The socket path must be short-ish because listen(2) fails on long - // socket paths. We hope/expect that ioutil.TempDir creates a directory + // socket paths. We hope/expect that os.MkdirTemp creates a directory // that is not too deep. We need a directory, not a tempfile, because we // will later want to set its permissions to 0700 - tmpDir, err := ioutil.TempDir("", "gitaly-internal") + tmpDir, err := os.MkdirTemp("", "gitaly-internal") if err != nil { return fmt.Errorf("create internal socket directory: %w", err) } diff --git a/internal/gitaly/config/config_test.go b/internal/gitaly/config/config_test.go index 754a1a97f..27aaa0c76 100644 --- a/internal/gitaly/config/config_test.go +++ b/internal/gitaly/config/config_test.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -185,7 +184,7 @@ func TestValidateStorages(t *testing.T) { repositories2 := tempDir(t) nestedRepositories := filepath.Join(repositories, "nested") require.NoError(t, os.MkdirAll(nestedRepositories, os.ModePerm)) - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") require.NoError(t, err) require.NoError(t, f.Close()) filePath := f.Name() @@ -339,7 +338,7 @@ const ( ) func setupTempHookDirs(t *testing.T, m map[string]hookFileMode) (string, func()) { - tempDir, err := ioutil.TempDir("", "hooks") + tempDir, err := os.MkdirTemp("", "hooks") require.NoError(t, err) for hookName, mode := range m { @@ -347,7 +346,7 @@ func setupTempHookDirs(t *testing.T, m map[string]hookFileMode) (string, func()) path := filepath.Join(tempDir, hookName) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(tempDir, hookName), nil, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(tempDir, hookName), nil, 0o644)) if mode&hookFileExecutable > 0 { require.NoError(t, os.Chmod(filepath.Join(tempDir, hookName), 0o755)) @@ -561,7 +560,7 @@ func TestValidateGitConfig(t *testing.T) { } func TestValidateShellPath(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "gitaly-tests-") + tmpDir, err := os.MkdirTemp("", "gitaly-tests-") require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, "bin"), 0o755)) tmpFile := filepath.Join(tmpDir, "my-file") @@ -611,12 +610,12 @@ func TestValidateShellPath(t *testing.T) { } func TestConfigureRuby(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "gitaly-test") + tmpDir, err := os.MkdirTemp("", "gitaly-test") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(tmpDir)) }() tmpFile := filepath.Join(tmpDir, "file") - require.NoError(t, ioutil.WriteFile(tmpFile, nil, 0o644)) + require.NoError(t, os.WriteFile(tmpFile, nil, 0o644)) testCases := []struct { desc string @@ -765,7 +764,7 @@ func TestValidateInternalSocketDir(t *testing.T) { // create a symlinked socket directory dirName := "internal_socket_dir" validSocketDirSymlink := filepath.Join(tmpDir, dirName) - tmpSocketDir, err := ioutil.TempDir(tmpDir, "") + tmpSocketDir, err := os.MkdirTemp(tmpDir, "") require.NoError(t, err) tmpSocketDir, err = filepath.Abs(tmpSocketDir) require.NoError(t, err) @@ -1209,7 +1208,7 @@ func TestValidateBinDir(t *testing.T) { } func tempDir(t *testing.T) string { - tmpdir, err := ioutil.TempDir("", "") + tmpdir, err := os.MkdirTemp("", "") require.NoError(t, err) t.Cleanup(func() { if err := os.RemoveAll(tmpdir); err != nil && !errors.Is(err, os.ErrNotExist) { diff --git a/internal/gitaly/diff/diff.go b/internal/gitaly/diff/diff.go index 38f763728..3fb8191f7 100644 --- a/internal/gitaly/diff/diff.go +++ b/internal/gitaly/diff/diff.go @@ -5,7 +5,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "regexp" "strconv" @@ -120,7 +119,7 @@ func NewDiffParser(src io.Reader, limits Limits) *Parser { func (parser *Parser) Parse() bool { if parser.finished || len(parser.rawLines) == 0 { // In case we didn't consume the whole output due to reaching limitations - _, _ = io.Copy(ioutil.Discard, parser.patchReader) + _, _ = io.Copy(io.Discard, parser.patchReader) return false } diff --git a/internal/gitaly/hook/custom.go b/internal/gitaly/hook/custom.go index 8c894e09d..cbbf10c1b 100644 --- a/internal/gitaly/hook/custom.go +++ b/internal/gitaly/hook/custom.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -57,7 +56,7 @@ func (m *GitLabHookManager) newCustomHooksExecutor(repo *gitalypb.Repository, ho return func(ctx context.Context, args, env []string, stdin io.Reader, stdout, stderr io.Writer) error { var stdinBytes []byte if stdin != nil { - stdinBytes, err = ioutil.ReadAll(stdin) + stdinBytes, err = io.ReadAll(stdin) if err != nil { return err } @@ -83,7 +82,7 @@ func (m *GitLabHookManager) newCustomHooksExecutor(repo *gitalypb.Repository, ho // valid if `isValidHook()` would return `true`. Matching hooks are sorted by // filename. func findHooks(dir string) ([]string, error) { - fis, err := ioutil.ReadDir(dir) + fis, err := os.ReadDir(dir) if err != nil { if os.IsNotExist(err) { return nil, nil diff --git a/internal/gitaly/hook/custom_test.go b/internal/gitaly/hook/custom_test.go index cd9872c92..9f99fa6b7 100644 --- a/internal/gitaly/hook/custom_test.go +++ b/internal/gitaly/hook/custom_test.go @@ -4,7 +4,6 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -425,7 +424,7 @@ type customHookResults struct { func writeCustomHook(t *testing.T, hookName, dir string, content []byte) func() { require.NoError(t, os.MkdirAll(dir, 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, hookName), content, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, hookName), content, 0o755)) return func() { require.NoError(t, os.RemoveAll(dir)) diff --git a/internal/gitaly/hook/postreceive.go b/internal/gitaly/hook/postreceive.go index a9082049e..1bfd40fe2 100644 --- a/internal/gitaly/hook/postreceive.go +++ b/internal/gitaly/hook/postreceive.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "strings" @@ -123,7 +122,7 @@ func (m *GitLabHookManager) PostReceiveHook(ctx context.Context, repo *gitalypb. return helper.ErrInternalf("extracting hooks payload: %w", err) } - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) if err != nil { return helper.ErrInternalf("reading stdin from request: %w", err) } diff --git a/internal/gitaly/hook/prereceive.go b/internal/gitaly/hook/prereceive.go index d0f6e4b35..1277fb541 100644 --- a/internal/gitaly/hook/prereceive.go +++ b/internal/gitaly/hook/prereceive.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "path/filepath" "strings" @@ -68,7 +67,7 @@ func (m *GitLabHookManager) PreReceiveHook(ctx context.Context, repo *gitalypb.R return helper.ErrInternalf("extracting hooks payload: %w", err) } - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) if err != nil { return helper.ErrInternalf("reading stdin from request: %w", err) } diff --git a/internal/gitaly/hook/referencetransaction.go b/internal/gitaly/hook/referencetransaction.go index 7d2fbd4ad..e75ea3cb0 100644 --- a/internal/gitaly/hook/referencetransaction.go +++ b/internal/gitaly/hook/referencetransaction.go @@ -7,7 +7,6 @@ import ( "crypto/sha1" "fmt" "io" - "io/ioutil" "gitlab.com/gitlab-org/gitaly/v14/internal/git" ) @@ -22,7 +21,7 @@ func (m *GitLabHookManager) ReferenceTransactionHook(ctx context.Context, state return fmt.Errorf("extracting hooks payload: %w", err) } - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) if err != nil { return fmt.Errorf("reading stdin from request: %w", err) } diff --git a/internal/gitaly/hook/sidechannel.go b/internal/gitaly/hook/sidechannel.go index 18381237c..3311a56c5 100644 --- a/internal/gitaly/hook/sidechannel.go +++ b/internal/gitaly/hook/sidechannel.go @@ -3,7 +3,6 @@ package hook import ( "context" "fmt" - "io/ioutil" "net" "os" "path" @@ -41,7 +40,7 @@ func GetSidechannel(ctx context.Context) (net.Conn, error) { // returned context, so that the caller can propagate it to a server. The // caller must Close the SidechannelWaiter to prevent resource leaks. func SetupSidechannel(ctx context.Context, callback func(*net.UnixConn) error) (context.Context, *SidechannelWaiter, error) { - socketDir, err := ioutil.TempDir("", "gitaly") + socketDir, err := os.MkdirTemp("", "gitaly") if err != nil { return nil, nil, err } diff --git a/internal/gitaly/hook/sidechannel_test.go b/internal/gitaly/hook/sidechannel_test.go index 362b2432a..8571d8a2b 100644 --- a/internal/gitaly/hook/sidechannel_test.go +++ b/internal/gitaly/hook/sidechannel_test.go @@ -3,7 +3,6 @@ package hook import ( "context" "io" - "io/ioutil" "net" "testing" @@ -30,7 +29,7 @@ func TestSidechannel(t *testing.T) { require.NoError(t, err) defer c.Close() - buf, err := ioutil.ReadAll(c) + buf, err := io.ReadAll(c) require.NoError(t, err) require.Equal(t, "ping", string(buf)) diff --git a/internal/gitaly/hook/transactions_test.go b/internal/gitaly/hook/transactions_test.go index d3d65e646..b9ee01858 100644 --- a/internal/gitaly/hook/transactions_test.go +++ b/internal/gitaly/hook/transactions_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "strings" "testing" "time" @@ -56,13 +56,13 @@ func TestHookManager_stopCalled(t *testing.T) { } preReceiveFunc := func(t *testing.T) error { - return hookManager.PreReceiveHook(ctx, repo, nil, []string{hooksPayload}, strings.NewReader("changes"), ioutil.Discard, ioutil.Discard) + return hookManager.PreReceiveHook(ctx, repo, nil, []string{hooksPayload}, strings.NewReader("changes"), io.Discard, io.Discard) } updateFunc := func(t *testing.T) error { - return hookManager.UpdateHook(ctx, repo, "ref", git.ZeroOID.String(), git.ZeroOID.String(), []string{hooksPayload}, ioutil.Discard, ioutil.Discard) + return hookManager.UpdateHook(ctx, repo, "ref", git.ZeroOID.String(), git.ZeroOID.String(), []string{hooksPayload}, io.Discard, io.Discard) } postReceiveFunc := func(t *testing.T) error { - return hookManager.PostReceiveHook(ctx, repo, nil, []string{hooksPayload}, strings.NewReader("changes"), ioutil.Discard, ioutil.Discard) + return hookManager.PostReceiveHook(ctx, repo, nil, []string{hooksPayload}, strings.NewReader("changes"), io.Discard, io.Discard) } for _, tc := range []struct { diff --git a/internal/gitaly/linguist/linguist.go b/internal/gitaly/linguist/linguist.go index ebe9dd8d0..240b75a00 100644 --- a/internal/gitaly/linguist/linguist.go +++ b/internal/gitaly/linguist/linguist.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -55,7 +54,7 @@ func (inst *Instance) Stats(ctx context.Context, cfg config.Cfg, repoPath string return nil, fmt.Errorf("starting linguist: %w", err) } - data, err := ioutil.ReadAll(cmd) + data, err := io.ReadAll(cmd) if err != nil { return nil, fmt.Errorf("reading linguist output: %w", err) } @@ -132,7 +131,7 @@ func openLanguagesJSON(cfg config.Cfg) (io.ReadCloser, error) { return os.Open(jsonPath) } - linguistPathSymlink, err := ioutil.TempFile("", "gitaly-linguist-path") + linguistPathSymlink, err := os.CreateTemp("", "gitaly-linguist-path") if err != nil { return nil, err } diff --git a/internal/gitaly/maintenance/randomwalker.go b/internal/gitaly/maintenance/randomwalker.go index 6424b5432..eed27dbda 100644 --- a/internal/gitaly/maintenance/randomwalker.go +++ b/internal/gitaly/maintenance/randomwalker.go @@ -2,7 +2,6 @@ package maintenance import ( "errors" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -12,7 +11,7 @@ var errIterOver = errors.New("random walker at end") type stackFrame struct { name string - entries []os.FileInfo + entries []os.DirEntry } // randomWalker is a filesystem walker which traverses a directory hierarchy in depth-first order, @@ -36,19 +35,19 @@ func newRandomWalker(root string, r *rand.Rand) *randomWalker { // next returns the next file. Traversal happens in depth-first order, where each directory's // entities are traversed in random order. If there are no more files to iterate, `errIterOver` is // returned. -func (r *randomWalker) next() (os.FileInfo, string, error) { +func (r *randomWalker) next() (os.DirEntry, string, error) { if r.pendingDir != "" { // Reset pendingDir before returning the error such that the caller can continue if // he doesn't care e.g. for the directory not existing. pendingDir := r.pendingDir r.pendingDir = "" - entries, err := ioutil.ReadDir(pendingDir) + entries, err := os.ReadDir(pendingDir) if err != nil { return nil, pendingDir, err } - shuffleFileInfos(r.rand, entries) + shuffleDirEntries(r.rand, entries) r.stack = append(r.stack, stackFrame{ name: pendingDir, entries: entries, @@ -83,7 +82,7 @@ func (r *randomWalker) next() (os.FileInfo, string, error) { } } -func shuffleFileInfos(randSrc *rand.Rand, s []os.FileInfo) { +func shuffleDirEntries(randSrc *rand.Rand, s []os.DirEntry) { randSrc.Shuffle(len(s), func(i, j int) { s[i], s[j] = s[j], s[i] }) } diff --git a/internal/gitaly/maintenance/randomwalker_test.go b/internal/gitaly/maintenance/randomwalker_test.go index 66676f372..5db523dc3 100644 --- a/internal/gitaly/maintenance/randomwalker_test.go +++ b/internal/gitaly/maintenance/randomwalker_test.go @@ -1,7 +1,6 @@ package maintenance import ( - "io/ioutil" "math/rand" "os" "path/filepath" @@ -154,7 +153,7 @@ func TestRandomWalk(t *testing.T) { } for _, file := range tc.files { - require.NoError(t, ioutil.WriteFile(filepath.Join(root, file), []byte{}, 0o777)) + require.NoError(t, os.WriteFile(filepath.Join(root, file), []byte{}, 0o777)) } walker := newRandomWalker(root, rand.New(rand.NewSource(1))) diff --git a/internal/gitaly/server/auth_test.go b/internal/gitaly/server/auth_test.go index 94f5e9ef5..2dbde3056 100644 --- a/internal/gitaly/server/auth_test.go +++ b/internal/gitaly/server/auth_test.go @@ -5,7 +5,7 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" + "io" "net" "os" "testing" @@ -292,7 +292,7 @@ func TestStreamingNoAuth(t *testing.T) { ) require.NoError(t, err) - _, err = ioutil.ReadAll(streamio.NewReader(func() ([]byte, error) { + _, err = io.ReadAll(streamio.NewReader(func() ([]byte, error) { _, err = stream.Recv() return nil, err })) diff --git a/internal/gitaly/service/blob/blobs.go b/internal/gitaly/service/blob/blobs.go index cb6dcfc53..651bbdf29 100644 --- a/internal/gitaly/service/blob/blobs.go +++ b/internal/gitaly/service/blob/blobs.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "strings" "gitlab.com/gitlab-org/gitaly/v14/internal/git" @@ -169,7 +168,7 @@ func processBlobs( // Discard trailing blob data in case the blob is bigger than the read // limit. - _, err = io.Copy(ioutil.Discard, blob.ObjectReader) + _, err = io.Copy(io.Discard, blob.ObjectReader) if err != nil { return helper.ErrInternal(fmt.Errorf("discarding blob data: %w", err)) } diff --git a/internal/gitaly/service/blob/get_blobs.go b/internal/gitaly/service/blob/get_blobs.go index c2cfda64f..3051492d2 100644 --- a/internal/gitaly/service/blob/get_blobs.go +++ b/internal/gitaly/service/blob/get_blobs.go @@ -3,7 +3,6 @@ package blob import ( "bytes" "io" - "io/ioutil" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile" @@ -133,7 +132,7 @@ func sendBlobTreeEntry(response *gitalypb.GetBlobsResponse, stream gitalypb.Blob return status.Errorf(codes.Unavailable, "GetBlobs: send: %v", err) } - if _, err := io.Copy(ioutil.Discard, blobObj.Reader); err != nil { + if _, err := io.Copy(io.Discard, blobObj.Reader); err != nil { return status.Errorf(codes.Unavailable, "GetBlobs: discarding data: %v", err) } diff --git a/internal/gitaly/service/commit/count_commits.go b/internal/gitaly/service/commit/count_commits.go index 408a04d3c..6dc68e250 100644 --- a/internal/gitaly/service/commit/count_commits.go +++ b/internal/gitaly/service/commit/count_commits.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "strconv" "time" @@ -54,7 +54,7 @@ func (s *server) CountCommits(ctx context.Context, in *gitalypb.CountCommitsRequ } var count int64 - countStr, readAllErr := ioutil.ReadAll(cmd) + countStr, readAllErr := io.ReadAll(cmd) if readAllErr != nil { ctxlogrus.Extract(ctx).WithError(err).Info("ignoring git rev-list error") } diff --git a/internal/gitaly/service/commit/count_diverging_commits.go b/internal/gitaly/service/commit/count_diverging_commits.go index a4ee6a903..f47b135da 100644 --- a/internal/gitaly/service/commit/count_diverging_commits.go +++ b/internal/gitaly/service/commit/count_diverging_commits.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "strconv" "strings" @@ -65,7 +65,7 @@ func (s *server) findLeftRightCount(ctx context.Context, repo *gitalypb.Reposito } var leftCount, rightCount int64 - countStr, err := ioutil.ReadAll(cmd) + countStr, err := io.ReadAll(cmd) if err != nil { return 0, 0, fmt.Errorf("git rev-list error: %v", err) } diff --git a/internal/gitaly/service/commit/raw_blame_test.go b/internal/gitaly/service/commit/raw_blame_test.go index cb4c21085..31abdc77b 100644 --- a/internal/gitaly/service/commit/raw_blame_test.go +++ b/internal/gitaly/service/commit/raw_blame_test.go @@ -2,7 +2,7 @@ package commit import ( "fmt" - "io/ioutil" + "io" "testing" "github.com/stretchr/testify/require" @@ -54,7 +54,7 @@ func TestSuccessfulRawBlameRequest(t *testing.T) { return response.GetData(), err }) - blame, err := ioutil.ReadAll(sr) + blame, err := io.ReadAll(sr) require.NoError(t, err) require.Equal(t, testCase.data, blame, "blame data mismatched") diff --git a/internal/gitaly/service/conflicts/list_conflict_files_test.go b/internal/gitaly/service/conflicts/list_conflict_files_test.go index 2fc7b4346..f5b68c777 100644 --- a/internal/gitaly/service/conflicts/list_conflict_files_test.go +++ b/internal/gitaly/service/conflicts/list_conflict_files_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "io" - "io/ioutil" + "os" "path/filepath" "testing" @@ -185,7 +185,7 @@ func buildCommit(t *testing.T, ctx context.Context, cfg config.Cfg, repo *gitaly for file, contents := range files { filePath := filepath.Join(repoPath, file) - require.NoError(t, ioutil.WriteFile(filePath, contents, 0o666)) + require.NoError(t, os.WriteFile(filePath, contents, 0o666)) gittest.Exec(t, cfg, "-C", repoPath, "add", filePath) } diff --git a/internal/gitaly/service/conflicts/resolve_conflicts_test.go b/internal/gitaly/service/conflicts/resolve_conflicts_test.go index 3c08fd012..9bc790d89 100644 --- a/internal/gitaly/service/conflicts/resolve_conflicts_test.go +++ b/internal/gitaly/service/conflicts/resolve_conflicts_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" + "os" "os/exec" "path/filepath" "regexp" @@ -129,7 +129,7 @@ func TestSuccessfulResolveConflictsRequestHelper(t *testing.T) { hookCount := 0 verifyFunc := func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error { - changes, err := ioutil.ReadAll(stdin) + changes, err := io.ReadAll(stdin) require.NoError(t, err) pattern := fmt.Sprintf("%s .* refs/heads/%s\n", ourCommitOID, sourceBranch) require.Regexp(t, regexp.MustCompile(pattern), string(changes)) @@ -448,7 +448,7 @@ func TestResolveConflictsIdenticalContent(t *testing.T) { } { contents := gittest.Exec(t, cfg, "-C", repoPath, "cat-file", "-p", rev+":files/ruby/popen.rb") path := filepath.Join(tempDir, rev) - require.NoError(t, ioutil.WriteFile(path, contents, 0o644)) + require.NoError(t, os.WriteFile(path, contents, 0o644)) conflictingPaths = append(conflictingPaths, path) } diff --git a/internal/gitaly/service/conflicts/testhelper_test.go b/internal/gitaly/service/conflicts/testhelper_test.go index f20e12785..f85a2adc1 100644 --- a/internal/gitaly/service/conflicts/testhelper_test.go +++ b/internal/gitaly/service/conflicts/testhelper_test.go @@ -1,7 +1,6 @@ package conflicts import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -33,7 +32,7 @@ func testMain(m *testing.M) int { cleanup := testhelper.Configure() defer cleanup() - tempDir, err := ioutil.TempDir("", "gitaly") + tempDir, err := os.MkdirTemp("", "gitaly") if err != nil { log.Error(err) return 1 diff --git a/internal/gitaly/service/diff/raw_test.go b/internal/gitaly/service/diff/raw_test.go index 05b0a7c01..5a70e3eae 100644 --- a/internal/gitaly/service/diff/raw_test.go +++ b/internal/gitaly/service/diff/raw_test.go @@ -2,7 +2,7 @@ package diff import ( "fmt" - "io/ioutil" + "io" "regexp" "testing" @@ -197,7 +197,7 @@ func TestRawPatchContainsGitLabSignature(t *testing.T) { return response.GetData(), err }) - patch, err := ioutil.ReadAll(reader) + patch, err := io.ReadAll(reader) require.NoError(t, err) require.Regexp(t, regexp.MustCompile(`\n-- \nGitLab\s+$`), string(patch)) diff --git a/internal/gitaly/service/hook/pack_objects.go b/internal/gitaly/service/hook/pack_objects.go index e9eb34430..3512f7c8b 100644 --- a/internal/gitaly/service/hook/pack_objects.go +++ b/internal/gitaly/service/hook/pack_objects.go @@ -10,7 +10,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "os" "strings" "syscall" @@ -311,7 +310,7 @@ func (p *packObjectsArgs) subcmd() git.SubCmd { } func bufferStdin(r io.Reader, h hash.Hash) (_ io.ReadCloser, err error) { - f, err := ioutil.TempFile("", "PackObjectsHook-stdin") + f, err := os.CreateTemp("", "PackObjectsHook-stdin") if err != nil { return nil, err } diff --git a/internal/gitaly/service/objectpool/alternates.go b/internal/gitaly/service/objectpool/alternates.go index 5884114ee..218ef8492 100644 --- a/internal/gitaly/service/objectpool/alternates.go +++ b/internal/gitaly/service/objectpool/alternates.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -50,7 +49,7 @@ func (s *server) disconnectAlternates(ctx context.Context, repo *gitalypb.Reposi return err } - altContents, err := ioutil.ReadFile(altFile) + altContents, err := os.ReadFile(altFile) if err != nil { if os.IsNotExist(err) { return nil diff --git a/internal/gitaly/service/objectpool/alternates_test.go b/internal/gitaly/service/objectpool/alternates_test.go index 350973d8a..383120a19 100644 --- a/internal/gitaly/service/objectpool/alternates_test.go +++ b/internal/gitaly/service/objectpool/alternates_test.go @@ -2,7 +2,6 @@ package objectpool import ( "fmt" - "io/ioutil" "os" "testing" @@ -91,7 +90,7 @@ func TestDisconnectGitAlternatesUnexpectedAlternates(t *testing.T) { altPath, err := locator.InfoAlternatesPath(repo) require.NoError(t, err, "find info/alternates") - require.NoError(t, ioutil.WriteFile(altPath, []byte(tc.altContent), 0o644)) + require.NoError(t, os.WriteFile(altPath, []byte(tc.altContent), 0o644)) _, err = client.DisconnectGitAlternates(ctx, &gitalypb.DisconnectGitAlternatesRequest{Repository: repo}) require.Error(t, err, "call DisconnectGitAlternates on repository with unexpected objects/info/alternates") @@ -111,7 +110,7 @@ func TestRemoveAlternatesIfOk(t *testing.T) { altPath, err := locator.InfoAlternatesPath(repo) require.NoError(t, err, "find info/alternates") altContent := "/var/empty\n" - require.NoError(t, ioutil.WriteFile(altPath, []byte(altContent), 0o644), "write alternates file") + require.NoError(t, os.WriteFile(altPath, []byte(altContent), 0o644), "write alternates file") // Intentionally break the repository, so that 'git fsck' will fail later. testhelper.MustRunCommand(t, nil, "sh", "-c", fmt.Sprintf("rm %s/objects/pack/*.pack", repoPath)) diff --git a/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go b/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go index c3e14761d..9b68557e1 100644 --- a/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go +++ b/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go @@ -3,7 +3,6 @@ package objectpool import ( "bytes" "encoding/json" - "io/ioutil" "os" "path/filepath" "strings" @@ -71,7 +70,7 @@ func TestFetchIntoObjectPool_Success(t *testing.T) { require.NoError(t, err) brokenRef := filepath.Join(poolPath, "refs", "heads", "broken") require.NoError(t, os.MkdirAll(filepath.Dir(brokenRef), 0o755)) - require.NoError(t, ioutil.WriteFile(brokenRef, []byte{}, 0o777)) + require.NoError(t, os.WriteFile(brokenRef, []byte{}, 0o777)) oldTime := time.Now().Add(-25 * time.Hour) require.NoError(t, os.Chtimes(brokenRef, oldTime, oldTime)) @@ -100,7 +99,7 @@ func TestFetchIntoObjectPool_hooks(t *testing.T) { // Set up a custom reference-transaction hook which simply exits failure. This asserts that // the RPC doesn't invoke any reference-transaction. - require.NoError(t, ioutil.WriteFile(filepath.Join(hookDir, "reference-transaction"), []byte("#!/bin/sh\nexit 1\n"), 0o777)) + require.NoError(t, os.WriteFile(filepath.Join(hookDir, "reference-transaction"), []byte("#!/bin/sh\nexit 1\n"), 0o777)) req := &gitalypb.FetchIntoObjectPoolRequest{ ObjectPool: pool.ToProto(), diff --git a/internal/gitaly/service/objectpool/get_test.go b/internal/gitaly/service/objectpool/get_test.go index 562a93273..ecc9a2343 100644 --- a/internal/gitaly/service/objectpool/get_test.go +++ b/internal/gitaly/service/objectpool/get_test.go @@ -1,7 +1,6 @@ package objectpool import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -55,7 +54,7 @@ func TestGetObjectPoolBadFile(t *testing.T) { alternatesFilePath := filepath.Join(repoPath, "objects", "info", "alternates") require.NoError(t, os.MkdirAll(filepath.Dir(alternatesFilePath), 0o755)) - require.NoError(t, ioutil.WriteFile(alternatesFilePath, []byte("not-a-directory"), 0o644)) + require.NoError(t, os.WriteFile(alternatesFilePath, []byte("not-a-directory"), 0o644)) ctx, cancel := testhelper.Context() defer cancel() diff --git a/internal/gitaly/service/objectpool/link_test.go b/internal/gitaly/service/objectpool/link_test.go index 148a0889d..5ae22a8b5 100644 --- a/internal/gitaly/service/objectpool/link_test.go +++ b/internal/gitaly/service/objectpool/link_test.go @@ -1,7 +1,6 @@ package objectpool import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -120,7 +119,7 @@ func TestLinkNoClobber(t *testing.T) { require.NoFileExists(t, alternatesFile) contentBefore := "mock/objects\n" - require.NoError(t, ioutil.WriteFile(alternatesFile, []byte(contentBefore), 0o644)) + require.NoError(t, os.WriteFile(alternatesFile, []byte(contentBefore), 0o644)) request := &gitalypb.LinkRepositoryToObjectPoolRequest{ Repository: repo, diff --git a/internal/gitaly/service/operations/merge_test.go b/internal/gitaly/service/operations/merge_test.go index e670e48a9..ed7559a12 100644 --- a/internal/gitaly/service/operations/merge_test.go +++ b/internal/gitaly/service/operations/merge_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "os/exec" "regexp" @@ -62,7 +61,7 @@ func testUserMergeBranchSuccessful(t *testing.T, ctx context.Context) { hooks := GitlabHooks hookTempfiles := make([]string, len(hooks)) for i, hook := range hooks { - outputFile, err := ioutil.TempFile("", "") + outputFile, err := os.CreateTemp("", "") require.NoError(t, err) require.NoError(t, outputFile.Close()) defer func() { require.NoError(t, os.Remove(outputFile.Name())) }() diff --git a/internal/gitaly/service/operations/squash_test.go b/internal/gitaly/service/operations/squash_test.go index 5bbdec94d..bba554088 100644 --- a/internal/gitaly/service/operations/squash_test.go +++ b/internal/gitaly/service/operations/squash_test.go @@ -2,7 +2,7 @@ package operations import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -140,7 +140,7 @@ func authorFromUser(user *gitalypb.User, seconds int64) *gitalypb.CommitAuthor { func ensureSplitIndexExists(t *testing.T, cfg config.Cfg, repoDir string) bool { gittest.Exec(t, cfg, "-C", repoDir, "update-index", "--add") - fis, err := ioutil.ReadDir(repoDir) + fis, err := os.ReadDir(repoDir) require.NoError(t, err) for _, fi := range fis { if strings.HasPrefix(fi.Name(), "sharedindex") { @@ -229,7 +229,7 @@ func TestUserSquash_renames(t *testing.T) { renamedFilename := "renamed-file.txt" gittest.Exec(t, cfg, "-C", repoPath, "checkout", "-b", "squash-rename-test", "master") - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is a test"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is a test"), 0o644)) gittest.Exec(t, cfg, "-C", repoPath, "add", ".") gittest.Exec(t, cfg, "-C", repoPath, "commit", "-m", "test file") @@ -240,10 +240,10 @@ func TestUserSquash_renames(t *testing.T) { // Modify the original file in another branch gittest.Exec(t, cfg, "-C", repoPath, "checkout", "-b", "squash-rename-branch", startCommitID) - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is a change"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is a change"), 0o644)) gittest.Exec(t, cfg, "-C", repoPath, "commit", "-a", "-m", "test") - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is another change"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, originalFilename), []byte("This is another change"), 0o644)) gittest.Exec(t, cfg, "-C", repoPath, "commit", "-a", "-m", "test") endCommitID := text.ChompBytes(gittest.Exec(t, cfg, "-C", repoPath, "rev-parse", "HEAD")) diff --git a/internal/gitaly/service/operations/tags_test.go b/internal/gitaly/service/operations/tags_test.go index fa7a202bd..0a51b392a 100644 --- a/internal/gitaly/service/operations/tags_test.go +++ b/internal/gitaly/service/operations/tags_test.go @@ -2,7 +2,6 @@ package operations import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -117,7 +116,7 @@ end`, cfg.Git.BinPath) dir := testhelper.TempDir(t) hookPath := filepath.Join(dir, "pre-receive") - require.NoError(t, ioutil.WriteFile(hookPath, []byte(hook), 0o755)) + require.NoError(t, os.WriteFile(hookPath, []byte(hook), 0o755)) return hookPath } @@ -150,7 +149,7 @@ end`, cfg.Git.BinPath) dir := testhelper.TempDir(t) hookPath := filepath.Join(dir, "pre-receive") - require.NoError(t, ioutil.WriteFile(hookPath, []byte(hook), 0o755)) + require.NoError(t, os.WriteFile(hookPath, []byte(hook), 0o755)) return hookPath } diff --git a/internal/gitaly/service/ref/find_all_tags.go b/internal/gitaly/service/ref/find_all_tags.go index 057414302..a52156191 100644 --- a/internal/gitaly/service/ref/find_all_tags.go +++ b/internal/gitaly/service/ref/find_all_tags.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "gitlab.com/gitlab-org/gitaly/v14/internal/git/catfile" "gitlab.com/gitlab-org/gitaly/v14/internal/git/gitpipe" @@ -137,7 +136,7 @@ func (s *server) findAllTags(ctx context.Context, repo *localrepo.Repo, sortFiel return fmt.Errorf("parsing tagged commit: %w", err) } } else { - if _, err := io.Copy(ioutil.Discard, peeledTag.ObjectReader); err != nil { + if _, err := io.Copy(io.Discard, peeledTag.ObjectReader); err != nil { return fmt.Errorf("discarding tagged object contents: %w", err) } } @@ -152,7 +151,7 @@ func (s *server) findAllTags(ctx context.Context, repo *localrepo.Repo, sortFiel TargetCommit: commit, } default: - if _, err := io.Copy(ioutil.Discard, tag.ObjectReader); err != nil { + if _, err := io.Copy(io.Discard, tag.ObjectReader); err != nil { return fmt.Errorf("discarding tag object contents: %w", err) } diff --git a/internal/gitaly/service/ref/pack_refs_test.go b/internal/gitaly/service/ref/pack_refs_test.go index 3863b34ce..c9f068df6 100644 --- a/internal/gitaly/service/ref/pack_refs_test.go +++ b/internal/gitaly/service/ref/pack_refs_test.go @@ -3,7 +3,6 @@ package ref import ( "bufio" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -38,7 +37,7 @@ func TestPackRefsSuccessfulRequest(t *testing.T) { _, err := client.PackRefs(ctx, &gitalypb.PackRefsRequest{Repository: repoProto}) require.NoError(t, err) - files, err := ioutil.ReadDir(filepath.Join(repoPath, "refs/heads")) + files, err := os.ReadDir(filepath.Join(repoPath, "refs/heads")) require.NoError(t, err) assert.Len(t, files, 0, "git pack-refs --all should have packed all refs in refs/heads") assert.Equal(t, packedRefs+newBranches, linesInPackfile(t, repoPath), fmt.Sprintf("should have added %d new lines to the packfile", newBranches)) diff --git a/internal/gitaly/service/ref/tag_signatures.go b/internal/gitaly/service/ref/tag_signatures.go index 61239afae..57f656f4f 100644 --- a/internal/gitaly/service/ref/tag_signatures.go +++ b/internal/gitaly/service/ref/tag_signatures.go @@ -3,7 +3,7 @@ package ref import ( "errors" "fmt" - "io/ioutil" + "io" "strings" "gitlab.com/gitlab-org/gitaly/v14/internal/git" @@ -77,7 +77,7 @@ func (s *server) GetTagSignatures(req *gitalypb.GetTagSignaturesRequest, stream for catfileObjectIter.Next() { tag := catfileObjectIter.Result() - raw, err := ioutil.ReadAll(tag.ObjectReader) + raw, err := io.ReadAll(tag.ObjectReader) if err != nil { return helper.ErrInternal(err) } diff --git a/internal/gitaly/service/remote/fetch_internal_remote_test.go b/internal/gitaly/service/remote/fetch_internal_remote_test.go index b4c5df9a4..b792ce166 100644 --- a/internal/gitaly/service/remote/fetch_internal_remote_test.go +++ b/internal/gitaly/service/remote/fetch_internal_remote_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -83,7 +82,7 @@ func listenGitalySSHCalls(t *testing.T, conf config.Cfg) func() []GitalySSHParam exit $?`, tmpDir, envPrefix, argsPrefix, updatedPath) - require.NoError(t, ioutil.WriteFile(initialPath, []byte(script), 0o755)) + require.NoError(t, os.WriteFile(initialPath, []byte(script), 0o755)) getSSHParams := func() []GitalySSHParams { var gitalySSHParams []GitalySSHParams @@ -110,7 +109,7 @@ func listenGitalySSHCalls(t *testing.T, conf config.Cfg) func() []GitalySSHParam gitalySSHParams = tmp } - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return err } diff --git a/internal/gitaly/service/remote/find_remote_repository.go b/internal/gitaly/service/remote/find_remote_repository.go index 1d0088390..5504da686 100644 --- a/internal/gitaly/service/remote/find_remote_repository.go +++ b/internal/gitaly/service/remote/find_remote_repository.go @@ -3,7 +3,7 @@ package remote import ( "bytes" "context" - "io/ioutil" + "io" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb" @@ -29,7 +29,7 @@ func (s *server) FindRemoteRepository(ctx context.Context, req *gitalypb.FindRem return nil, status.Errorf(codes.Internal, "error executing git command: %s", err) } - output, err := ioutil.ReadAll(cmd) + output, err := io.ReadAll(cmd) if err != nil { return nil, status.Errorf(codes.Internal, "unable to read stdout: %s", err) } diff --git a/internal/gitaly/service/repository/apply_gitattributes.go b/internal/gitaly/service/repository/apply_gitattributes.go index a26b1cc14..38b517837 100644 --- a/internal/gitaly/service/repository/apply_gitattributes.go +++ b/internal/gitaly/service/repository/apply_gitattributes.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" @@ -86,7 +85,7 @@ func (s *server) applyGitattributes(ctx context.Context, c catfile.Batch, repoPa return nil } - tempFile, err := ioutil.TempFile(infoPath, "attributes") + tempFile, err := os.CreateTemp(infoPath, "attributes") if err != nil { return helper.ErrInternalf("creating temporary gitattributes file: %w", err) } diff --git a/internal/gitaly/service/repository/apply_gitattributes_test.go b/internal/gitaly/service/repository/apply_gitattributes_test.go index 1fa728644..b83c2fd09 100644 --- a/internal/gitaly/service/repository/apply_gitattributes_test.go +++ b/internal/gitaly/service/repository/apply_gitattributes_test.go @@ -5,7 +5,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -75,7 +74,7 @@ func testApplyGitattributesSuccess(t *testing.T, ctx context.Context) { // Test when a git attributes file already exists require.NoError(t, os.MkdirAll(infoPath, 0o755)) - require.NoError(t, ioutil.WriteFile(attributesPath, []byte("*.docx diff=word"), 0o644)) + require.NoError(t, os.WriteFile(attributesPath, []byte("*.docx diff=word"), 0o644)) assertGitattributesApplied(t, ctx, client, repo, attributesPath, test.revision, test.contents) }) } @@ -302,7 +301,7 @@ func assertGitattributesApplied(t *testing.T, ctx context.Context, client gitaly assert.NoError(t, err) assert.NotNil(t, c) - contents, err := ioutil.ReadFile(attributesPath) + contents, err := os.ReadFile(attributesPath) if expectedContents == nil { if !os.IsNotExist(err) { t.Error(err) diff --git a/internal/gitaly/service/repository/archive_test.go b/internal/gitaly/service/repository/archive_test.go index 7098a4910..c2ab3095c 100644 --- a/internal/gitaly/service/repository/archive_test.go +++ b/internal/gitaly/service/repository/archive_test.go @@ -5,7 +5,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -147,7 +147,7 @@ func TestGetArchiveSuccess(t *testing.T) { data, err := consumeArchive(stream) require.NoError(t, err) - archiveFile, err := ioutil.TempFile("", "") + archiveFile, err := os.CreateTemp("", "") require.NoError(t, err) defer func() { require.NoError(t, os.Remove(archiveFile.Name())) }() @@ -263,7 +263,7 @@ func TestGetArchiveWithLfsSuccess(t *testing.T) { require.NoError(t, err) defer fc.Close() - data, err := ioutil.ReadAll(fc) + data, err := io.ReadAll(fc) require.NoError(t, err) if tc.includeLfsBlobs { @@ -464,7 +464,7 @@ func TestGetArchivePathInjection(t *testing.T) { require.NoError(t, err) defer authorizedKeysFile.Close() - authorizedKeysFileBytes, err := ioutil.ReadAll(authorizedKeysFile) + authorizedKeysFileBytes, err := io.ReadAll(authorizedKeysFile) require.NoError(t, err) authorizedKeysFileStat, err := authorizedKeysFile.Stat() require.NoError(t, err) @@ -475,7 +475,7 @@ func TestGetArchivePathInjection(t *testing.T) { func TestGetArchiveEnv(t *testing.T) { t.Parallel() - tmpFile, err := ioutil.TempFile("", "archive.sh") + tmpFile, err := os.CreateTemp("", "archive.sh") require.NoError(t, err) defer func() { require.NoError(t, os.Remove(tmpFile.Name())) }() @@ -557,5 +557,5 @@ func consumeArchive(stream gitalypb.RepositoryService_GetArchiveClient) ([]byte, return response.GetData(), err }) - return ioutil.ReadAll(reader) + return io.ReadAll(reader) } diff --git a/internal/gitaly/service/repository/backup_custom_hooks_test.go b/internal/gitaly/service/repository/backup_custom_hooks_test.go index 9c154d1f4..ef0b69b3b 100644 --- a/internal/gitaly/service/repository/backup_custom_hooks_test.go +++ b/internal/gitaly/service/repository/backup_custom_hooks_test.go @@ -5,7 +5,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -31,7 +30,7 @@ func TestSuccessfullBackupCustomHooksRequest(t *testing.T) { } require.NoError(t, os.Mkdir(filepath.Join(repoPath, "custom_hooks"), 0o700), "Could not create custom_hooks dir") for _, fileName := range expectedTarResponse[1:] { - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, fileName), []byte("Some hooks"), 0o700), fmt.Sprintf("Could not create %s", fileName)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, fileName), []byte("Some hooks"), 0o700), fmt.Sprintf("Could not create %s", fileName)) } backupRequest := &gitalypb.BackupCustomHooksRequest{Repository: repo} diff --git a/internal/gitaly/service/repository/cleanup.go b/internal/gitaly/service/repository/cleanup.go index 060dd7215..c1302053f 100644 --- a/internal/gitaly/service/repository/cleanup.go +++ b/internal/gitaly/service/repository/cleanup.go @@ -1,5 +1,6 @@ package repository +//nolint:depguard import ( "bytes" "context" diff --git a/internal/gitaly/service/repository/config_test.go b/internal/gitaly/service/repository/config_test.go index 62739da74..817ff9535 100644 --- a/internal/gitaly/service/repository/config_test.go +++ b/internal/gitaly/service/repository/config_test.go @@ -4,7 +4,7 @@ import ( "bufio" "bytes" "context" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -54,7 +54,7 @@ func TestGetConfig(t *testing.T) { return bytes, err }) - contents, err := ioutil.ReadAll(reader) + contents, err := io.ReadAll(reader) return string(contents), err } diff --git a/internal/gitaly/service/repository/create_bundle_from_ref_list_test.go b/internal/gitaly/service/repository/create_bundle_from_ref_list_test.go index ce98a674b..2174d891d 100644 --- a/internal/gitaly/service/repository/create_bundle_from_ref_list_test.go +++ b/internal/gitaly/service/repository/create_bundle_from_ref_list_test.go @@ -3,7 +3,6 @@ package repository import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -56,7 +55,7 @@ func TestCreateBundleFromRefList_success(t *testing.T) { return response.GetData(), err }) - bundle, err := ioutil.TempFile("", "bundle") + bundle, err := os.CreateTemp("", "bundle") require.NoError(t, err) defer func() { require.NoError(t, os.Remove(bundle.Name())) }() diff --git a/internal/gitaly/service/repository/create_bundle_test.go b/internal/gitaly/service/repository/create_bundle_test.go index cfa629305..f615c9775 100644 --- a/internal/gitaly/service/repository/create_bundle_test.go +++ b/internal/gitaly/service/repository/create_bundle_test.go @@ -2,7 +2,6 @@ package repository import ( "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -49,7 +48,7 @@ func TestSuccessfulCreateBundleRequest(t *testing.T) { dstDir, err := tempdir.New(ctx, repo.GetStorageName(), config.NewLocator(cfg)) require.NoError(t, err) - dstFile, err := ioutil.TempFile(dstDir.Path(), "") + dstFile, err := os.CreateTemp(dstDir.Path(), "") require.NoError(t, err) defer dstFile.Close() defer func() { require.NoError(t, os.RemoveAll(dstFile.Name())) }() diff --git a/internal/gitaly/service/repository/create_from_url_test.go b/internal/gitaly/service/repository/create_from_url_test.go index 9aae68ca7..527ccea07 100644 --- a/internal/gitaly/service/repository/create_from_url_test.go +++ b/internal/gitaly/service/repository/create_from_url_test.go @@ -3,7 +3,6 @@ package repository import ( "encoding/base64" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -118,7 +117,7 @@ func TestFailedCreateRepositoryFromURLRequestDueToExistingTarget(t *testing.T) { if testCase.isDir { require.NoError(t, os.MkdirAll(importedRepoPath, 0o770)) } else { - require.NoError(t, ioutil.WriteFile(importedRepoPath, nil, 0o644)) + require.NoError(t, os.WriteFile(importedRepoPath, nil, 0o644)) } t.Cleanup(func() { require.NoError(t, os.RemoveAll(importedRepoPath)) }) diff --git a/internal/gitaly/service/repository/fork_test.go b/internal/gitaly/service/repository/fork_test.go index 7ec027588..dba63ffa2 100644 --- a/internal/gitaly/service/repository/fork_test.go +++ b/internal/gitaly/service/repository/fork_test.go @@ -3,7 +3,6 @@ package repository import ( "crypto/tls" "crypto/x509" - "io/ioutil" "os" "path/filepath" "testing" @@ -174,13 +173,13 @@ func TestFailedCreateForkRequestDueToExistingTarget(t *testing.T) { if testCase.isDir { require.NoError(t, os.MkdirAll(forkedRepoPath, 0o770)) - require.NoError(t, ioutil.WriteFile( + require.NoError(t, os.WriteFile( filepath.Join(forkedRepoPath, "config"), nil, 0o644, )) } else { - require.NoError(t, ioutil.WriteFile(forkedRepoPath, nil, 0o644)) + require.NoError(t, os.WriteFile(forkedRepoPath, nil, 0o644)) } defer func() { require.NoError(t, os.RemoveAll(forkedRepoPath)) }() diff --git a/internal/gitaly/service/repository/gc.go b/internal/gitaly/service/repository/gc.go index dda5f71a9..3dd03b143 100644 --- a/internal/gitaly/service/repository/gc.go +++ b/internal/gitaly/service/repository/gc.go @@ -1,5 +1,6 @@ package repository +//nolint:depguard import ( "context" "errors" diff --git a/internal/gitaly/service/repository/gc_test.go b/internal/gitaly/service/repository/gc_test.go index 4ab776502..35727167c 100644 --- a/internal/gitaly/service/repository/gc_test.go +++ b/internal/gitaly/service/repository/gc_test.go @@ -3,7 +3,6 @@ package repository import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -434,11 +433,11 @@ func TestCleanupInvalidKeepAroundRefs(t *testing.T) { // Create an invalid ref that should should be removed with the testcase bogusSha := "b3f5e4adf6277b571b7943a4f0405a6dd7ee7e15" bogusPath := filepath.Join(repoPath, fmt.Sprintf("refs/keep-around/%s", bogusSha)) - require.NoError(t, ioutil.WriteFile(bogusPath, []byte(bogusSha), 0o644)) + require.NoError(t, os.WriteFile(bogusPath, []byte(bogusSha), 0o644)) // Creating the keeparound without using git so we can create invalid ones in testcases refPath := filepath.Join(repoPath, fmt.Sprintf("refs/keep-around/%s", testcase.refName)) - require.NoError(t, ioutil.WriteFile(refPath, []byte(testcase.refContent), 0o644)) + require.NoError(t, os.WriteFile(refPath, []byte(testcase.refContent), 0o644)) // Perform the request req := &gitalypb.GarbageCollectRequest{Repository: repo} @@ -467,7 +466,7 @@ func mustCreateFileWithTimes(t testing.TB, path string, mTime time.Time) { t.Helper() require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - require.NoError(t, ioutil.WriteFile(path, nil, 0o644)) + require.NoError(t, os.WriteFile(path, nil, 0o644)) require.NoError(t, os.Chtimes(path, mTime, mTime)) } diff --git a/internal/gitaly/service/repository/info_attributes_test.go b/internal/gitaly/service/repository/info_attributes_test.go index 429a2079a..05aece572 100644 --- a/internal/gitaly/service/repository/info_attributes_test.go +++ b/internal/gitaly/service/repository/info_attributes_test.go @@ -2,7 +2,7 @@ package repository import ( "bytes" - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -23,7 +23,7 @@ func TestGetInfoAttributesExisting(t *testing.T) { buffSize := streamio.WriteBufferSize + 1 data := bytes.Repeat([]byte("*.pbxproj binary\n"), buffSize) attrsPath := filepath.Join(infoPath, "attributes") - err := ioutil.WriteFile(attrsPath, data, 0o644) + err := os.WriteFile(attrsPath, data, 0o644) require.NoError(t, err) request := &gitalypb.GetInfoAttributesRequest{Repository: repo} @@ -33,7 +33,7 @@ func TestGetInfoAttributesExisting(t *testing.T) { stream, err := client.GetInfoAttributes(testCtx, request) require.NoError(t, err) - receivedData, err := ioutil.ReadAll(streamio.NewReader(func() ([]byte, error) { + receivedData, err := io.ReadAll(streamio.NewReader(func() ([]byte, error) { response, err := stream.Recv() return response.GetAttributes(), err })) diff --git a/internal/gitaly/service/repository/merge_base.go b/internal/gitaly/service/repository/merge_base.go index 07f284cdd..52653d150 100644 --- a/internal/gitaly/service/repository/merge_base.go +++ b/internal/gitaly/service/repository/merge_base.go @@ -2,7 +2,7 @@ package repository import ( "context" - "io/ioutil" + "io" "gitlab.com/gitlab-org/gitaly/v14/internal/git" "gitlab.com/gitlab-org/gitaly/v14/internal/helper/text" @@ -34,7 +34,7 @@ func (s *server) FindMergeBase(ctx context.Context, req *gitalypb.FindMergeBaseR return nil, status.Errorf(codes.Internal, "FindMergeBase: cmd: %v", err) } - mergeBase, err := ioutil.ReadAll(cmd) + mergeBase, err := io.ReadAll(cmd) if err != nil { return nil, err } diff --git a/internal/gitaly/service/repository/midx_test.go b/internal/gitaly/service/repository/midx_test.go index c4ab36abe..3780c8549 100644 --- a/internal/gitaly/service/repository/midx_test.go +++ b/internal/gitaly/service/repository/midx_test.go @@ -3,7 +3,6 @@ package repository import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -66,7 +65,7 @@ func TestMidxRewrite(t *testing.T) { // Create an invalid multi-pack-index file // with mtime update being the basis for comparison - require.NoError(t, ioutil.WriteFile(midxPath, nil, 0o644)) + require.NoError(t, os.WriteFile(midxPath, nil, 0o644)) require.NoError(t, os.Chtimes(midxPath, time.Time{}, time.Time{})) info, err := os.Stat(midxPath) require.NoError(t, err) diff --git a/internal/gitaly/service/repository/replicate_test.go b/internal/gitaly/service/repository/replicate_test.go index 0f3ccbd07..5c07ccb11 100644 --- a/internal/gitaly/service/repository/replicate_test.go +++ b/internal/gitaly/service/repository/replicate_test.go @@ -3,7 +3,6 @@ package repository import ( "bytes" "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -50,7 +49,7 @@ func TestReplicateRepository(t *testing.T) { // write info attributes attrFilePath := filepath.Join(repoPath, "info", "attributes") attrData := []byte("*.pbxproj binary\n") - require.NoError(t, ioutil.WriteFile(attrFilePath, attrData, 0o644)) + require.NoError(t, os.WriteFile(attrFilePath, attrData, 0o644)) // Write a modified gitconfig gittest.Exec(t, cfg, "-C", repoPath, "config", "please.replicate", "me") diff --git a/internal/gitaly/service/repository/search_files_test.go b/internal/gitaly/service/repository/search_files_test.go index d3716ee07..096485610 100644 --- a/internal/gitaly/service/repository/search_files_test.go +++ b/internal/gitaly/service/repository/search_files_test.go @@ -4,7 +4,7 @@ import ( "bytes" "fmt" "io" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -181,7 +181,7 @@ func TestSearchFilesByContentLargeFile(t *testing.T) { for _, largeFile := range largeFiles { t.Run(largeFile.filename, func(t *testing.T) { - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, largeFile.filename), bytes.Repeat([]byte(largeFile.line), largeFile.repeated), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, largeFile.filename), bytes.Repeat([]byte(largeFile.line), largeFile.repeated), 0o644)) gittest.Exec(t, cfg, "-C", repoPath, "add", ".") gittest.Exec(t, cfg, "-C", repoPath, "-c", fmt.Sprintf("user.name=%s", committerName), diff --git a/internal/gitaly/service/repository/size.go b/internal/gitaly/service/repository/size.go index 8036b4b78..dc4e500dc 100644 --- a/internal/gitaly/service/repository/size.go +++ b/internal/gitaly/service/repository/size.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "os/exec" "strconv" @@ -38,7 +38,7 @@ func getPathSize(ctx context.Context, path string) int64 { return 0 } - sizeLine, err := ioutil.ReadAll(cmd) + sizeLine, err := io.ReadAll(cmd) if err != nil { ctxlogrus.Extract(ctx).WithError(err).Warn("ignoring command read error") return 0 diff --git a/internal/gitaly/service/repository/snapshot_test.go b/internal/gitaly/service/repository/snapshot_test.go index a6e2be7a7..973eb93b6 100644 --- a/internal/gitaly/service/repository/snapshot_test.go +++ b/internal/gitaly/service/repository/snapshot_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net/http/httptest" "os" "os/exec" @@ -49,7 +48,7 @@ func getSnapshot(client gitalypb.RepositoryServiceClient, req *gitalypb.GetSnaps func touch(t *testing.T, format string, args ...interface{}) { path := fmt.Sprintf(format, args...) - require.NoError(t, ioutil.WriteFile(path, nil, 0o644)) + require.NoError(t, os.WriteFile(path, nil, 0o644)) } func TestGetSnapshotSuccess(t *testing.T) { @@ -144,7 +143,7 @@ func TestGetSnapshotWithDedupe(t *testing.T) { // write alternates file to point to alt objects folder alternatesPath, err := locator.InfoAlternatesPath(repoProto) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(alternatesPath, []byte(filepath.Join(repoPath, ".git", fmt.Sprintf("%s\n", alternateObjDir))), 0o644)) + require.NoError(t, os.WriteFile(alternatesPath, []byte(filepath.Join(repoPath, ".git", fmt.Sprintf("%s\n", alternateObjDir))), 0o644)) // write another commit and ensure we can find it cmd = exec.Command(cfg.Git.BinPath, "-C", repoPath, @@ -182,7 +181,7 @@ func TestGetSnapshotWithDedupeSoftFailures(t *testing.T) { alternateObjPath := filepath.Join(repoPath, ".git", alternateObjDir) alternatesPath, err := locator.InfoAlternatesPath(testRepo) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(alternatesPath, []byte(fmt.Sprintf("%s\n", alternateObjPath)), 0o644)) + require.NoError(t, os.WriteFile(alternatesPath, []byte(fmt.Sprintf("%s\n", alternateObjPath)), 0o644)) req := &gitalypb.GetSnapshotRequest{Repository: testRepo} _, err = getSnapshot(client, req) @@ -192,14 +191,14 @@ func TestGetSnapshotWithDedupeSoftFailures(t *testing.T) { // write alternates file to point outside storage root storageRoot, err := locator.GetStorageByName(testRepo.GetStorageName()) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(alternatesPath, []byte(filepath.Join(storageRoot, "..")), 0o600)) + require.NoError(t, os.WriteFile(alternatesPath, []byte(filepath.Join(storageRoot, "..")), 0o600)) _, err = getSnapshot(client, &gitalypb.GetSnapshotRequest{Repository: testRepo}) assert.NoError(t, err) require.NoError(t, os.Remove(alternatesPath)) // write alternates file with bad permissions - require.NoError(t, ioutil.WriteFile(alternatesPath, []byte(fmt.Sprintf("%s\n", alternateObjPath)), 0o000)) + require.NoError(t, os.WriteFile(alternatesPath, []byte(fmt.Sprintf("%s\n", alternateObjPath)), 0o000)) _, err = getSnapshot(client, req) assert.NoError(t, err) require.NoError(t, os.Remove(alternatesPath)) @@ -216,7 +215,7 @@ func TestGetSnapshotWithDedupeSoftFailures(t *testing.T) { commitSha := gittest.CreateCommitInAlternateObjectDirectory(t, cfg.Git.BinPath, repoPath, alternateObjDir, cmd) originalAlternatesCommit := string(commitSha) - require.NoError(t, ioutil.WriteFile(alternatesPath, []byte(alternateObjPath), 0o644)) + require.NoError(t, os.WriteFile(alternatesPath, []byte(alternateObjPath), 0o644)) _, repoCopyPath := copyRepoUsingSnapshot(t, cfg, client, testRepo) diff --git a/internal/gitaly/service/server/info.go b/internal/gitaly/service/server/info.go index 509e9e70a..11ade3b35 100644 --- a/internal/gitaly/service/server/info.go +++ b/internal/gitaly/service/server/info.go @@ -2,7 +2,6 @@ package server import ( "context" - "io/ioutil" "os" "path/filepath" @@ -57,7 +56,7 @@ func shardCheck(shardPath string) (readable bool, writeable bool) { testPath := filepath.Join(shardPath, "+testWrite") content := []byte("testWrite") - if err := ioutil.WriteFile(testPath, content, 0o644); err == nil { + if err := os.WriteFile(testPath, content, 0o644); err == nil { writeable = true } _ = os.Remove(testPath) diff --git a/internal/gitaly/service/smarthttp/cache.go b/internal/gitaly/service/smarthttp/cache.go index 9857e3741..5531d0236 100644 --- a/internal/gitaly/service/smarthttp/cache.go +++ b/internal/gitaly/service/smarthttp/cache.go @@ -3,7 +3,6 @@ package smarthttp import ( "context" "io" - "io/ioutil" "sync" "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus" @@ -92,7 +91,7 @@ func (c infoRefCache) tryCache(ctx context.Context, in *gitalypb.InfoRefsRequest // discard remaining bytes if caching stream // failed so that tee reader is not blocked - _, err = io.Copy(ioutil.Discard, tr) + _, err = io.Copy(io.Discard, tr) if err != nil { logger.WithError(err). Error("unable to discard remaining InfoRefsUploadPack cache stream") diff --git a/internal/gitaly/service/smarthttp/inforefs_test.go b/internal/gitaly/service/smarthttp/inforefs_test.go index 8a2244d83..1746aca5d 100644 --- a/internal/gitaly/service/smarthttp/inforefs_test.go +++ b/internal/gitaly/service/smarthttp/inforefs_test.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -151,7 +150,7 @@ func makeInfoRefsUploadPackRequest(ctx context.Context, t *testing.T, serverSock c, err := client.InfoRefsUploadPack(ctx, rpcRequest) require.NoError(t, err) - response, err := ioutil.ReadAll(streamio.NewReader(func() ([]byte, error) { + response, err := io.ReadAll(streamio.NewReader(func() ([]byte, error) { resp, err := c.Recv() return resp.GetData(), err })) @@ -254,7 +253,7 @@ func makeInfoRefsReceivePackRequest(ctx context.Context, t *testing.T, serverSoc c, err := client.InfoRefsReceivePack(ctx, rpcRequest) require.NoError(t, err) - response, err := ioutil.ReadAll(streamio.NewReader(func() ([]byte, error) { + response, err := io.ReadAll(streamio.NewReader(func() ([]byte, error) { resp, err := c.Recv() return resp.GetData(), err })) @@ -400,7 +399,7 @@ func createInvalidRepo(t testing.TB, repoDir string) func() { func replaceCachedResponse(t testing.TB, ctx context.Context, cache *cache.DiskCache, req *gitalypb.InfoRefsRequest, newContents string) { path := pathToCachedResponse(t, ctx, cache, req) - require.NoError(t, ioutil.WriteFile(path, []byte(newContents), 0o644)) + require.NoError(t, os.WriteFile(path, []byte(newContents), 0o644)) } func setInfoRefsUploadPackMethod(ctx context.Context) context.Context { diff --git a/internal/gitaly/service/smarthttp/receive_pack_test.go b/internal/gitaly/service/smarthttp/receive_pack_test.go index 1146958e2..d84eee94f 100644 --- a/internal/gitaly/service/smarthttp/receive_pack_test.go +++ b/internal/gitaly/service/smarthttp/receive_pack_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -214,7 +213,7 @@ func TestFailedReceivePackRequestDueToHooksFailure(t *testing.T) { require.NoError(t, os.MkdirAll(hooks.Path(cfg), 0o755)) hookContent := []byte("#!/bin/sh\nexit 1") - require.NoError(t, ioutil.WriteFile(filepath.Join(hooks.Path(cfg), "pre-receive"), hookContent, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(hooks.Path(cfg), "pre-receive"), hookContent, 0o755)) serverSocketPath := runSmartHTTPServer(t, cfg) @@ -306,7 +305,7 @@ func createCommit(t *testing.T, cfg config.Cfg, repoPath string, fileContents [] oldHead = text.ChompBytes(gittest.Exec(t, cfg, "-C", repoPath, "rev-parse", "master")) changedFile := "README.md" - require.NoError(t, ioutil.WriteFile(filepath.Join(repoPath, changedFile), fileContents, 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(repoPath, changedFile), fileContents, 0o644)) gittest.Exec(t, cfg, "-C", repoPath, "add", changedFile) gittest.Exec(t, cfg, "-C", repoPath, diff --git a/internal/gitaly/service/ssh/receive_pack_test.go b/internal/gitaly/service/ssh/receive_pack_test.go index 6e89f5978..db17db5d0 100644 --- a/internal/gitaly/service/ssh/receive_pack_test.go +++ b/internal/gitaly/service/ssh/receive_pack_test.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -216,7 +215,7 @@ func TestReceivePackPushHookFailure(t *testing.T) { require.NoError(t, os.MkdirAll(hooks.Path(cfg), 0o755)) hookContent := []byte("#!/bin/sh\nexit 1") - require.NoError(t, ioutil.WriteFile(filepath.Join(hooks.Path(cfg), "pre-receive"), hookContent, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(hooks.Path(cfg), "pre-receive"), hookContent, 0o755)) _, _, err := testCloneAndPush(t, cfg, cfg.Storages[0].Path, serverSocketPath, repo, pushParams{storageName: cfg.Storages[0].Name, glID: "1"}) require.Error(t, err) @@ -642,7 +641,7 @@ func makeCommit(t *testing.T, cfg config.Cfg, localRepoPath string) ([]byte, []b newFilePath := localRepoPath + "/foo.txt" // Create a tiny file and add it to the index - require.NoError(t, ioutil.WriteFile(newFilePath, []byte("foo bar"), 0o644)) + require.NoError(t, os.WriteFile(newFilePath, []byte("foo bar"), 0o644)) gittest.Exec(t, cfg, "-C", localRepoPath, "add", ".") // The latest commit ID on the remote repo diff --git a/internal/gitaly/service/wiki/testhelper_test.go b/internal/gitaly/service/wiki/testhelper_test.go index 6865dd18a..9302d6b14 100644 --- a/internal/gitaly/service/wiki/testhelper_test.go +++ b/internal/gitaly/service/wiki/testhelper_test.go @@ -2,7 +2,6 @@ package wiki import ( "bytes" - "io/ioutil" "os" "reflect" "runtime" @@ -43,7 +42,7 @@ func testMain(m *testing.M) int { cleanup := testhelper.Configure() defer cleanup() - tempDir, err := ioutil.TempDir("", "gitaly") + tempDir, err := os.MkdirTemp("", "gitaly") if err != nil { log.Error(err) return 1 diff --git a/internal/gitaly/storage/metadata_test.go b/internal/gitaly/storage/metadata_test.go index 82bd7caa1..a70846045 100644 --- a/internal/gitaly/storage/metadata_test.go +++ b/internal/gitaly/storage/metadata_test.go @@ -2,7 +2,6 @@ package storage import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "testing" @@ -23,7 +22,7 @@ func readFilesystemID(t *testing.T, path string) string { } func TestWriteMetdataFile(t *testing.T) { - tempDir, err := ioutil.TempDir("", t.Name()) + tempDir, err := os.MkdirTemp("", t.Name()) require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(tempDir)) @@ -34,7 +33,7 @@ func TestWriteMetdataFile(t *testing.T) { } func TestWriteMetadataFile_AlreadyExists(t *testing.T) { - tempDir, err := ioutil.TempDir("", t.Name()) + tempDir, err := os.MkdirTemp("", t.Name()) require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(tempDir)) diff --git a/internal/gitaly/transaction/voting_test.go b/internal/gitaly/transaction/voting_test.go index 8912a3032..434c9374e 100644 --- a/internal/gitaly/transaction/voting_test.go +++ b/internal/gitaly/transaction/voting_test.go @@ -3,7 +3,7 @@ package transaction import ( "context" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -198,7 +198,7 @@ func TestCommitLockedFile(t *testing.T) { VoteFn: func(context.Context, txinfo.Transaction, voting.Vote) error { // This shouldn't typically happen given that the file is locked, // but we concurrently update the file after our first vote. - require.NoError(t, ioutil.WriteFile(file, []byte("something"), + require.NoError(t, os.WriteFile(file, []byte("something"), 0o666)) return nil }, diff --git a/internal/gitlab/http_client.go b/internal/gitlab/http_client.go index 3395d1c7a..919365453 100644 --- a/internal/gitlab/http_client.go +++ b/internal/gitlab/http_client.go @@ -5,10 +5,10 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "mime" "net/http" "net/url" + "os" "regexp" "strings" @@ -64,7 +64,7 @@ func NewHTTPClient( return nil, fmt.Errorf("%s is not a valid url", gitlabCfg.URL) } - secret, err := ioutil.ReadFile(gitlabCfg.SecretFile) + secret, err := os.ReadFile(gitlabCfg.SecretFile) if err != nil { return nil, fmt.Errorf("reading secret file: %w", err) } @@ -297,7 +297,7 @@ func (c *HTTPClient) Check(ctx context.Context) (*CheckInfo, error) { } func (c *HTTPClient) finalizeResponse(resp *http.Response) { - if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { + if _, err := io.Copy(io.Discard, resp.Body); err != nil { c.logger.WithError(err).Errorf("discard body error for the request %q", resp.Request.RequestURI) } if err := resp.Body.Close(); err != nil { diff --git a/internal/gitlab/test_server.go b/internal/gitlab/test_server.go index 2bda68301..7de3fc7ae 100644 --- a/internal/gitlab/test_server.go +++ b/internal/gitlab/test_server.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -31,7 +30,7 @@ func WriteShellSecretFile(t testing.TB, dir, secretToken string) string { require.NoError(t, os.MkdirAll(dir, os.ModeDir)) filePath := filepath.Join(dir, ".gitlab_shell_secret") - require.NoError(t, ioutil.WriteFile(filePath, []byte(secretToken), 0o644)) + require.NoError(t, os.WriteFile(filePath, []byte(secretToken), 0o644)) return filePath } @@ -74,7 +73,7 @@ func NewTestServer(t testing.TB, options TestServerOptions) (url string, cleanup var tlsCfg *tls.Config if options.ClientCACertPath != "" { - caCertPEM, err := ioutil.ReadFile(options.ClientCACertPath) + caCertPEM, err := os.ReadFile(options.ClientCACertPath) require.NoError(t, err) certPool := x509.NewCertPool() diff --git a/internal/listenmux/mux.go b/internal/listenmux/mux.go index ad1f468a6..f5a1ed67a 100644 --- a/internal/listenmux/mux.go +++ b/internal/listenmux/mux.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net" "google.golang.org/grpc/credentials" @@ -73,7 +72,7 @@ func (m *Mux) ServerHandshake(conn net.Conn) (net.Conn, credentials.AuthInfo, er return nil, nil, fmt.Errorf("wrapped server handshake: %w", err) } - peeked, err := ioutil.ReadAll(io.LimitReader(conn, magicLen)) + peeked, err := io.ReadAll(io.LimitReader(conn, magicLen)) if err != nil { return nil, nil, fmt.Errorf("peek network stream: %w", err) } diff --git a/internal/listenmux/mux_test.go b/internal/listenmux/mux_test.go index 905329fbe..4ab8c488a 100644 --- a/internal/listenmux/mux_test.go +++ b/internal/listenmux/mux_test.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "net" "syscall" @@ -253,7 +252,7 @@ func TestMux_concurrency(t *testing.T) { return err } - out, err := ioutil.ReadAll(c) + out, err := io.ReadAll(c) if err != nil { return err } diff --git a/internal/log/hook.go b/internal/log/hook.go index 3ad214401..d9a995f3e 100644 --- a/internal/log/hook.go +++ b/internal/log/hook.go @@ -2,7 +2,7 @@ package log import ( "fmt" - "io/ioutil" + "io" "os" "path/filepath" @@ -20,13 +20,13 @@ func NewHookLogger() *HookLogger { logDir := os.Getenv(GitalyLogDirEnvKey) if logDir == "" { - logger.SetOutput(ioutil.Discard) + logger.SetOutput(io.Discard) return &HookLogger{logger: logger} } logFile, err := os.OpenFile(filepath.Join(logDir, "gitaly_hooks.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { - logger.SetOutput(ioutil.Discard) + logger.SetOutput(io.Discard) } else { logger.SetOutput(logFile) } diff --git a/internal/logsanitizer/url_test.go b/internal/logsanitizer/url_test.go index 8e827ea10..ae9eee5ea 100644 --- a/internal/logsanitizer/url_test.go +++ b/internal/logsanitizer/url_test.go @@ -3,7 +3,7 @@ package logsanitizer import ( "bytes" "fmt" - "io/ioutil" + "io" "testing" log "github.com/sirupsen/logrus" @@ -101,7 +101,7 @@ func BenchmarkUrlSanitizerWithoutSanitization(b *testing.B) { urlSanitizer := NewURLSanitizerHook() logger := log.New() - logger.Out = ioutil.Discard + logger.Out = io.Discard logger.Hooks.Add(urlSanitizer) benchmarkLogging(logger, b) @@ -115,7 +115,7 @@ func BenchmarkUrlSanitizerWithSanitization(b *testing.B) { ) logger := log.New() - logger.Out = ioutil.Discard + logger.Out = io.Discard logger.Hooks.Add(urlSanitizer) benchmarkLogging(logger, b) diff --git a/internal/middleware/featureflag/featureflag_handler_test.go b/internal/middleware/featureflag/featureflag_handler_test.go index fdca12319..36fde745f 100644 --- a/internal/middleware/featureflag/featureflag_handler_test.go +++ b/internal/middleware/featureflag/featureflag_handler_test.go @@ -2,7 +2,7 @@ package featureflag import ( "context" - "io/ioutil" + "io" "testing" grpcmw "github.com/grpc-ecosystem/go-grpc-middleware" @@ -73,7 +73,7 @@ func setup() (context.Context, *test.Hook) { func setupContext() (context.Context, *test.Hook) { ctx := context.Background() logger := logrus.New() - logger.SetOutput(ioutil.Discard) + logger.SetOutput(io.Discard) hook := test.NewLocal(logger) ctx = ctxlogrus.ToContext(ctx, logrus.NewEntry(logger)) diff --git a/internal/praefect/config/config.go b/internal/praefect/config/config.go index 6dc66b2b7..60899deb3 100644 --- a/internal/praefect/config/config.go +++ b/internal/praefect/config/config.go @@ -3,7 +3,7 @@ package config import ( "errors" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -146,7 +146,7 @@ type VirtualStorage struct { // FromFile loads the config for the passed file path func FromFile(filePath string) (Config, error) { - b, err := ioutil.ReadFile(filePath) + b, err := os.ReadFile(filePath) if err != nil { return Config{}, err } diff --git a/internal/praefect/coordinator_test.go b/internal/praefect/coordinator_test.go index c87f5c455..35e4b54a5 100644 --- a/internal/praefect/coordinator_test.go +++ b/internal/praefect/coordinator_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "math/rand" "strconv" "strings" @@ -56,7 +56,7 @@ import ( var testLogger = logrus.New() func init() { - testLogger.SetOutput(ioutil.Discard) + testLogger.SetOutput(io.Discard) } func TestSecondaryRotation(t *testing.T) { diff --git a/internal/praefect/datastore/glsql/testing.go b/internal/praefect/datastore/glsql/testing.go index d1cc2806e..bb9430b1f 100644 --- a/internal/praefect/datastore/glsql/testing.go +++ b/internal/praefect/datastore/glsql/testing.go @@ -3,6 +3,7 @@ package glsql import ( "database/sql" "errors" + "net" "os" "os/exec" "strconv" @@ -268,11 +269,7 @@ func initPraefectTestDB(t testing.TB, database string) *sql.DB { dbCfg.DBName = database praefectTestDB := requireSQLOpen(t, dbCfg, false) t.Cleanup(func() { - // This could should replace current implementation after drop support of Go 1.15 - //if err := praefectTestDB.Close(); !errors.Is(err, net.ErrClosed) { - // require.NoErrorf(t, err, "release connection to the %q database", dbCfg.DBName) - //} - if err := praefectTestDB.Close(); err != nil && !strings.Contains(err.Error(), "use of closed network connection") { + if err := praefectTestDB.Close(); !errors.Is(err, net.ErrClosed) { require.NoErrorf(t, err, "release connection to the %q database", dbCfg.DBName) } }) diff --git a/internal/safe/file_writer.go b/internal/safe/file_writer.go index 49d7903d8..0a2f1eb12 100644 --- a/internal/safe/file_writer.go +++ b/internal/safe/file_writer.go @@ -3,7 +3,6 @@ package safe import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sync" @@ -42,7 +41,7 @@ func NewFileWriter(path string, optionalCfg ...FileWriterConfig) (*FileWriter, e directory := filepath.Dir(path) - tmpFile, err := ioutil.TempFile(directory, filepath.Base(path)) + tmpFile, err := os.CreateTemp(directory, filepath.Base(path)) if err != nil { return nil, err } diff --git a/internal/safe/file_writer_test.go b/internal/safe/file_writer_test.go index d6c83ab03..c31420a7f 100644 --- a/internal/safe/file_writer_test.go +++ b/internal/safe/file_writer_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sync" @@ -33,7 +32,7 @@ func TestFileWriter_successful(t *testing.T) { writtenContents := testhelper.MustReadFile(t, filePath) require.Equal(t, fileContents, string(writtenContents)) - filesInTempDir, err := ioutil.ReadDir(dir) + filesInTempDir, err := os.ReadDir(dir) require.NoError(t, err) require.Len(t, filesInTempDir, 1) require.Equal(t, filepath.Base(filePath), filesInTempDir[0].Name()) @@ -49,7 +48,7 @@ func TestFileWriter_mode(t *testing.T) { dir := testhelper.TempDir(t) target := filepath.Join(dir, "file") - require.NoError(t, ioutil.WriteFile(target, []byte("contents"), 0o600)) + require.NoError(t, os.WriteFile(target, []byte("contents"), 0o600)) writer, err := safe.NewFileWriter(target, safe.FileWriterConfig{ FileMode: 0o060, @@ -83,7 +82,7 @@ func TestFileWriter_race(t *testing.T) { wg.Wait() require.FileExists(t, filePath) - filesInTempDir, err := ioutil.ReadDir(dir) + filesInTempDir, err := os.ReadDir(dir) require.NoError(t, err) require.Len(t, filesInTempDir, 1, "make sure no other files were written") } @@ -128,7 +127,7 @@ func TestFileWriter_commitBeforeClose(t *testing.T) { } func dirEmpty(t testing.TB, dirPath string) bool { - infos, err := ioutil.ReadDir(dirPath) + infos, err := os.ReadDir(dirPath) require.NoError(t, err) return len(infos) == 0 } diff --git a/internal/safe/locking_file_writer_test.go b/internal/safe/locking_file_writer_test.go index bf813a2d3..152c63d94 100644 --- a/internal/safe/locking_file_writer_test.go +++ b/internal/safe/locking_file_writer_test.go @@ -2,7 +2,6 @@ package safe_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -148,7 +147,7 @@ func TestLockingFileWriter_seedingWithExistingTarget(t *testing.T) { t.Parallel() target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("seed"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("seed"), 0o644)) writer, err := safe.NewLockingFileWriter(target, safe.LockingFileWriterConfig{ SeedContents: true, @@ -166,7 +165,7 @@ func TestLockingFileWriter_modifiesExistingFiles(t *testing.T) { t.Parallel() target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("preexisting"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("preexisting"), 0o644)) writer, err := safe.NewLockingFileWriter(target) require.NoError(t, err) @@ -182,7 +181,7 @@ func TestLockingFileWriter_modifiesExistingFilesWithMode(t *testing.T) { t.Parallel() target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("preexisting"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("preexisting"), 0o644)) writer, err := safe.NewLockingFileWriter(target, safe.LockingFileWriterConfig{ FileWriterConfig: safe.FileWriterConfig{FileMode: 0o060}, @@ -205,7 +204,7 @@ func TestLockingFileWriter_concurrentCreation(t *testing.T) { require.NoError(t, err) // Create file concurrently. - require.NoError(t, ioutil.WriteFile(target, []byte("concurrent"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("concurrent"), 0o644)) require.Equal(t, fmt.Errorf("file concurrently created"), writer.Lock()) @@ -217,7 +216,7 @@ func TestLockingFileWriter_concurrentDeletion(t *testing.T) { target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("base"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("base"), 0o644)) writer, err := safe.NewLockingFileWriter(target) require.NoError(t, err) @@ -234,12 +233,12 @@ func TestLockingFileWriter_concurrentModification(t *testing.T) { target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("base"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("base"), 0o644)) writer, err := safe.NewLockingFileWriter(target) require.NoError(t, err) // Concurrently modify the file. - require.NoError(t, ioutil.WriteFile(target, []byte("concurrent"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("concurrent"), 0o644)) require.Equal(t, fmt.Errorf("file concurrently modified"), writer.Lock()) @@ -272,13 +271,13 @@ func TestLockingFileWriter_locked(t *testing.T) { t.Parallel() target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("base"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("base"), 0o644)) writer, err := safe.NewLockingFileWriter(target) require.NoError(t, err) // Concurrently lock the file. - require.NoError(t, ioutil.WriteFile(target+".lock", nil, 0o644)) + require.NoError(t, os.WriteFile(target+".lock", nil, 0o644)) require.Equal(t, fmt.Errorf("file already locked"), writer.Lock()) @@ -291,7 +290,7 @@ func TestLockingFileWriter_externalProcess(t *testing.T) { cfg := testcfg.Build(t) target := filepath.Join(testhelper.TempDir(t), "file") - require.NoError(t, ioutil.WriteFile(target, []byte("base"), 0o644)) + require.NoError(t, os.WriteFile(target, []byte("base"), 0o644)) writer, err := safe.NewLockingFileWriter(target) require.NoError(t, err) diff --git a/internal/sidechannel/registry_test.go b/internal/sidechannel/registry_test.go index 5b8217e70..07d2f85c1 100644 --- a/internal/sidechannel/registry_test.go +++ b/internal/sidechannel/registry_test.go @@ -2,7 +2,7 @@ package sidechannel import ( "fmt" - "io/ioutil" + "io" "net" "strconv" "sync" @@ -60,7 +60,7 @@ func TestRegistry(t *testing.T) { } for i := 0; i < N; i++ { - out, err := ioutil.ReadAll(servers[i]) + out, err := io.ReadAll(servers[i]) require.NoError(t, err) require.Equal(t, strconv.Itoa(i), string(out)) } diff --git a/internal/sidechannel/sidechannel_test.go b/internal/sidechannel/sidechannel_test.go index bfcd4fa42..c85517952 100644 --- a/internal/sidechannel/sidechannel_test.go +++ b/internal/sidechannel/sidechannel_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "math/rand" "net" "sync" @@ -52,7 +51,7 @@ func TestSidechannel(t *testing.T) { errC := make(chan error, 1) go func() { var err error - out, err = ioutil.ReadAll(conn) + out, err = io.ReadAll(conn) errC <- err }() @@ -118,7 +117,7 @@ func TestSidechannelConcurrency(t *testing.T) { errC := make(chan error, 1) go func() { var err error - outs[i], err = ioutil.ReadAll(conn) + outs[i], err = io.ReadAll(conn) errC <- err }() diff --git a/internal/streamcache/cache_test.go b/internal/streamcache/cache_test.go index a21b726ed..708d09fd9 100644 --- a/internal/streamcache/cache_test.go +++ b/internal/streamcache/cache_test.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -49,7 +48,7 @@ func TestCache_writeOneReadMultiple(t *testing.T) { require.Equal(t, i == 0, created, "all calls except the first one should be cache hits") - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) require.NoError(t, r.Wait(context.Background())) require.Equal(t, content(0), string(out), "expect cache hits for all i > 0") @@ -89,7 +88,7 @@ func TestCache_manyConcurrentWrites(t *testing.T) { } defer r.Close() - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) if err != nil { return err } @@ -166,11 +165,11 @@ func TestCache_deletedFile(t *testing.T) { defer r2.Close() require.True(t, created, "because the first file is gone, cache is forced to create a new entry") - out1, err := ioutil.ReadAll(r1) + out1, err := io.ReadAll(r1) require.NoError(t, err) require.Equal(t, content(1), string(out1), "r1 should still see its original pre-wipe contents") - out2, err := ioutil.ReadAll(r2) + out2, err := io.ReadAll(r2) require.NoError(t, err) require.Equal(t, content(2), string(out2), "r2 should see the new post-wipe contents") } @@ -214,7 +213,7 @@ func TestCache_scope(t *testing.T) { for i := 0; i < N; i++ { r, content := reader[i], input[i] - out, err := ioutil.ReadAll(r) + out, err := io.ReadAll(r) require.NoError(t, err) require.NoError(t, r.Wait(context.Background())) @@ -269,7 +268,7 @@ func TestCache_diskCleanup(t *testing.T) { defer r1.Close() require.True(t, created) - out1, err := ioutil.ReadAll(r1) + out1, err := io.ReadAll(r1) require.NoError(t, err) require.Equal(t, content(1), string(out1)) require.NoError(t, r1.Wait(context.Background())) @@ -292,7 +291,7 @@ func TestCache_diskCleanup(t *testing.T) { defer r2.Close() require.True(t, created) - out2, err := ioutil.ReadAll(r2) + out2, err := io.ReadAll(r2) require.NoError(t, err) require.NoError(t, r2.Wait(context.Background())) @@ -326,7 +325,7 @@ func TestCache_failedWrite(t *testing.T) { require.NoError(t, err) require.True(t, created) - _, err = io.Copy(ioutil.Discard, r1) + _, err = io.Copy(io.Discard, r1) require.NoError(t, err, "errors on the write end are not propagated via Read()") require.NoError(t, r1.Close(), "errors on the write end are not propagated via Close()") require.Error(t, r1.Wait(context.Background()), "error propagation happens via Wait()") @@ -339,7 +338,7 @@ func TestCache_failedWrite(t *testing.T) { defer r2.Close() require.True(t, created, "because the previous entry failed, a new one should have been created") - out, err := ioutil.ReadAll(r2) + out, err := io.ReadAll(r2) require.NoError(t, err) require.NoError(t, r2.Wait(context.Background())) require.Equal(t, happy, string(out)) @@ -377,7 +376,7 @@ func TestCache_unWriteableFile(t *testing.T) { require.NoError(t, err) require.True(t, created) - _, err = ioutil.ReadAll(r) + _, err = io.ReadAll(r) require.NoError(t, err) err = r.Wait(context.Background()) @@ -403,7 +402,7 @@ func TestCache_unCloseableFile(t *testing.T) { require.NoError(t, err) require.True(t, created) - _, err = ioutil.ReadAll(r) + _, err = io.ReadAll(r) require.NoError(t, err) err = r.Wait(context.Background()) @@ -494,7 +493,7 @@ func TestNullCache(t *testing.T) { return errors.New("created should be true") } - output, err := ioutil.ReadAll(s) + output, err := io.ReadAll(s) if err != nil { return err } diff --git a/internal/streamcache/filestore.go b/internal/streamcache/filestore.go index 4fc6a5100..67337c95f 100644 --- a/internal/streamcache/filestore.go +++ b/internal/streamcache/filestore.go @@ -83,7 +83,7 @@ type namedWriteCloser interface { io.WriteCloser } -// Create creates a new tempfile. It does not use ioutil.TempFile because +// Create creates a new tempfile. It does not use os.CreateTemp because // the documentation of TempFile makes no promises about reusing tempfile // names after a file has been deleted. By using a very large (uint64) // counter, Create makes it clear / explicit how unlikely reuse is. diff --git a/internal/streamcache/filestore_test.go b/internal/streamcache/filestore_test.go index f9ff5826a..b5c1f055e 100644 --- a/internal/streamcache/filestore_test.go +++ b/internal/streamcache/filestore_test.go @@ -2,7 +2,6 @@ package streamcache import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -110,7 +109,7 @@ func TestFilestoreCleanwalk(t *testing.T) { file := filepath.Join(dir2, "file") require.NoError(t, os.Mkdir(dir1, 0o755)) require.NoError(t, os.Mkdir(dir2, 0o755)) - require.NoError(t, ioutil.WriteFile(file, nil, 0o644)) + require.NoError(t, os.WriteFile(file, nil, 0o644)) require.NoError(t, os.Chmod(dir2, 0), "create dir with pathological permissions") require.NoError(t, fs.cleanWalk(time.Now().Add(time.Hour))) diff --git a/internal/streamcache/pipe_test.go b/internal/streamcache/pipe_test.go index 87372cfc9..17c73f9fb 100644 --- a/internal/streamcache/pipe_test.go +++ b/internal/streamcache/pipe_test.go @@ -3,8 +3,8 @@ package streamcache import ( "bytes" "io" - "io/ioutil" "math/rand" + "os" "sync" "sync/atomic" "testing" @@ -16,7 +16,7 @@ import ( func createPipe(t *testing.T) (*pipeReader, *pipe) { t.Helper() - f, err := ioutil.TempFile("", "gitaly-streamcache-test") + f, err := os.CreateTemp("", "gitaly-streamcache-test") require.NoError(t, err) pr, p, err := newPipe(f) @@ -98,7 +98,7 @@ func TestPipe_readAfterClose(t *testing.T) { werr := make(chan error, 1) go func() { werr <- writeBytes(p, []byte(input), nil) }() - out1, err := ioutil.ReadAll(pr1) + out1, err := io.ReadAll(pr1) require.NoError(t, err) require.Equal(t, input, string(out1)) @@ -109,7 +109,7 @@ func TestPipe_readAfterClose(t *testing.T) { require.NoError(t, err) defer pr2.Close() - out2, err := ioutil.ReadAll(pr2) + out2, err := io.ReadAll(pr2) require.NoError(t, err) require.Equal(t, input, string(out2)) } @@ -140,7 +140,7 @@ func TestPipe_backpressure(t *testing.T) { time.Sleep(10 * time.Millisecond) require.Equal(t, int64(3), atomic.LoadInt64(&wprogress), "writer should be blocked after having advanced 1 byte") - rest, err := ioutil.ReadAll(pr) + rest, err := io.ReadAll(pr) require.NoError(t, err) output = append(output, rest...) require.Equal(t, input, string(output)) @@ -200,7 +200,7 @@ func (cs *closeSpy) Close() error { // Closing the last reader _before_ closing the writer is a failure // condition. After this happens, opening new readers should fail. func TestPipe_closeWrongOrder(t *testing.T) { - f, err := ioutil.TempFile("", "gitaly-streamcache-test") + f, err := os.CreateTemp("", "gitaly-streamcache-test") require.NoError(t, err) cs := &closeSpy{namedWriteCloser: f} @@ -233,7 +233,7 @@ func TestPipe_closeWrongOrder(t *testing.T) { // Closing last reader after closing the writer is the happy path. After // this happens, opening new readers should work. func TestPipe_closeOrderHappy(t *testing.T) { - f, err := ioutil.TempFile("", "gitaly-streamcache-test") + f, err := os.CreateTemp("", "gitaly-streamcache-test") require.NoError(t, err) cs := &closeSpy{namedWriteCloser: f} @@ -251,7 +251,7 @@ func TestPipe_closeOrderHappy(t *testing.T) { require.NoError(t, p.Close()) require.True(t, cs.closed) - out1, err := ioutil.ReadAll(pr1) + out1, err := io.ReadAll(pr1) require.NoError(t, err) require.Empty(t, out1) @@ -259,7 +259,7 @@ func TestPipe_closeOrderHappy(t *testing.T) { require.NoError(t, err, "opening reader after normal close should succeed") defer pr2.Close() - out2, err := ioutil.ReadAll(pr2) + out2, err := io.ReadAll(pr2) require.NoError(t, err) require.Empty(t, out2) } diff --git a/internal/streamcache/sendfile_test.go b/internal/streamcache/sendfile_test.go index 786c085b4..b349c6331 100644 --- a/internal/streamcache/sendfile_test.go +++ b/internal/streamcache/sendfile_test.go @@ -6,7 +6,6 @@ package streamcache import ( "bytes" "io" - "io/ioutil" "math/rand" "os" "testing" @@ -34,7 +33,7 @@ func TestPipe_WriteTo(t *testing.T) { { desc: "os.File", create: func(t *testing.T) namedWriteCloser { - f, err := ioutil.TempFile("", "pipe write to") + f, err := os.CreateTemp("", "pipe write to") require.NoError(t, err) t.Cleanup(func() { require.NoError(t, os.Remove(f.Name())) }) return f @@ -44,7 +43,7 @@ func TestPipe_WriteTo(t *testing.T) { { desc: "non-file writer", create: func(t *testing.T) namedWriteCloser { - f, err := ioutil.TempFile("", "pipe write to") + f, err := os.CreateTemp("", "pipe write to") require.NoError(t, err) t.Cleanup(func() { require.NoError(t, os.Remove(f.Name())) }) return &wrappedFile{f} @@ -83,7 +82,7 @@ func TestPipe_WriteTo(t *testing.T) { require.NoError(t, outW.Close()) require.NoError(t, <-errC) - outBytes, err := ioutil.ReadFile(outW.Name()) + outBytes, err := os.ReadFile(outW.Name()) require.NoError(t, err) // Don't use require.Equal because we don't want a 10MB error message. require.True(t, bytes.Equal(data, outBytes)) @@ -128,7 +127,7 @@ func TestPipe_WriteTo_EAGAIN(t *testing.T) { }() }() - out, err := ioutil.ReadAll(fr) + out, err := io.ReadAll(fr) require.NoError(t, err) // Don't use require.Equal because we don't want a 10MB error message. require.True(t, bytes.Equal(data, out)) diff --git a/internal/supervisor/supervisor_test.go b/internal/supervisor/supervisor_test.go index d5e071d0c..9e2642d57 100644 --- a/internal/supervisor/supervisor_test.go +++ b/internal/supervisor/supervisor_test.go @@ -2,7 +2,7 @@ package supervisor import ( "context" - "io/ioutil" + "io" "net" "os" "os/exec" @@ -33,7 +33,7 @@ func testMain(m *testing.M) int { defer cleanup() var err error - testDir, err = ioutil.TempDir("", "gitaly-supervisor-test") + testDir, err = os.MkdirTemp("", "gitaly-supervisor-test") if err != nil { log.Error(err) return 1 @@ -188,7 +188,7 @@ func getPid(ctx context.Context, socket string) (int, error) { } defer conn.Close() - response, err := ioutil.ReadAll(conn) + response, err := io.ReadAll(conn) if err != nil { return 0, err } diff --git a/internal/tempdir/clean.go b/internal/tempdir/clean.go index 0bef52c3e..327423225 100644 --- a/internal/tempdir/clean.go +++ b/internal/tempdir/clean.go @@ -1,5 +1,6 @@ package tempdir +//nolint:depguard import ( "context" "fmt" diff --git a/internal/tempdir/clean_test.go b/internal/tempdir/clean_test.go index 890ebeee5..3d3e16c13 100644 --- a/internal/tempdir/clean_test.go +++ b/internal/tempdir/clean_test.go @@ -1,7 +1,7 @@ package tempdir import ( - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -59,7 +59,7 @@ func TestCleanTempDir(t *testing.T) { gittest.CloneRepo(t, cfg, cfg.Storages[0]) logrus.SetLevel(logrus.InfoLevel) - logrus.SetOutput(ioutil.Discard) + logrus.SetOutput(io.Discard) hook := test.NewGlobal() @@ -123,7 +123,7 @@ func assertEntries(t *testing.T, locator storage.Locator, storage config.Storage root, err := locator.TempDir(storage.Name) require.NoError(t, err) - foundEntries, err := ioutil.ReadDir(root) + foundEntries, err := os.ReadDir(root) require.NoError(t, err) require.Len(t, foundEntries, len(entries)) @@ -138,7 +138,7 @@ func makeFile(t *testing.T, locator storage.Locator, storage config.Storage, fil require.NoError(t, err) fullPath := filepath.Join(root, filePath) - require.NoError(t, ioutil.WriteFile(fullPath, nil, 0o644)) + require.NoError(t, os.WriteFile(fullPath, nil, 0o644)) require.NoError(t, os.Chtimes(fullPath, mtime, mtime)) } diff --git a/internal/tempdir/tempdir.go b/internal/tempdir/tempdir.go index 949d04533..b34538851 100644 --- a/internal/tempdir/tempdir.go +++ b/internal/tempdir/tempdir.go @@ -3,7 +3,6 @@ package tempdir import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -84,7 +83,7 @@ func newDirectory(ctx context.Context, storageName string, prefix string, loc st return Dir{}, err } - tempDir, err := ioutil.TempDir(root, prefix) + tempDir, err := os.MkdirTemp(root, prefix) if err != nil { return Dir{}, err } diff --git a/internal/tempdir/tempdir_test.go b/internal/tempdir/tempdir_test.go index 7db046a29..c474bee4f 100644 --- a/internal/tempdir/tempdir_test.go +++ b/internal/tempdir/tempdir_test.go @@ -1,7 +1,7 @@ package tempdir import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -27,7 +27,7 @@ func TestNewRepositorySuccess(t *testing.T) { require.NoError(t, err) require.Equal(t, tempDir.Path(), calculatedPath) - require.NoError(t, ioutil.WriteFile(filepath.Join(tempDir.Path(), "test"), []byte("hello"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(tempDir.Path(), "test"), []byte("hello"), 0o644)) require.DirExists(t, tempDir.Path()) diff --git a/internal/testhelper/configure.go b/internal/testhelper/configure.go index 3ba25c47d..ea993b678 100644 --- a/internal/testhelper/configure.go +++ b/internal/testhelper/configure.go @@ -2,7 +2,6 @@ package testhelper import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -121,7 +120,7 @@ func getTestTmpDir() string { return testTmpDir } - testTmpDir, err := ioutil.TempDir("/tmp/", "gitaly-") + testTmpDir, err := os.MkdirTemp("/tmp/", "gitaly-") if err != nil { log.Fatal(err) } diff --git a/internal/testhelper/test_hook.go b/internal/testhelper/test_hook.go index 85fe4d244..c10e51823 100644 --- a/internal/testhelper/test_hook.go +++ b/internal/testhelper/test_hook.go @@ -1,7 +1,7 @@ package testhelper import ( - "io/ioutil" + "io" "testing" log "github.com/sirupsen/logrus" @@ -13,7 +13,7 @@ var NewTestLogger = DiscardTestLogger // DiscardTestLogger created a logrus hook that discards everything. func DiscardTestLogger(tb testing.TB) *log.Logger { logger := log.New() - logger.Out = ioutil.Discard + logger.Out = io.Discard return logger } diff --git a/internal/testhelper/testcfg/gitaly_builder.go b/internal/testhelper/testcfg/gitaly_builder.go index 6d65556a2..2dc48643c 100644 --- a/internal/testhelper/testcfg/gitaly_builder.go +++ b/internal/testhelper/testcfg/gitaly_builder.go @@ -1,7 +1,6 @@ package testcfg import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -125,7 +124,7 @@ func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { if cfg.Ruby.LinguistLanguagesPath == "" { // set a stub to prevent a long ruby process to run where it is not needed cfg.Ruby.LinguistLanguagesPath = filepath.Join(root, "linguist_languages.json") - require.NoError(t, ioutil.WriteFile(cfg.Ruby.LinguistLanguagesPath, []byte(`{}`), 0o655)) + require.NoError(t, os.WriteFile(cfg.Ruby.LinguistLanguagesPath, []byte(`{}`), 0o655)) } } diff --git a/internal/testhelper/testhelper.go b/internal/testhelper/testhelper.go index 763308518..1c452e85a 100644 --- a/internal/testhelper/testhelper.go +++ b/internal/testhelper/testhelper.go @@ -12,7 +12,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "math/big" "net" "os" @@ -50,7 +49,7 @@ const ( // MustReadFile returns the content of a file or fails at once. func MustReadFile(t testing.TB, filename string) []byte { - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { t.Fatal(err) } @@ -141,7 +140,7 @@ func CopyFile(t testing.TB, src, dst string) { func GetTemporaryGitalySocketFileName(t testing.TB) string { require.NotEmpty(t, testDirectory, "you must call testhelper.Configure() before GetTemporaryGitalySocketFileName()") - tmpfile, err := ioutil.TempFile(testDirectory, "gitaly.socket.") + tmpfile, err := os.CreateTemp(testDirectory, "gitaly.socket.") require.NoError(t, err) name := tmpfile.Name() @@ -251,13 +250,13 @@ func Context(opts ...ContextOpt) (context.Context, func()) { } } -// TempDir is a wrapper around ioutil.TempDir that provides a cleanup function. +// TempDir is a wrapper around os.MkdirTemp that provides a cleanup function. func TempDir(t testing.TB) string { if testDirectory == "" { panic("you must call testhelper.Configure() before TempDir()") } - tmpDir, err := ioutil.TempDir(testDirectory, "") + tmpDir, err := os.MkdirTemp(testDirectory, "") require.NoError(t, err) t.Cleanup(func() { require.NoError(t, os.RemoveAll(tmpDir)) @@ -275,7 +274,7 @@ func WriteExecutable(t testing.TB, path string, content []byte) { dir := filepath.Dir(path) require.NoError(t, os.MkdirAll(dir, 0o755)) - require.NoError(t, ioutil.WriteFile(path, content, 0o755)) + require.NoError(t, os.WriteFile(path, content, 0o755)) t.Cleanup(func() { assert.NoError(t, os.RemoveAll(dir)) @@ -330,7 +329,7 @@ func GenerateCerts(t *testing.T) (string, string) { entityCert, err := x509.CreateCertificate(rand.Reader, rootCA, entityX509, &entityKey.PublicKey, caKey) require.NoError(t, err) - certFile, err := ioutil.TempFile(testDirectory, "") + certFile, err := os.CreateTemp(testDirectory, "") require.NoError(t, err) defer MustClose(t, certFile) t.Cleanup(func() { @@ -347,7 +346,7 @@ func GenerateCerts(t *testing.T) (string, string) { ) } - keyFile, err := ioutil.TempFile(testDirectory, "") + keyFile, err := os.CreateTemp(testDirectory, "") require.NoError(t, err) defer MustClose(t, keyFile) t.Cleanup(func() { diff --git a/internal/x509/pool_darwin.go b/internal/x509/pool_darwin.go index d7614da77..851b16d72 100644 --- a/internal/x509/pool_darwin.go +++ b/internal/x509/pool_darwin.go @@ -3,7 +3,6 @@ package x509 import ( "crypto/x509" "errors" - "io/ioutil" "os" "path/filepath" ) @@ -14,7 +13,7 @@ func SystemCertPool() (*x509.CertPool, error) { var certPem []byte if f := os.Getenv(SSLCertFile); len(f) > 0 { - pem, err := ioutil.ReadFile(f) + pem, err := os.ReadFile(f) if err != nil { return nil, err } @@ -24,7 +23,7 @@ func SystemCertPool() (*x509.CertPool, error) { } if d := os.Getenv(SSLCertDir); len(d) > 0 { - entries, err := ioutil.ReadDir(d) + entries, err := os.ReadDir(d) if err != nil { return nil, err } @@ -34,7 +33,7 @@ func SystemCertPool() (*x509.CertPool, error) { continue } - pem, err := ioutil.ReadFile(filepath.Join(d, entry.Name())) + pem, err := os.ReadFile(filepath.Join(d, entry.Name())) if err != nil { return nil, err } diff --git a/proto/go/internal/cmd/protoc-gen-gitaly/main.go b/proto/go/internal/cmd/protoc-gen-gitaly/main.go index 40499a1fa..efe8a312e 100644 --- a/proto/go/internal/cmd/protoc-gen-gitaly/main.go +++ b/proto/go/internal/cmd/protoc-gen-gitaly/main.go @@ -55,7 +55,6 @@ import ( "fmt" "go/format" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -73,7 +72,7 @@ const ( ) func main() { - data, err := ioutil.ReadAll(os.Stdin) + data, err := io.ReadAll(os.Stdin) if err != nil { log.Fatalf("reading input: %s", err) } @@ -156,7 +155,7 @@ func generateProtolistGo(req *pluginpb.CodeGeneratorRequest) error { return fmt.Errorf("failed to get absolute path for %s: %v", gitalyProtoDir, err) } - files, err := ioutil.ReadDir(gitalyProtoDir) + files, err := os.ReadDir(gitalyProtoDir) if err != nil { return fmt.Errorf("failed to read %s: %v", gitalyProtoDir, err) } diff --git a/streamio/stream_test.go b/streamio/stream_test.go index 2e879ab55..c91d5a58f 100644 --- a/streamio/stream_test.go +++ b/streamio/stream_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "strings" "sync" "testing" @@ -26,7 +25,7 @@ func TestReceiveSources(t *testing.T) { } for _, tc := range testCases { - data, err := ioutil.ReadAll(&opaqueReader{NewReader(receiverFromReader(tc.r))}) + data, err := io.ReadAll(&opaqueReader{NewReader(receiverFromReader(tc.r))}) require.NoError(t, err, tc.desc) require.Equal(t, testData, string(data), tc.desc) } |