refactor: move from io/ioutil to io and os package (#17109)

The io/ioutil package has been deprecated as of Go 1.16, see
https://golang.org/doc/go1.16#ioutil. This commit replaces the existing
io/ioutil functions with their new definitions in io and os packages.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
pull/17124/head
Eng Zer Jun 3 years ago committed by GitHub
parent aa631d8cd1
commit f2e7d5477f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      build/generate-bindata.go
  2. 9
      build/generate-emoji.go
  3. 7
      build/generate-gitignores.go
  4. 3
      build/generate-licenses.go
  5. 3
      cmd/dump.go
  6. 3
      contrib/fixtures/fixture_generation.go
  7. 9
      contrib/pr/checkout.go
  8. 6
      integrations/api_helper_for_declarative_test.go
  9. 6
      integrations/api_repo_test.go
  10. 3
      integrations/create_no_session_test.go
  11. 6
      integrations/git_clone_wiki_test.go
  12. 9
      integrations/git_helper_for_declarative_test.go
  13. 4
      integrations/git_smart_http_test.go
  14. 16
      integrations/git_test.go
  15. 3
      integrations/gpg_git_test.go
  16. 4
      integrations/lfs_getobject_test.go
  17. 7
      integrations/lfs_local_endpoint_test.go
  18. 5
      integrations/migrate_test.go
  19. 4
      integrations/migration-test/migration_test.go
  20. 12
      integrations/oauth_test.go
  21. 4
      integrations/repo_tag_test.go
  22. 16
      integrations/ssh_key_test.go
  23. 5
      models/db/unit_tests.go
  24. 3
      models/engine_test.go
  25. 4
      models/fixture_test.go
  26. 3
      models/helper_directory.go
  27. 10
      models/migrations/v115.go
  28. 9
      models/repo.go
  29. 4
      models/ssh_key_parse.go
  30. 8
      modules/avatar/avatar_test.go
  31. 3
      modules/charset/charset.go
  32. 4
      modules/context/repo.go
  33. 3
      modules/doctor/paths.go
  34. 4
      modules/git/blame_test.go
  35. 3
      modules/git/blob.go
  36. 5
      modules/git/blob_nogogit.go
  37. 6
      modules/git/blob_test.go
  38. 9
      modules/git/hook.go
  39. 4
      modules/git/notes_gogit.go
  40. 4
      modules/git/notes_nogogit.go
  41. 4
      modules/git/repo_blob_test.go
  42. 5
      modules/git/repo_commit.go
  43. 3
      modules/git/repo_commit_nogogit.go
  44. 4
      modules/git/repo_compare_test.go
  45. 3
      modules/git/repo_index.go
  46. 6
      modules/git/repo_language_stats_gogit.go
  47. 4
      modules/git/repo_language_stats_nogogit.go
  48. 3
      modules/git/repo_tree_nogogit.go
  49. 5
      modules/graceful/server.go
  50. 9
      modules/httplib/httplib.go
  51. 3
      modules/indexer/code/bleve.go
  52. 4
      modules/indexer/code/bleve_test.go
  53. 3
      modules/indexer/code/elastic_search.go
  54. 4
      modules/indexer/issues/bleve_test.go
  55. 4
      modules/indexer/issues/indexer_test.go
  56. 9
      modules/lfs/http_client_test.go
  57. 5
      modules/lfs/transferadapter_test.go
  58. 4
      modules/log/conn_test.go
  59. 34
      modules/log/file_test.go
  60. 4
      modules/log/stack.go
  61. 3
      modules/markup/csv/csv.go
  62. 3
      modules/markup/external/external.go
  63. 3
      modules/markup/html.go
  64. 3
      modules/markup/markdown/markdown.go
  65. 19
      modules/migrations/restore.go
  66. 6
      modules/options/dynamic.go
  67. 9
      modules/options/static.go
  68. 6
      modules/pprof/pprof.go
  69. 4
      modules/private/key.go
  70. 4
      modules/private/mail.go
  71. 4
      modules/private/restore_repo.go
  72. 3
      modules/public/static.go
  73. 4
      modules/queue/queue_disk_channel_test.go
  74. 4
      modules/queue/queue_disk_test.go
  75. 4
      modules/recaptcha/recaptcha.go
  76. 9
      modules/repository/generate.go
  77. 9
      modules/repository/hooks.go
  78. 9
      modules/repository/init.go
  79. 5
      modules/setting/setting.go
  80. 3
      modules/storage/local.go
  81. 4
      modules/svg/discover_nobindata.go
  82. 9
      modules/templates/dynamic.go
  83. 8
      modules/templates/static.go
  84. 4
      routers/api/v1/misc/markdown_test.go
  85. 4
      routers/private/restore_repo.go
  86. 4
      routers/web/repo/editor.go
  87. 3
      routers/web/repo/http.go
  88. 4
      routers/web/repo/issue.go
  89. 3
      routers/web/repo/lfs.go
  90. 6
      routers/web/repo/setting.go
  91. 4
      routers/web/repo/settings_test.go
  92. 9
      routers/web/repo/view.go
  93. 4
      routers/web/repo/wiki.go
  94. 4
      routers/web/repo/wiki_test.go
  95. 3
      routers/web/user/auth.go
  96. 6
      routers/web/user/setting/profile.go
  97. 3
      services/auth/source/oauth2/jwtsigningkey.go
  98. 5
      services/gitdiff/gitdiff.go
  99. 5
      services/pull/check.go
  100. 5
      services/pull/merge.go
  101. Some files were not shown because too many files have changed in this diff Show More

@ -11,7 +11,6 @@ import (
"bytes" "bytes"
"crypto/sha1" "crypto/sha1"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -28,7 +27,7 @@ func needsUpdate(dir string, filename string) (bool, []byte) {
needRegen = true needRegen = true
} }
oldHash, err := ioutil.ReadFile(filename + ".hash") oldHash, err := os.ReadFile(filename + ".hash")
if err != nil { if err != nil {
oldHash = []byte{} oldHash = []byte{}
} }
@ -83,5 +82,5 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("%v\n", err) log.Fatalf("%v\n", err)
} }
_ = ioutil.WriteFile(filename+".hash", newHash, 0666) _ = os.WriteFile(filename+".hash", newHash, 0666)
} }

@ -12,9 +12,10 @@ import (
"flag" "flag"
"fmt" "fmt"
"go/format" "go/format"
"io/ioutil" "io"
"log" "log"
"net/http" "net/http"
"os"
"regexp" "regexp"
"sort" "sort"
"strconv" "strconv"
@ -67,7 +68,7 @@ func main() {
} }
// write // write
err = ioutil.WriteFile(*flagOut, buf, 0644) err = os.WriteFile(*flagOut, buf, 0644)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@ -96,7 +97,7 @@ func generate() ([]byte, error) {
defer res.Body.Close() defer res.Body.Close()
// read all // read all
body, err := ioutil.ReadAll(res.Body) body, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -157,7 +158,7 @@ func generate() ([]byte, error) {
// write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet) // write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet)
file, _ := json.Marshal(data) file, _ := json.Marshal(data)
_ = ioutil.WriteFile("assets/emoji.json", file, 0644) _ = os.WriteFile("assets/emoji.json", file, 0644)
// Add skin tones to emoji that support it // Add skin tones to emoji that support it
var ( var (

@ -9,7 +9,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -34,7 +33,7 @@ func main() {
flag.StringVar(&githubApiToken, "token", "", "github api token") flag.StringVar(&githubApiToken, "token", "", "github api token")
flag.Parse() flag.Parse()
file, err := ioutil.TempFile(os.TempDir(), prefix) file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil { if err != nil {
log.Fatalf("Failed to create temp file. %s", err) log.Fatalf("Failed to create temp file. %s", err)
@ -114,13 +113,13 @@ func main() {
for dst, src := range filesToCopy { for dst, src := range filesToCopy {
// Read all content of src to data // Read all content of src to data
src = path.Join(destination, src) src = path.Join(destination, src)
data, err := ioutil.ReadFile(src) data, err := os.ReadFile(src)
if err != nil { if err != nil {
log.Fatalf("Failed to read src file. %s", err) log.Fatalf("Failed to read src file. %s", err)
} }
// Write data to dst // Write data to dst
dst = path.Join(destination, dst) dst = path.Join(destination, dst)
err = ioutil.WriteFile(dst, data, 0644) err = os.WriteFile(dst, data, 0644)
if err != nil { if err != nil {
log.Fatalf("Failed to write new file. %s", err) log.Fatalf("Failed to write new file. %s", err)
} }

@ -9,7 +9,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -34,7 +33,7 @@ func main() {
flag.StringVar(&githubApiToken, "token", "", "github api token") flag.StringVar(&githubApiToken, "token", "", "github api token")
flag.Parse() flag.Parse()
file, err := ioutil.TempFile(os.TempDir(), prefix) file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil { if err != nil {
log.Fatalf("Failed to create temp file. %s", err) log.Fatalf("Failed to create temp file. %s", err)

@ -7,7 +7,6 @@ package cmd
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -247,7 +246,7 @@ func runDump(ctx *cli.Context) error {
fatal("Path does not exist: %s", tmpDir) fatal("Path does not exist: %s", tmpDir)
} }
dbDump, err := ioutil.TempFile(tmpDir, "gitea-db.sql") dbDump, err := os.CreateTemp(tmpDir, "gitea-db.sql")
if err != nil { if err != nil {
fatal("Failed to create tmp file: %v", err) fatal("Failed to create tmp file: %v", err)
} }

@ -6,7 +6,6 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -65,7 +64,7 @@ func generate(name string) error {
return err return err
} }
path := filepath.Join(fixturesDir, name+".yml") path := filepath.Join(fixturesDir, name+".yml")
if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil { if err := os.WriteFile(path, []byte(data), 0644); err != nil {
return fmt.Errorf("%s: %+v", path, err) return fmt.Errorf("%s: %+v", path, err)
} }
fmt.Printf("%s created.\n", path) fmt.Printf("%s created.\n", path)

@ -12,7 +12,6 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@ -52,11 +51,11 @@ func runPR() {
setting.SetCustomPathAndConf("", "", "") setting.SetCustomPathAndConf("", "", "")
setting.NewContext() setting.NewContext()
setting.RepoRootPath, err = ioutil.TempDir(os.TempDir(), "repos") setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos")
if err != nil { if err != nil {
log.Fatalf("TempDir: %v\n", err) log.Fatalf("TempDir: %v\n", err)
} }
setting.AppDataPath, err = ioutil.TempDir(os.TempDir(), "appdata") setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata")
if err != nil { if err != nil {
log.Fatalf("TempDir: %v\n", err) log.Fatalf("TempDir: %v\n", err)
} }
@ -181,7 +180,7 @@ func main() {
codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS codeFilePath = filepath.FromSlash(codeFilePath) //Convert to running OS
//Copy this file if it will not exist in the PR branch //Copy this file if it will not exist in the PR branch
dat, err := ioutil.ReadFile(codeFilePath) dat, err := os.ReadFile(codeFilePath)
if err != nil { if err != nil {
log.Fatalf("Failed to cache this code file : %v", err) log.Fatalf("Failed to cache this code file : %v", err)
} }
@ -245,7 +244,7 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err) log.Fatalf("Failed to duplicate this code file in PR : %v", err)
} }
err = ioutil.WriteFile(codeFilePath, dat, 0644) err = os.WriteFile(codeFilePath, dat, 0644)
if err != nil { if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err) log.Fatalf("Failed to duplicate this code file in PR : %v", err)
} }

@ -7,9 +7,9 @@ package integrations
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os"
"testing" "testing"
"time" "time"
@ -163,7 +163,7 @@ func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback ..
return func(t *testing.T) { return func(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/user/keys?token=%s", ctx.Token) urlStr := fmt.Sprintf("/api/v1/user/keys?token=%s", ctx.Token)
dataPubKey, err := ioutil.ReadFile(keyFile + ".pub") dataPubKey, err := os.ReadFile(keyFile + ".pub")
assert.NoError(t, err) assert.NoError(t, err)
req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateKeyOption{ req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateKeyOption{
Title: keyname, Title: keyname,
@ -199,7 +199,7 @@ func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly
return func(t *testing.T) { return func(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", ctx.Username, ctx.Reponame, ctx.Token) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", ctx.Username, ctx.Reponame, ctx.Token)
dataPubKey, err := ioutil.ReadFile(keyFile + ".pub") dataPubKey, err := os.ReadFile(keyFile + ".pub")
assert.NoError(t, err) assert.NoError(t, err)
req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{ req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{
Title: keyname, Title: keyname,

@ -6,9 +6,9 @@ package integrations
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -356,7 +356,7 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) {
httpContext := baseAPITestContext httpContext := baseAPITestContext
httpContext.Reponame = "repo-tmp-17" httpContext.Reponame = "repo-tmp-17"
dstPath, err := ioutil.TempDir("", httpContext.Reponame) dstPath, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
@ -419,7 +419,7 @@ func testAPIRepoCreateConflict(t *testing.T, u *url.URL) {
httpContext := baseAPITestContext httpContext := baseAPITestContext
httpContext.Reponame = "repo-tmp-17" httpContext.Reponame = "repo-tmp-17"
dstPath, err := ioutil.TempDir("", httpContext.Reponame) dstPath, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) t.Run("CreateRepo", doAPICreateRepository(httpContext, false))

@ -5,7 +5,6 @@
package integrations package integrations
import ( import (
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@ -69,7 +68,7 @@ func TestSessionFileCreation(t *testing.T) {
config.Provider = "file" config.Provider = "file"
// Now create a temporaryDirectory // Now create a temporaryDirectory
tmpDir, err := ioutil.TempDir("", "sessions") tmpDir, err := os.MkdirTemp("", "sessions")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { defer func() {
if _, err := os.Stat(tmpDir); !os.IsNotExist(err) { if _, err := os.Stat(tmpDir); !os.IsNotExist(err) {

@ -7,8 +7,8 @@ package integrations
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net/url" "net/url"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -24,7 +24,7 @@ func assertFileExist(t *testing.T, p string) {
} }
func assertFileEqual(t *testing.T, p string, content []byte) { func assertFileEqual(t *testing.T, p string, content []byte) {
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
assert.NoError(t, err) assert.NoError(t, err)
assert.EqualValues(t, content, bs) assert.EqualValues(t, content, bs)
} }
@ -33,7 +33,7 @@ func TestRepoCloneWiki(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) { onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer prepareTestEnv(t)() defer prepareTestEnv(t)()
dstPath, err := ioutil.TempDir("", "clone_wiki") dstPath, err := os.MkdirTemp("", "clone_wiki")
assert.NoError(t, err) assert.NoError(t, err)
r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String()) r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String())

@ -7,7 +7,6 @@ package integrations
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -28,7 +27,7 @@ import (
func withKeyFile(t *testing.T, keyname string, callback func(string)) { func withKeyFile(t *testing.T, keyname string, callback func(string)) {
tmpDir, err := ioutil.TempDir("", "key-file") tmpDir, err := os.MkdirTemp("", "key-file")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
@ -39,7 +38,7 @@ func withKeyFile(t *testing.T, keyname string, callback func(string)) {
err = ssh.GenKeyPair(keyFile) err = ssh.GenKeyPair(keyFile)
assert.NoError(t, err) assert.NoError(t, err)
err = ioutil.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+ err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+
"ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700) "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700)
assert.NoError(t, err) assert.NoError(t, err)
@ -125,7 +124,7 @@ func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
func doGitCloneFail(u *url.URL) func(*testing.T) { func doGitCloneFail(u *url.URL) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "doGitCloneFail") tmpDir, err := os.MkdirTemp("", "doGitCloneFail")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
assert.Error(t, git.Clone(u.String(), tmpDir, git.CloneRepoOptions{})) assert.Error(t, git.Clone(u.String(), tmpDir, git.CloneRepoOptions{}))
@ -139,7 +138,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
// Init repository in dstPath // Init repository in dstPath
assert.NoError(t, git.InitRepository(dstPath, false)) assert.NoError(t, git.InitRepository(dstPath, false))
assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644)) assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
assert.NoError(t, git.AddChanges(dstPath, true)) assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{ signature := git.Signature{
Email: "test@example.com", Email: "test@example.com",

@ -5,7 +5,7 @@
package integrations package integrations
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"testing" "testing"
@ -62,7 +62,7 @@ func testGitSmartHTTP(t *testing.T, u *url.URL) {
assert.NoError(t, err) assert.NoError(t, err)
defer resp.Body.Close() defer resp.Body.Close()
assert.EqualValues(t, kase.code, resp.StatusCode) assert.EqualValues(t, kase.code, resp.StatusCode)
_, err = ioutil.ReadAll(resp.Body) _, err = io.ReadAll(resp.Body)
assert.NoError(t, err) assert.NoError(t, err)
}) })
} }

@ -7,10 +7,10 @@ package integrations
import ( import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"net/http" "net/http"
"net/url" "net/url"
"os"
"path" "path"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -52,7 +52,7 @@ func testGit(t *testing.T, u *url.URL) {
httpContext.Reponame = "repo-tmp-17" httpContext.Reponame = "repo-tmp-17"
forkedUserCtx.Reponame = httpContext.Reponame forkedUserCtx.Reponame = httpContext.Reponame
dstPath, err := ioutil.TempDir("", httpContext.Reponame) dstPath, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
@ -102,7 +102,7 @@ func testGit(t *testing.T, u *url.URL) {
sshURL := createSSHUrl(sshContext.GitPath(), u) sshURL := createSSHUrl(sshContext.GitPath(), u)
//Setup clone folder //Setup clone folder
dstPath, err := ioutil.TempDir("", sshContext.Reponame) dstPath, err := os.MkdirTemp("", sshContext.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
@ -128,7 +128,7 @@ func testGit(t *testing.T, u *url.URL) {
} }
func ensureAnonymousClone(t *testing.T, u *url.URL) { func ensureAnonymousClone(t *testing.T, u *url.URL) {
dstLocalPath, err := ioutil.TempDir("", "repo1") dstLocalPath, err := os.MkdirTemp("", "repo1")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstLocalPath) defer util.RemoveAll(dstLocalPath)
t.Run("CloneAnonymous", doGitClone(dstLocalPath, u)) t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
@ -311,7 +311,7 @@ func generateCommitWithNewData(size int, repoPath, email, fullName, prefix strin
buffer := make([]byte, bufSize) buffer := make([]byte, bufSize)
tmpFile, err := ioutil.TempFile(repoPath, prefix) tmpFile, err := os.CreateTemp(repoPath, prefix)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -558,7 +558,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
u.Path = ctx.GitPath() u.Path = ctx.GitPath()
// Create a temporary directory // Create a temporary directory
tmpDir, err := ioutil.TempDir("", ctx.Reponame) tmpDir, err := os.MkdirTemp("", ctx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
@ -636,7 +636,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch)) t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
t.Run("AddCommit", func(t *testing.T) { t.Run("AddCommit", func(t *testing.T) {
err := ioutil.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666) err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
@ -710,7 +710,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
} }
t.Run("AddCommit2", func(t *testing.T) { t.Run("AddCommit2", func(t *testing.T) {
err := ioutil.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666) err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666)
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }

@ -7,7 +7,6 @@ package integrations
import ( import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"testing" "testing"
@ -28,7 +27,7 @@ func TestGPGGit(t *testing.T) {
username := "user2" username := "user2"
// OK Set a new GPG home // OK Set a new GPG home
tmpDir, err := ioutil.TempDir("", "temp-gpg") tmpDir, err := os.MkdirTemp("", "temp-gpg")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)

@ -7,7 +7,7 @@ package integrations
import ( import (
"archive/zip" "archive/zip"
"bytes" "bytes"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -74,7 +74,7 @@ func checkResponseTestContentEncoding(t *testing.T, content *[]byte, resp *httpt
assert.Contains(t, contentEncoding, "gzip") assert.Contains(t, contentEncoding, "gzip")
gzippReader, err := gzipp.NewReader(resp.Body) gzippReader, err := gzipp.NewReader(resp.Body)
assert.NoError(t, err) assert.NoError(t, err)
result, err := ioutil.ReadAll(gzippReader) result, err := io.ReadAll(gzippReader)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, *content, result) assert.Equal(t, *content, result)
} }

@ -6,7 +6,6 @@ package integrations
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
@ -25,14 +24,14 @@ func str2url(raw string) *url.URL {
func TestDetermineLocalEndpoint(t *testing.T) { func TestDetermineLocalEndpoint(t *testing.T) {
defer prepareTestEnv(t)() defer prepareTestEnv(t)()
root, _ := ioutil.TempDir("", "lfs_test") root, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(root) defer os.RemoveAll(root)
rootdotgit, _ := ioutil.TempDir("", "lfs_test") rootdotgit, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(rootdotgit) defer os.RemoveAll(rootdotgit)
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700) os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700)
lfsroot, _ := ioutil.TempDir("", "lfs_test") lfsroot, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(lfsroot) defer os.RemoveAll(lfsroot)
// Test cases // Test cases

@ -5,7 +5,6 @@
package integrations package integrations
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -25,14 +24,14 @@ func TestMigrateLocalPath(t *testing.T) {
old := setting.ImportLocalPaths old := setting.ImportLocalPaths
setting.ImportLocalPaths = true setting.ImportLocalPaths = true
lowercasePath, err := ioutil.TempDir("", "lowercase") // may not be lowercase because TempDir creates a random directory name which may be mixedcase lowercasePath, err := os.MkdirTemp("", "lowercase") // may not be lowercase because MkdirTemp creates a random directory name which may be mixedcase
assert.NoError(t, err) assert.NoError(t, err)
defer os.RemoveAll(lowercasePath) defer os.RemoveAll(lowercasePath)
err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser) err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser)
assert.NoError(t, err, "case lowercase path") assert.NoError(t, err, "case lowercase path")
mixedcasePath, err := ioutil.TempDir("", "mIxeDCaSe") mixedcasePath, err := os.MkdirTemp("", "mIxeDCaSe")
assert.NoError(t, err) assert.NoError(t, err)
defer os.RemoveAll(mixedcasePath) defer os.RemoveAll(mixedcasePath)

@ -9,7 +9,7 @@ import (
"context" "context"
"database/sql" "database/sql"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -113,7 +113,7 @@ func readSQLFromFile(version string) (string, error) {
} }
defer gr.Close() defer gr.Close()
bytes, err := ioutil.ReadAll(gr) bytes, err := io.ReadAll(gr)
if err != nil { if err != nil {
return "", err return "", err
} }

@ -6,7 +6,7 @@ package integrations
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"testing" "testing"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
@ -240,20 +240,20 @@ func TestRefreshTokenInvalidation(t *testing.T) {
"refresh_token": parsed.RefreshToken, "refresh_token": parsed.RefreshToken,
}) })
bs, err := ioutil.ReadAll(refreshReq.Body) bs, err := io.ReadAll(refreshReq.Body)
assert.NoError(t, err) assert.NoError(t, err)
refreshReq.Body = ioutil.NopCloser(bytes.NewReader(bs)) refreshReq.Body = io.NopCloser(bytes.NewReader(bs))
MakeRequest(t, refreshReq, 200) MakeRequest(t, refreshReq, 200)
refreshReq.Body = ioutil.NopCloser(bytes.NewReader(bs)) refreshReq.Body = io.NopCloser(bytes.NewReader(bs))
MakeRequest(t, refreshReq, 200) MakeRequest(t, refreshReq, 200)
// test with invalidation // test with invalidation
setting.OAuth2.InvalidateRefreshTokens = true setting.OAuth2.InvalidateRefreshTokens = true
refreshReq.Body = ioutil.NopCloser(bytes.NewReader(bs)) refreshReq.Body = io.NopCloser(bytes.NewReader(bs))
MakeRequest(t, refreshReq, 200) MakeRequest(t, refreshReq, 200)
refreshReq.Body = ioutil.NopCloser(bytes.NewReader(bs)) refreshReq.Body = io.NopCloser(bytes.NewReader(bs))
MakeRequest(t, refreshReq, 400) MakeRequest(t, refreshReq, 400)
} }

@ -5,8 +5,8 @@
package integrations package integrations
import ( import (
"io/ioutil"
"net/url" "net/url"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -55,7 +55,7 @@ func TestCreateNewTagProtected(t *testing.T) {
username := "user2" username := "user2"
httpContext := NewAPITestContext(t, username, "repo1") httpContext := NewAPITestContext(t, username, "repo1")
dstPath, err := ioutil.TempDir("", httpContext.Reponame) dstPath, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)

@ -6,9 +6,9 @@ package integrations
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) { func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644)) assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644))
assert.NoError(t, git.AddChanges(dstPath, true)) assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{ signature := git.Signature{
Email: "test@example.com", Email: "test@example.com",
@ -61,7 +61,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) {
t.Run("CreatePushDeployKey", doAPICreateDeployKey(ctx, keyname, keyFile, false)) t.Run("CreatePushDeployKey", doAPICreateDeployKey(ctx, keyname, keyFile, false))
// Setup the testing repository // Setup the testing repository
dstPath, err := ioutil.TempDir("", "repo-tmp-deploy-key-empty-repo-1") dstPath, err := os.MkdirTemp("", "repo-tmp-deploy-key-empty-repo-1")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
@ -107,7 +107,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
withKeyFile(t, keyname, func(keyFile string) { withKeyFile(t, keyname, func(keyFile string) {
var userKeyPublicKeyID int64 var userKeyPublicKeyID int64
t.Run("KeyCanOnlyBeUser", func(t *testing.T) { t.Run("KeyCanOnlyBeUser", func(t *testing.T) {
dstPath, err := ioutil.TempDir("", ctx.Reponame) dstPath, err := os.MkdirTemp("", ctx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
@ -133,7 +133,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
}) })
t.Run("KeyCanBeAnyDeployButNotUserAswell", func(t *testing.T) { t.Run("KeyCanBeAnyDeployButNotUserAswell", func(t *testing.T) {
dstPath, err := ioutil.TempDir("", ctx.Reponame) dstPath, err := os.MkdirTemp("", ctx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)
@ -151,7 +151,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
t.Run("FailToPush", doGitPushTestRepositoryFail(dstPath, "origin", "master")) t.Run("FailToPush", doGitPushTestRepositoryFail(dstPath, "origin", "master"))
otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) otherSSHURL := createSSHUrl(otherCtx.GitPath(), u)
dstOtherPath, err := ioutil.TempDir("", otherCtx.Reponame) dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstOtherPath) defer util.RemoveAll(dstOtherPath)
@ -168,7 +168,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
t.Run("DeleteRepositoryShouldReleaseKey", func(t *testing.T) { t.Run("DeleteRepositoryShouldReleaseKey", func(t *testing.T) {
otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) otherSSHURL := createSSHUrl(otherCtx.GitPath(), u)
dstOtherPath, err := ioutil.TempDir("", otherCtx.Reponame) dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstOtherPath) defer util.RemoveAll(dstOtherPath)
@ -190,7 +190,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
userKeyPublicKeyID = publicKey.ID userKeyPublicKeyID = publicKey.ID
})) }))
dstPath, err := ioutil.TempDir("", ctx.Reponame) dstPath, err := os.MkdirTemp("", ctx.Reponame)
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(dstPath) defer util.RemoveAll(dstPath)

@ -6,7 +6,6 @@ package db
import ( import (
"fmt" "fmt"
"io/ioutil"
"math" "math"
"net/url" "net/url"
"os" "os"
@ -57,11 +56,11 @@ func MainTest(m *testing.M, pathToGiteaRoot string) {
setting.SSH.Port = 3000 setting.SSH.Port = 3000
setting.SSH.Domain = "try.gitea.io" setting.SSH.Domain = "try.gitea.io"
setting.Database.UseSQLite3 = true setting.Database.UseSQLite3 = true
setting.RepoRootPath, err = ioutil.TempDir(os.TempDir(), "repos") setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos")
if err != nil { if err != nil {
fatalTestError("TempDir: %v\n", err) fatalTestError("TempDir: %v\n", err)
} }
setting.AppDataPath, err = ioutil.TempDir(os.TempDir(), "appdata") setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata")
if err != nil { if err != nil {
fatalTestError("TempDir: %v\n", err) fatalTestError("TempDir: %v\n", err)
} }

@ -5,7 +5,6 @@
package models package models
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -19,7 +18,7 @@ import (
func TestDumpDatabase(t *testing.T) { func TestDumpDatabase(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
dir, err := ioutil.TempDir(os.TempDir(), "dump") dir, err := os.MkdirTemp(os.TempDir(), "dump")
assert.NoError(t, err) assert.NoError(t, err)
type Version struct { type Version struct {

@ -5,7 +5,7 @@
package models package models
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -23,7 +23,7 @@ func TestFixtureGeneration(t *testing.T) {
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }
bytes, err := ioutil.ReadFile(filepath.Join(db.FixturesDir(), name+".yml")) bytes, err := os.ReadFile(filepath.Join(db.FixturesDir(), name+".yml"))
if !assert.NoError(t, err) { if !assert.NoError(t, err) {
return return
} }

@ -6,7 +6,6 @@ package models
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -30,7 +29,7 @@ func CreateTemporaryPath(prefix string) (string, error) {
log.Error("Unable to create localcopypath directory: %s (%v)", LocalCopyPath(), err) log.Error("Unable to create localcopypath directory: %s (%v)", LocalCopyPath(), err)
return "", fmt.Errorf("Failed to create localcopypath directory %s: %v", LocalCopyPath(), err) return "", fmt.Errorf("Failed to create localcopypath directory %s: %v", LocalCopyPath(), err)
} }
basePath, err := ioutil.TempDir(LocalCopyPath(), prefix+".git") basePath, err := os.MkdirTemp(LocalCopyPath(), prefix+".git")
if err != nil { if err != nil {
log.Error("Unable to create temporary directory: %s-*.git (%v)", prefix, err) log.Error("Unable to create temporary directory: %s-*.git (%v)", prefix, err)
return "", fmt.Errorf("Failed to create dir %s-*.git: %v", prefix, err) return "", fmt.Errorf("Failed to create dir %s-*.git: %v", prefix, err)

@ -7,7 +7,7 @@ package migrations
import ( import (
"crypto/md5" "crypto/md5"
"fmt" "fmt"
"io/ioutil" "io"
"math" "math"
"os" "os"
"path/filepath" "path/filepath"
@ -141,9 +141,9 @@ func copyOldAvatarToNewLocation(userID int64, oldAvatar string) (string, error)
} }
defer fr.Close() defer fr.Close()
data, err := ioutil.ReadAll(fr) data, err := io.ReadAll(fr)
if err != nil { if err != nil {
return "", fmt.Errorf("ioutil.ReadAll: %v", err) return "", fmt.Errorf("io.ReadAll: %v", err)
} }
newAvatar := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", userID, md5.Sum(data))))) newAvatar := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", userID, md5.Sum(data)))))
@ -151,8 +151,8 @@ func copyOldAvatarToNewLocation(userID int64, oldAvatar string) (string, error)
return newAvatar, nil return newAvatar, nil
} }
if err := ioutil.WriteFile(filepath.Join(setting.Avatar.Path, newAvatar), data, 0o666); err != nil { if err := os.WriteFile(filepath.Join(setting.Avatar.Path, newAvatar), data, 0o666); err != nil {
return "", fmt.Errorf("ioutil.WriteFile: %v", err) return "", fmt.Errorf("os.WriteFile: %v", err)
} }
return newAvatar, nil return newAvatar, nil

@ -10,11 +10,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"html/template" "html/template"
"unicode/utf8" _ "image/jpeg" // Needed for jpeg support
// Needed for jpeg support
_ "image/jpeg"
"io/ioutil"
"net" "net"
"net/url" "net/url"
"os" "os"
@ -24,6 +20,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"unicode/utf8"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/lfs"
@ -1013,7 +1010,7 @@ func GetRepoInitFile(tp, name string) ([]byte, error) {
log.Error("Unable to check if %s is a file. Error: %v", customPath, err) log.Error("Unable to check if %s is a file. Error: %v", customPath, err)
} }
if isFile { if isFile {
return ioutil.ReadFile(customPath) return os.ReadFile(customPath)
} }
switch tp { switch tp {

@ -13,8 +13,8 @@ import (
"encoding/pem" "encoding/pem"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os"
"strconv" "strconv"
"strings" "strings"
@ -263,7 +263,7 @@ func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
// writeTmpKeyFile writes key content to a temporary file // writeTmpKeyFile writes key content to a temporary file
// and returns the name of that file, along with any possible errors. // and returns the name of that file, along with any possible errors.
func writeTmpKeyFile(content string) (string, error) { func writeTmpKeyFile(content string) (string, error) {
tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gitea_keytest") tmpFile, err := os.CreateTemp(setting.SSH.KeyTestPath, "gitea_keytest")
if err != nil { if err != nil {
return "", fmt.Errorf("TempFile: %v", err) return "", fmt.Errorf("TempFile: %v", err)
} }

@ -5,7 +5,7 @@
package avatar package avatar
import ( import (
"io/ioutil" "os"
"testing" "testing"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -30,7 +30,7 @@ func Test_PrepareWithPNG(t *testing.T) {
setting.Avatar.MaxWidth = 4096 setting.Avatar.MaxWidth = 4096
setting.Avatar.MaxHeight = 4096 setting.Avatar.MaxHeight = 4096
data, err := ioutil.ReadFile("testdata/avatar.png") data, err := os.ReadFile("testdata/avatar.png")
assert.NoError(t, err) assert.NoError(t, err)
imgPtr, err := Prepare(data) imgPtr, err := Prepare(data)
@ -44,7 +44,7 @@ func Test_PrepareWithJPEG(t *testing.T) {
setting.Avatar.MaxWidth = 4096 setting.Avatar.MaxWidth = 4096
setting.Avatar.MaxHeight = 4096 setting.Avatar.MaxHeight = 4096
data, err := ioutil.ReadFile("testdata/avatar.jpeg") data, err := os.ReadFile("testdata/avatar.jpeg")
assert.NoError(t, err) assert.NoError(t, err)
imgPtr, err := Prepare(data) imgPtr, err := Prepare(data)
@ -65,7 +65,7 @@ func Test_PrepareWithInvalidImageSize(t *testing.T) {
setting.Avatar.MaxWidth = 5 setting.Avatar.MaxWidth = 5
setting.Avatar.MaxHeight = 5 setting.Avatar.MaxHeight = 5
data, err := ioutil.ReadFile("testdata/avatar.png") data, err := os.ReadFile("testdata/avatar.png")
assert.NoError(t, err) assert.NoError(t, err)
_, err = Prepare(data) _, err = Prepare(data)

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"unicode/utf8" "unicode/utf8"
@ -78,7 +77,7 @@ func ToUTF8WithErr(content []byte) (string, error) {
// ToUTF8WithFallback detects the encoding of content and coverts to UTF-8 if possible // ToUTF8WithFallback detects the encoding of content and coverts to UTF-8 if possible
func ToUTF8WithFallback(content []byte) []byte { func ToUTF8WithFallback(content []byte) []byte {
bs, _ := ioutil.ReadAll(ToUTF8WithFallbackReader(bytes.NewReader(content))) bs, _ := io.ReadAll(ToUTF8WithFallbackReader(bytes.NewReader(content)))
return bs return bs
} }

@ -8,7 +8,7 @@ package context
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/url" "net/url"
"path" "path"
"strings" "strings"
@ -915,7 +915,7 @@ func (ctx *Context) IssueTemplatesFromDefaultBranch() []api.IssueTemplate {
_ = r.Close() _ = r.Close()
} }
}() }()
data, err := ioutil.ReadAll(r) data, err := io.ReadAll(r)
if err != nil { if err != nil {
log.Debug("ReadAll: %v", err) log.Debug("ReadAll: %v", err)
continue continue

@ -6,7 +6,6 @@ package doctor
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -102,7 +101,7 @@ func isWritableDir(path string) error {
// There's no platform-independent way of checking if a directory is writable // There's no platform-independent way of checking if a directory is writable
// https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable // https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable
tmpFile, err := ioutil.TempFile(path, "doctors-order") tmpFile, err := os.CreateTemp(path, "doctors-order")
if err != nil { if err != nil {
return err return err
} }

@ -6,7 +6,7 @@ package git
import ( import (
"context" "context"
"io/ioutil" "os"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -84,7 +84,7 @@ e2aa991e10ffd924a828ec149951f2f20eecead2 7 7
` `
func TestReadingBlameOutput(t *testing.T) { func TestReadingBlameOutput(t *testing.T) {
tempFile, err := ioutil.TempFile("", ".txt") tempFile, err := os.CreateTemp("", ".txt")
if err != nil { if err != nil {
panic(err) panic(err)
} }

@ -9,7 +9,6 @@ import (
"bytes" "bytes"
"encoding/base64" "encoding/base64"
"io" "io"
"io/ioutil"
"code.gitea.io/gitea/modules/typesniffer" "code.gitea.io/gitea/modules/typesniffer"
) )
@ -83,7 +82,7 @@ func (b *Blob) GetBlobContentBase64() (string, error) {
} }
}() }()
out, err := ioutil.ReadAll(pr) out, err := io.ReadAll(pr)
if err != nil { if err != nil {
return "", err return "", err
} }

@ -11,7 +11,6 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"io" "io"
"io/ioutil"
"math" "math"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -46,13 +45,13 @@ func (b *Blob) DataAsync() (io.ReadCloser, error) {
b.size = size b.size = size
if size < 4096 { if size < 4096 {
bs, err := ioutil.ReadAll(io.LimitReader(rd, size)) bs, err := io.ReadAll(io.LimitReader(rd, size))
defer cancel() defer cancel()
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = rd.Discard(1) _, err = rd.Discard(1)
return ioutil.NopCloser(bytes.NewReader(bs)), err return io.NopCloser(bytes.NewReader(bs)), err
} }
return &blobReader{ return &blobReader{

@ -6,7 +6,7 @@
package git package git
import ( import (
"io/ioutil" "io"
"path/filepath" "path/filepath"
"testing" "testing"
@ -30,7 +30,7 @@ func TestBlob_Data(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
require.NotNil(t, r) require.NotNil(t, r)
data, err := ioutil.ReadAll(r) data, err := io.ReadAll(r)
assert.NoError(t, r.Close()) assert.NoError(t, r.Close())
assert.NoError(t, err) assert.NoError(t, err)
@ -55,7 +55,7 @@ func Benchmark_Blob_Data(b *testing.B) {
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
ioutil.ReadAll(r) io.ReadAll(r)
_ = r.Close() _ = r.Close()
} }
} }

@ -7,7 +7,6 @@ package git
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -59,14 +58,14 @@ func GetHook(repoPath, name string) (*Hook, error) {
} }
samplePath := filepath.Join(repoPath, "hooks", name+".sample") samplePath := filepath.Join(repoPath, "hooks", name+".sample")
if isFile(h.path) { if isFile(h.path) {
data, err := ioutil.ReadFile(h.path) data, err := os.ReadFile(h.path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
h.IsActive = true h.IsActive = true
h.Content = string(data) h.Content = string(data)
} else if isFile(samplePath) { } else if isFile(samplePath) {
data, err := ioutil.ReadFile(samplePath) data, err := os.ReadFile(samplePath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -97,7 +96,7 @@ func (h *Hook) Update() error {
return err return err
} }
err := ioutil.WriteFile(h.path, []byte(strings.ReplaceAll(h.Content, "\r", "")), os.ModePerm) err := os.WriteFile(h.path, []byte(strings.ReplaceAll(h.Content, "\r", "")), os.ModePerm)
if err != nil { if err != nil {
return err return err
} }
@ -143,5 +142,5 @@ func SetUpdateHook(repoPath, content string) (err error) {
if err != nil { if err != nil {
return err return err
} }
return ioutil.WriteFile(hookPath, []byte(content), 0777) return os.WriteFile(hookPath, []byte(content), 0777)
} }

@ -9,7 +9,7 @@ package git
import ( import (
"context" "context"
"io/ioutil" "io"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -58,7 +58,7 @@ func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note)
} }
defer dataRc.Close() defer dataRc.Close()
d, err := ioutil.ReadAll(dataRc) d, err := io.ReadAll(dataRc)
if err != nil { if err != nil {
log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err) log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err)
return err return err

@ -9,7 +9,7 @@ package git
import ( import (
"context" "context"
"io/ioutil" "io"
"strings" "strings"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -60,7 +60,7 @@ func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note)
_ = dataRc.Close() _ = dataRc.Close()
} }
}() }()
d, err := ioutil.ReadAll(dataRc) d, err := io.ReadAll(dataRc)
if err != nil { if err != nil {
log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err) log.Error("Unable to read blob with ID %q. Error: %v", blob.ID, err)
return err return err

@ -6,7 +6,7 @@ package git
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"path/filepath" "path/filepath"
"testing" "testing"
@ -34,7 +34,7 @@ func TestRepository_GetBlob_Found(t *testing.T) {
dataReader, err := blob.DataAsync() dataReader, err := blob.DataAsync()
assert.NoError(t, err) assert.NoError(t, err)
data, err := ioutil.ReadAll(dataReader) data, err := io.ReadAll(dataReader)
assert.NoError(t, dataReader.Close()) assert.NoError(t, dataReader.Close())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, testCase.Data, data) assert.Equal(t, testCase.Data, data)

@ -8,7 +8,6 @@ package git
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"strconv" "strconv"
"strings" "strings"
@ -222,7 +221,7 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
}() }()
if skip > 0 { if skip > 0 {
_, err := io.CopyN(ioutil.Discard, stdoutReader, int64(skip*41)) _, err := io.CopyN(io.Discard, stdoutReader, int64(skip*41))
if err != nil { if err != nil {
if err == io.EOF { if err == io.EOF {
return []*Commit{}, nil return []*Commit{}, nil
@ -232,7 +231,7 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (
} }
} }
stdout, err := ioutil.ReadAll(stdoutReader) stdout, err := io.ReadAll(stdoutReader)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -11,7 +11,6 @@ import (
"bufio" "bufio"
"errors" "errors"
"io" "io"
"io/ioutil"
"strings" "strings"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -77,7 +76,7 @@ func (repo *Repository) getCommitFromBatchReader(rd *bufio.Reader, id SHA1) (*Co
case "tag": case "tag":
// then we need to parse the tag // then we need to parse the tag
// and load the commit // and load the commit
data, err := ioutil.ReadAll(io.LimitReader(rd, size)) data, err := io.ReadAll(io.LimitReader(rd, size))
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -6,7 +6,7 @@ package git
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"path/filepath" "path/filepath"
"testing" "testing"
@ -25,7 +25,7 @@ func TestGetFormatPatch(t *testing.T) {
rd := &bytes.Buffer{} rd := &bytes.Buffer{}
err = repo.GetPatch("8d92fc95^", "8d92fc95", rd) err = repo.GetPatch("8d92fc95^", "8d92fc95", rd)
assert.NoError(t, err) assert.NoError(t, err)
patchb, err := ioutil.ReadAll(rd) patchb, err := io.ReadAll(rd)
assert.NoError(t, err) assert.NoError(t, err)
patch := string(patchb) patch := string(patchb)
assert.Regexp(t, "^From 8d92fc95", patch) assert.Regexp(t, "^From 8d92fc95", patch)

@ -7,7 +7,6 @@ package git
import ( import (
"bytes" "bytes"
"context" "context"
"io/ioutil"
"os" "os"
"strings" "strings"
@ -47,7 +46,7 @@ func (repo *Repository) readTreeToIndex(id SHA1, indexFilename ...string) error
// ReadTreeToTemporaryIndex reads a treeish to a temporary index file // ReadTreeToTemporaryIndex reads a treeish to a temporary index file
func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename string, cancel context.CancelFunc, err error) { func (repo *Repository) ReadTreeToTemporaryIndex(treeish string) (filename string, cancel context.CancelFunc, err error) {
tmpIndex, err := ioutil.TempFile("", "index") tmpIndex, err := os.CreateTemp("", "index")
if err != nil { if err != nil {
return return
} }

@ -11,7 +11,7 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil" "os"
"code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -51,7 +51,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID) indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
if err == nil { if err == nil {
defer deleteTemporaryFile() defer deleteTemporaryFile()
tmpWorkTree, err := ioutil.TempDir("", "empty-work-dir") tmpWorkTree, err := os.MkdirTemp("", "empty-work-dir")
if err == nil { if err == nil {
defer func() { defer func() {
_ = util.RemoveAll(tmpWorkTree) _ = util.RemoveAll(tmpWorkTree)
@ -174,7 +174,7 @@ func readFile(f *object.File, limit int64) ([]byte, error) {
defer r.Close() defer r.Close()
if limit <= 0 { if limit <= 0 {
return ioutil.ReadAll(r) return io.ReadAll(r)
} }
size := f.Size size := f.Size

@ -12,8 +12,8 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil"
"math" "math"
"os"
"code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/analyze"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -71,7 +71,7 @@ func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, err
indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID) indexFilename, deleteTemporaryFile, err := repo.ReadTreeToTemporaryIndex(commitID)
if err == nil { if err == nil {
defer deleteTemporaryFile() defer deleteTemporaryFile()
tmpWorkTree, err := ioutil.TempDir("", "empty-work-dir") tmpWorkTree, err := os.MkdirTemp("", "empty-work-dir")
if err == nil { if err == nil {
defer func() { defer func() {
_ = util.RemoveAll(tmpWorkTree) _ = util.RemoveAll(tmpWorkTree)

@ -9,7 +9,6 @@ package git
import ( import (
"io" "io"
"io/ioutil"
) )
func (repo *Repository) getTree(id SHA1) (*Tree, error) { func (repo *Repository) getTree(id SHA1) (*Tree, error) {
@ -27,7 +26,7 @@ func (repo *Repository) getTree(id SHA1) (*Tree, error) {
switch typ { switch typ {
case "tag": case "tag":
resolvedID := id resolvedID := id
data, err := ioutil.ReadAll(io.LimitReader(rd, size)) data, err := io.ReadAll(io.LimitReader(rd, size))
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -7,7 +7,6 @@ package graceful
import ( import (
"crypto/tls" "crypto/tls"
"io/ioutil"
"net" "net"
"os" "os"
"strings" "strings"
@ -111,13 +110,13 @@ func (srv *Server) ListenAndServeTLS(certFile, keyFile string, serve ServeFuncti
config.Certificates = make([]tls.Certificate, 1) config.Certificates = make([]tls.Certificate, 1)
certPEMBlock, err := ioutil.ReadFile(certFile) certPEMBlock, err := os.ReadFile(certFile)
if err != nil { if err != nil {
log.Error("Failed to load https cert file %s for %s:%s: %v", certFile, srv.network, srv.address, err) log.Error("Failed to load https cert file %s for %s:%s: %v", certFile, srv.network, srv.address, err)
return err return err
} }
keyPEMBlock, err := ioutil.ReadFile(keyFile) keyPEMBlock, err := os.ReadFile(keyFile)
if err != nil { if err != nil {
log.Error("Failed to load https key file %s for %s:%s: %v", keyFile, srv.network, srv.address, err) log.Error("Failed to load https key file %s for %s:%s: %v", keyFile, srv.network, srv.address, err)
return err return err

@ -11,7 +11,6 @@ import (
"crypto/tls" "crypto/tls"
"encoding/xml" "encoding/xml"
"io" "io"
"io/ioutil"
"log" "log"
"mime/multipart" "mime/multipart"
"net" "net"
@ -243,11 +242,11 @@ func (r *Request) Body(data interface{}) *Request {
switch t := data.(type) { switch t := data.(type) {
case string: case string:
bf := bytes.NewBufferString(t) bf := bytes.NewBufferString(t)
r.req.Body = ioutil.NopCloser(bf) r.req.Body = io.NopCloser(bf)
r.req.ContentLength = int64(len(t)) r.req.ContentLength = int64(len(t))
case []byte: case []byte:
bf := bytes.NewBuffer(t) bf := bytes.NewBuffer(t)
r.req.Body = ioutil.NopCloser(bf) r.req.Body = io.NopCloser(bf)
r.req.ContentLength = int64(len(t)) r.req.ContentLength = int64(len(t))
} }
return r return r
@ -307,7 +306,7 @@ func (r *Request) getResponse() (*http.Response, error) {
_ = pw.Close() _ = pw.Close()
}() }()
r.Header("Content-Type", bodyWriter.FormDataContentType()) r.Header("Content-Type", bodyWriter.FormDataContentType())
r.req.Body = ioutil.NopCloser(pr) r.req.Body = io.NopCloser(pr)
} else if len(paramBody) > 0 { } else if len(paramBody) > 0 {
r.Header("Content-Type", "application/x-www-form-urlencoded") r.Header("Content-Type", "application/x-www-form-urlencoded")
r.Body(paramBody) r.Body(paramBody)
@ -407,7 +406,7 @@ func (r *Request) Bytes() ([]byte, error) {
return nil, nil return nil, nil
} }
defer resp.Body.Close() defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -8,7 +8,6 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -210,7 +209,7 @@ func (b *BleveIndexer) addUpdate(batchWriter git.WriteCloserError, batchReader *
return err return err
} }
fileContents, err := ioutil.ReadAll(io.LimitReader(batchReader, size)) fileContents, err := io.ReadAll(io.LimitReader(batchReader, size))
if err != nil { if err != nil {
return err return err
} else if !typesniffer.DetectContentType(fileContents).IsText() { } else if !typesniffer.DetectContentType(fileContents).IsText() {

@ -5,7 +5,7 @@
package code package code
import ( import (
"io/ioutil" "os"
"testing" "testing"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -17,7 +17,7 @@ import (
func TestBleveIndexAndSearch(t *testing.T) { func TestBleveIndexAndSearch(t *testing.T) {
db.PrepareTestEnv(t) db.PrepareTestEnv(t)
dir, err := ioutil.TempDir("", "bleve.index") dir, err := os.MkdirTemp("", "bleve.index")
assert.NoError(t, err) assert.NoError(t, err)
if err != nil { if err != nil {
assert.Fail(t, "Unable to create temporary directory") assert.Fail(t, "Unable to create temporary directory")

@ -9,7 +9,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -207,7 +206,7 @@ func (b *ElasticSearchIndexer) addUpdate(batchWriter git.WriteCloserError, batch
return nil, err return nil, err
} }
fileContents, err := ioutil.ReadAll(io.LimitReader(batchReader, size)) fileContents, err := io.ReadAll(io.LimitReader(batchReader, size))
if err != nil { if err != nil {
return nil, err return nil, err
} else if !typesniffer.DetectContentType(fileContents).IsText() { } else if !typesniffer.DetectContentType(fileContents).IsText() {

@ -5,7 +5,7 @@
package issues package issues
import ( import (
"io/ioutil" "os"
"testing" "testing"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
@ -13,7 +13,7 @@ import (
) )
func TestBleveIndexAndSearch(t *testing.T) { func TestBleveIndexAndSearch(t *testing.T) {
dir, err := ioutil.TempDir("", "bleve.index") dir, err := os.MkdirTemp("", "bleve.index")
assert.NoError(t, err) assert.NoError(t, err)
if err != nil { if err != nil {
assert.Fail(t, "Unable to create temporary directory") assert.Fail(t, "Unable to create temporary directory")

@ -5,7 +5,7 @@
package issues package issues
import ( import (
"io/ioutil" "os"
"path" "path"
"path/filepath" "path/filepath"
"testing" "testing"
@ -28,7 +28,7 @@ func TestBleveSearchIssues(t *testing.T) {
assert.NoError(t, db.PrepareTestDatabase()) assert.NoError(t, db.PrepareTestDatabase())
setting.Cfg = ini.Empty() setting.Cfg = ini.Empty()
tmpIndexerDir, err := ioutil.TempDir("", "issues-indexer") tmpIndexerDir, err := os.MkdirTemp("", "issues-indexer")
if err != nil { if err != nil {
assert.Fail(t, "Unable to create temporary directory: %v", err) assert.Fail(t, "Unable to create temporary directory: %v", err)
return return

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -32,7 +31,7 @@ func (a *DummyTransferAdapter) Name() string {
} }
func (a *DummyTransferAdapter) Download(ctx context.Context, l *Link) (io.ReadCloser, error) { func (a *DummyTransferAdapter) Download(ctx context.Context, l *Link) (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewBufferString("dummy")), nil return io.NopCloser(bytes.NewBufferString("dummy")), nil
} }
func (a *DummyTransferAdapter) Upload(ctx context.Context, l *Link, p Pointer, r io.Reader) error { func (a *DummyTransferAdapter) Upload(ctx context.Context, l *Link, p Pointer, r io.Reader) error {
@ -50,7 +49,7 @@ func lfsTestRoundtripHandler(req *http.Request) *http.Response {
if strings.Contains(url, "status-not-ok") { if strings.Contains(url, "status-not-ok") {
return &http.Response{StatusCode: http.StatusBadRequest} return &http.Response{StatusCode: http.StatusBadRequest}
} else if strings.Contains(url, "invalid-json-response") { } else if strings.Contains(url, "invalid-json-response") {
return &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewBufferString("invalid json"))} return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString("invalid json"))}
} else if strings.Contains(url, "valid-batch-request-download") { } else if strings.Contains(url, "valid-batch-request-download") {
batchResponse = &BatchResponse{ batchResponse = &BatchResponse{
Transfer: "dummy", Transfer: "dummy",
@ -149,7 +148,7 @@ func lfsTestRoundtripHandler(req *http.Request) *http.Response {
payload := new(bytes.Buffer) payload := new(bytes.Buffer)
json.NewEncoder(payload).Encode(batchResponse) json.NewEncoder(payload).Encode(batchResponse)
return &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(payload)} return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(payload)}
} }
func TestHTTPClientDownload(t *testing.T) { func TestHTTPClientDownload(t *testing.T) {
@ -350,7 +349,7 @@ func TestHTTPClientUpload(t *testing.T) {
client.transfers["dummy"] = dummy client.transfers["dummy"] = dummy
err := client.Upload(context.Background(), []Pointer{p}, func(p Pointer, objectError error) (io.ReadCloser, error) { err := client.Upload(context.Background(), []Pointer{p}, func(p Pointer, objectError error) (io.ReadCloser, error) {
return ioutil.NopCloser(new(bytes.Buffer)), objectError return io.NopCloser(new(bytes.Buffer)), objectError
}) })
if len(c.expectederror) > 0 { if len(c.expectederror) > 0 {
assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror)

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -35,7 +34,7 @@ func TestBasicTransferAdapter(t *testing.T) {
if strings.Contains(url, "download-request") { if strings.Contains(url, "download-request") {
assert.Equal(t, "GET", req.Method) assert.Equal(t, "GET", req.Method)
return &http.Response{StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewBufferString("dummy"))} return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString("dummy"))}
} else if strings.Contains(url, "upload-request") { } else if strings.Contains(url, "upload-request") {
assert.Equal(t, "PUT", req.Method) assert.Equal(t, "PUT", req.Method)
assert.Equal(t, "application/octet-stream", req.Header.Get("Content-Type")) assert.Equal(t, "application/octet-stream", req.Header.Get("Content-Type"))
@ -63,7 +62,7 @@ func TestBasicTransferAdapter(t *testing.T) {
payload := new(bytes.Buffer) payload := new(bytes.Buffer)
json.NewEncoder(payload).Encode(er) json.NewEncoder(payload).Encode(er)
return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(payload)} return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(payload)}
} else { } else {
t.Errorf("Unknown test case: %s", url) t.Errorf("Unknown test case: %s", url)
return nil return nil

@ -6,7 +6,7 @@ package log
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"strings" "strings"
"sync" "sync"
@ -20,7 +20,7 @@ func listenReadAndClose(t *testing.T, l net.Listener, expected string) {
conn, err := l.Accept() conn, err := l.Accept()
assert.NoError(t, err) assert.NoError(t, err)
defer conn.Close() defer conn.Close()
written, err := ioutil.ReadAll(conn) written, err := io.ReadAll(conn)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(written)) assert.Equal(t, expected, string(written))

@ -7,7 +7,7 @@ package log
import ( import (
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -19,7 +19,7 @@ import (
) )
func TestFileLoggerFails(t *testing.T) { func TestFileLoggerFails(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestFileLogger") tmpDir, err := os.MkdirTemp("", "TestFileLogger")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
@ -47,7 +47,7 @@ func TestFileLoggerFails(t *testing.T) {
} }
func TestFileLogger(t *testing.T) { func TestFileLogger(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestFileLogger") tmpDir, err := os.MkdirTemp("", "TestFileLogger")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
@ -85,21 +85,21 @@ func TestFileLogger(t *testing.T) {
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err := ioutil.ReadFile(filename) logData, err := os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
event.level = DEBUG event.level = DEBUG
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
event.level = TRACE event.level = TRACE
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -107,18 +107,18 @@ func TestFileLogger(t *testing.T) {
expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
// Should rotate // Should rotate
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), 1)) logData, err = os.ReadFile(filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), 1))
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
expected = fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) expected = fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -134,7 +134,7 @@ func TestFileLogger(t *testing.T) {
expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -142,7 +142,7 @@ func TestFileLogger(t *testing.T) {
expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -150,7 +150,7 @@ func TestFileLogger(t *testing.T) {
} }
func TestCompressFileLogger(t *testing.T) { func TestCompressFileLogger(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestFileLogger") tmpDir, err := os.MkdirTemp("", "TestFileLogger")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
@ -184,7 +184,7 @@ func TestCompressFileLogger(t *testing.T) {
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err := ioutil.ReadFile(filename) logData, err := os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -192,7 +192,7 @@ func TestCompressFileLogger(t *testing.T) {
expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg) expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event) fileLogger.LogEvent(&event)
fileLogger.Flush() fileLogger.Flush()
logData, err = ioutil.ReadFile(filename) logData, err = os.ReadFile(filename)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, expected, string(logData)) assert.Equal(t, expected, string(logData))
@ -210,7 +210,7 @@ func TestCompressFileLogger(t *testing.T) {
} }
func TestCompressOldFile(t *testing.T) { func TestCompressOldFile(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestFileLogger") tmpDir, err := os.MkdirTemp("", "TestFileLogger")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
fname := filepath.Join(tmpDir, "test") fname := filepath.Join(tmpDir, "test")
@ -238,9 +238,9 @@ func TestCompressOldFile(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
zr, err := gzip.NewReader(f) zr, err := gzip.NewReader(f)
assert.NoError(t, err) assert.NoError(t, err)
data, err := ioutil.ReadAll(zr) data, err := io.ReadAll(zr)
assert.NoError(t, err) assert.NoError(t, err)
original, err := ioutil.ReadFile(nonGzip) original, err := os.ReadFile(nonGzip)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, original, data) assert.Equal(t, original, data)
} }

@ -7,7 +7,7 @@ package log
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "os"
"runtime" "runtime"
) )
@ -38,7 +38,7 @@ func Stack(skip int) string {
fmt.Fprintf(buf, "%s:%d (0x%x)\n", filename, lineNumber, programCounter) fmt.Fprintf(buf, "%s:%d (0x%x)\n", filename, lineNumber, programCounter)
// Now try to print the offending line // Now try to print the offending line
if filename != lastFilename { if filename != lastFilename {
data, err := ioutil.ReadFile(filename) data, err := os.ReadFile(filename)
if err != nil { if err != nil {
// can't read this sourcefile // can't read this sourcefile
// likely we don't have the sourcecode available // likely we don't have the sourcecode available

@ -9,7 +9,6 @@ import (
"bytes" "bytes"
"html" "html"
"io" "io"
"io/ioutil"
"regexp" "regexp"
"strconv" "strconv"
@ -87,7 +86,7 @@ func (Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Wri
var tmpBlock = bufio.NewWriter(output) var tmpBlock = bufio.NewWriter(output)
// FIXME: don't read all to memory // FIXME: don't read all to memory
rawBytes, err := ioutil.ReadAll(input) rawBytes, err := io.ReadAll(input)
if err != nil { if err != nil {
return err return err
} }

@ -8,7 +8,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"runtime" "runtime"
@ -75,7 +74,7 @@ func (p *Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.
if p.IsInputFile { if p.IsInputFile {
// write to temp file // write to temp file
f, err := ioutil.TempFile("", "gitea_input") f, err := os.CreateTemp("", "gitea_input")
if err != nil { if err != nil {
return fmt.Errorf("%s create temp file when rendering %s failed: %v", p.Name(), p.Command, err) return fmt.Errorf("%s create temp file when rendering %s failed: %v", p.Name(), p.Command, err)
} }

@ -7,7 +7,6 @@ package markup
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"path" "path"
"path/filepath" "path/filepath"
@ -290,7 +289,7 @@ var nulCleaner = strings.NewReplacer("\000", "")
func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error { func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error {
defer ctx.Cancel() defer ctx.Cancel()
// FIXME: don't read all content to memory // FIXME: don't read all content to memory
rawHTML, err := ioutil.ReadAll(input) rawHTML, err := io.ReadAll(input)
if err != nil { if err != nil {
return err return err
} }

@ -8,7 +8,6 @@ package markdown
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"strings" "strings"
"sync" "sync"
@ -189,7 +188,7 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer)
// FIXME: Don't read all to memory, but goldmark doesn't support // FIXME: Don't read all to memory, but goldmark doesn't support
pc := newParserContext(ctx) pc := newParserContext(ctx)
buf, err := ioutil.ReadAll(input) buf, err := io.ReadAll(input)
if err != nil { if err != nil {
log.Error("Unable to ReadAll: %v", err) log.Error("Unable to ReadAll: %v", err)
return return

@ -7,7 +7,6 @@ package migrations
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -55,7 +54,7 @@ func (r *RepositoryRestorer) SetContext(ctx context.Context) {
func (r *RepositoryRestorer) getRepoOptions() (map[string]string, error) { func (r *RepositoryRestorer) getRepoOptions() (map[string]string, error) {
p := filepath.Join(r.baseDir, "repo.yml") p := filepath.Join(r.baseDir, "repo.yml")
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -96,7 +95,7 @@ func (r *RepositoryRestorer) GetTopics() ([]string, error) {
Topics []string `yaml:"topics"` Topics []string `yaml:"topics"`
}{} }{}
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -120,7 +119,7 @@ func (r *RepositoryRestorer) GetMilestones() ([]*base.Milestone, error) {
return nil, err return nil, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -144,7 +143,7 @@ func (r *RepositoryRestorer) GetReleases() ([]*base.Release, error) {
return nil, err return nil, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -175,7 +174,7 @@ func (r *RepositoryRestorer) GetLabels() ([]*base.Label, error) {
return nil, err return nil, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -199,7 +198,7 @@ func (r *RepositoryRestorer) GetIssues(page, perPage int) ([]*base.Issue, bool,
return nil, false, err return nil, false, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
@ -226,7 +225,7 @@ func (r *RepositoryRestorer) GetComments(opts base.GetCommentOptions) ([]*base.C
return nil, false, err return nil, false, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
@ -250,7 +249,7 @@ func (r *RepositoryRestorer) GetPullRequests(page, perPage int) ([]*base.PullReq
return nil, false, err return nil, false, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
@ -278,7 +277,7 @@ func (r *RepositoryRestorer) GetReviews(context base.IssueContext) ([]*base.Revi
return nil, err return nil, err
} }
bs, err := ioutil.ReadFile(p) bs, err := os.ReadFile(p)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -9,7 +9,7 @@ package options
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"path" "path"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -100,7 +100,7 @@ func fileFromDir(name string) ([]byte, error) {
log.Error("Unable to check if %s is a file. Error: %v", customPath, err) log.Error("Unable to check if %s is a file. Error: %v", customPath, err)
} }
if isFile { if isFile {
return ioutil.ReadFile(customPath) return os.ReadFile(customPath)
} }
staticPath := path.Join(setting.StaticRootPath, "options", name) staticPath := path.Join(setting.StaticRootPath, "options", name)
@ -110,7 +110,7 @@ func fileFromDir(name string) ([]byte, error) {
log.Error("Unable to check if %s is a file. Error: %v", staticPath, err) log.Error("Unable to check if %s is a file. Error: %v", staticPath, err)
} }
if isFile { if isFile {
return ioutil.ReadFile(staticPath) return os.ReadFile(staticPath)
} }
return []byte{}, fmt.Errorf("Asset file does not exist: %s", name) return []byte{}, fmt.Errorf("Asset file does not exist: %s", name)

@ -9,7 +9,8 @@ package options
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os"
"path" "path"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
@ -109,7 +110,7 @@ func fileFromDir(name string) ([]byte, error) {
log.Error("Unable to check if %s is a file. Error: %v", customPath, err) log.Error("Unable to check if %s is a file. Error: %v", customPath, err)
} }
if isFile { if isFile {
return ioutil.ReadFile(customPath) return os.ReadFile(customPath)
} }
f, err := Assets.Open(name) f, err := Assets.Open(name)
@ -118,7 +119,7 @@ func fileFromDir(name string) ([]byte, error) {
} }
defer f.Close() defer f.Close()
return ioutil.ReadAll(f) return io.ReadAll(f)
} }
func Asset(name string) ([]byte, error) { func Asset(name string) ([]byte, error) {
@ -127,7 +128,7 @@ func Asset(name string) ([]byte, error) {
return nil, err return nil, err
} }
defer f.Close() defer f.Close()
return ioutil.ReadAll(f) return io.ReadAll(f)
} }
func AssetNames() []string { func AssetNames() []string {

@ -6,7 +6,7 @@ package pprof
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
@ -15,7 +15,7 @@ import (
// DumpMemProfileForUsername dumps a memory profile at pprofDataPath as memprofile_<username>_<temporary id> // DumpMemProfileForUsername dumps a memory profile at pprofDataPath as memprofile_<username>_<temporary id>
func DumpMemProfileForUsername(pprofDataPath, username string) error { func DumpMemProfileForUsername(pprofDataPath, username string) error {
f, err := ioutil.TempFile(pprofDataPath, fmt.Sprintf("memprofile_%s_", username)) f, err := os.CreateTemp(pprofDataPath, fmt.Sprintf("memprofile_%s_", username))
if err != nil { if err != nil {
return err return err
} }
@ -27,7 +27,7 @@ func DumpMemProfileForUsername(pprofDataPath, username string) error {
// DumpCPUProfileForUsername dumps a CPU profile at pprofDataPath as cpuprofile_<username>_<temporary id> // DumpCPUProfileForUsername dumps a CPU profile at pprofDataPath as cpuprofile_<username>_<temporary id>
// it returns the stop function which stops, writes and closes the CPU profile file // it returns the stop function which stops, writes and closes the CPU profile file
func DumpCPUProfileForUsername(pprofDataPath, username string) (func(), error) { func DumpCPUProfileForUsername(pprofDataPath, username string) (func(), error) {
f, err := ioutil.TempFile(pprofDataPath, fmt.Sprintf("cpuprofile_%s_", username)) f, err := os.CreateTemp(pprofDataPath, fmt.Sprintf("cpuprofile_%s_", username))
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -7,7 +7,7 @@ package private
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -49,7 +49,7 @@ func AuthorizedPublicKeyByContent(ctx context.Context, content string) (string,
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err) return "", fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err)
} }
bs, err := ioutil.ReadAll(resp.Body) bs, err := io.ReadAll(resp.Body)
return string(bs), err return string(bs), err
} }

@ -7,7 +7,7 @@ package private
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
@ -45,7 +45,7 @@ func SendEmail(ctx context.Context, subject, message string, to []string) (int,
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error())
} }

@ -7,7 +7,7 @@ package private
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"time" "time"
@ -47,7 +47,7 @@ func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, units
var ret = struct { var ret = struct {
Err string `json:"err"` Err string `json:"err"`
}{} }{}
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error())
} }

@ -11,7 +11,6 @@ import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"io" "io"
"io/ioutil"
"mime" "mime"
"net/http" "net/http"
"os" "os"
@ -31,7 +30,7 @@ func Asset(name string) ([]byte, error) {
return nil, err return nil, err
} }
defer f.Close() defer f.Close()
return ioutil.ReadAll(f) return io.ReadAll(f)
} }
func AssetNames() []string { func AssetNames() []string {

@ -5,7 +5,7 @@
package queue package queue
import ( import (
"io/ioutil" "os"
"sync" "sync"
"testing" "testing"
@ -26,7 +26,7 @@ func TestPersistableChannelQueue(t *testing.T) {
queueShutdown := []func(){} queueShutdown := []func(){}
queueTerminate := []func(){} queueTerminate := []func(){}
tmpDir, err := ioutil.TempDir("", "persistable-channel-queue-test-data") tmpDir, err := os.MkdirTemp("", "persistable-channel-queue-test-data")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)

@ -5,7 +5,7 @@
package queue package queue
import ( import (
"io/ioutil" "os"
"sync" "sync"
"testing" "testing"
"time" "time"
@ -28,7 +28,7 @@ func TestLevelQueue(t *testing.T) {
queueShutdown := []func(){} queueShutdown := []func(){}
queueTerminate := []func(){} queueTerminate := []func(){}
tmpDir, err := ioutil.TempDir("", "level-queue-test-data") tmpDir, err := os.MkdirTemp("", "level-queue-test-data")
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)

@ -7,7 +7,7 @@ package recaptcha
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@ -46,7 +46,7 @@ func Verify(ctx context.Context, response string) (bool, error) {
return false, fmt.Errorf("Failed to send CAPTCHA response: %s", err) return false, fmt.Errorf("Failed to send CAPTCHA response: %s", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return false, fmt.Errorf("Failed to read CAPTCHA response: %s", err) return false, fmt.Errorf("Failed to read CAPTCHA response: %s", err)
} }

@ -6,7 +6,6 @@ package repository
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -85,7 +84,7 @@ func checkGiteaTemplate(tmpDir string) (*models.GiteaTemplate, error) {
return nil, err return nil, err
} }
content, err := ioutil.ReadFile(gtPath) content, err := os.ReadFile(gtPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -151,12 +150,12 @@ func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmp
base := strings.TrimPrefix(filepath.ToSlash(path), tmpDirSlash) base := strings.TrimPrefix(filepath.ToSlash(path), tmpDirSlash)
for _, g := range gt.Globs() { for _, g := range gt.Globs() {
if g.Match(base) { if g.Match(base) {
content, err := ioutil.ReadFile(path) content, err := os.ReadFile(path)
if err != nil { if err != nil {
return err return err
} }
if err := ioutil.WriteFile(path, if err := os.WriteFile(path,
[]byte(generateExpansion(string(content), templateRepo, generateRepo)), []byte(generateExpansion(string(content), templateRepo, generateRepo)),
0644); err != nil { 0644); err != nil {
return err return err
@ -187,7 +186,7 @@ func generateRepoCommit(repo, templateRepo, generateRepo *models.Repository, tmp
} }
func generateGitContent(ctx *db.Context, repo, templateRepo, generateRepo *models.Repository) (err error) { func generateGitContent(ctx *db.Context, repo, templateRepo, generateRepo *models.Repository) (err error) {
tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name) tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-"+repo.Name)
if err != nil { if err != nil {
return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err) return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err)
} }

@ -7,7 +7,6 @@ package repository
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -110,7 +109,7 @@ func createDelegateHooks(repoPath string) (err error) {
if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) { if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err) return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err)
} }
if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil { if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err) return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
} }
@ -121,7 +120,7 @@ func createDelegateHooks(repoPath string) (err error) {
if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) { if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err) return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err)
} }
if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil { if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
return fmt.Errorf("write new hook file '%s': %v", newHookPath, err) return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
} }
@ -192,7 +191,7 @@ func CheckDelegateHooks(repoPath string) ([]string, error) {
if cont { if cont {
continue continue
} }
contents, err := ioutil.ReadFile(oldHookPath) contents, err := os.ReadFile(oldHookPath)
if err != nil { if err != nil {
return results, err return results, err
} }
@ -202,7 +201,7 @@ func CheckDelegateHooks(repoPath string) ([]string, error) {
if !checkExecutable(oldHookPath) { if !checkExecutable(oldHookPath) {
results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath)) results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath))
} }
contents, err = ioutil.ReadFile(newHookPath) contents, err = os.ReadFile(newHookPath)
if err != nil { if err != nil {
return results, err return results, err
} }

@ -7,7 +7,6 @@ package repository
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -59,7 +58,7 @@ func prepareRepoCommit(ctx *db.Context, repo *models.Repository, tmpDir, repoPat
"CloneURL.HTTPS": cloneLink.HTTPS, "CloneURL.HTTPS": cloneLink.HTTPS,
"OwnerName": repo.OwnerName, "OwnerName": repo.OwnerName,
} }
if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"), if err = os.WriteFile(filepath.Join(tmpDir, "README.md"),
[]byte(com.Expand(string(data), match)), 0644); err != nil { []byte(com.Expand(string(data), match)), 0644); err != nil {
return fmt.Errorf("write README.md: %v", err) return fmt.Errorf("write README.md: %v", err)
} }
@ -79,7 +78,7 @@ func prepareRepoCommit(ctx *db.Context, repo *models.Repository, tmpDir, repoPat
} }
if buf.Len() > 0 { if buf.Len() > 0 {
if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil { if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
return fmt.Errorf("write .gitignore: %v", err) return fmt.Errorf("write .gitignore: %v", err)
} }
} }
@ -92,7 +91,7 @@ func prepareRepoCommit(ctx *db.Context, repo *models.Repository, tmpDir, repoPat
return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err) return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err)
} }
if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil { if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
return fmt.Errorf("write LICENSE: %v", err) return fmt.Errorf("write LICENSE: %v", err)
} }
} }
@ -291,7 +290,7 @@ func initRepository(ctx *db.Context, repoPath string, u *models.User, repo *mode
// Initialize repository according to user's choice. // Initialize repository according to user's choice.
if opts.AutoInit { if opts.AutoInit {
tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-"+repo.Name) tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-"+repo.Name)
if err != nil { if err != nil {
return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err) return fmt.Errorf("Failed to create temp dir for repository %s: %v", repo.RepoPath(), err)
} }

@ -9,7 +9,6 @@ import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math" "math"
"net" "net"
"net/url" "net/url"
@ -764,7 +763,7 @@ func NewContext() {
if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled { if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled {
fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem")) fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem"))
if err := ioutil.WriteFile(fname, if err := os.WriteFile(fname,
[]byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil { []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil {
log.Fatal("Failed to create '%s': %v", fname, err) log.Fatal("Failed to create '%s': %v", fname, err)
} }
@ -1030,7 +1029,7 @@ func loadInternalToken(sec *ini.Section) string {
} }
defer fp.Close() defer fp.Close()
buf, err := ioutil.ReadAll(fp) buf, err := io.ReadAll(fp)
if err != nil { if err != nil {
log.Fatal("Failed to read InternalTokenURI (%s): %v", uri, err) log.Fatal("Failed to read InternalTokenURI (%s): %v", uri, err)
} }

@ -7,7 +7,6 @@ package storage
import ( import (
"context" "context"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
@ -76,7 +75,7 @@ func (l *LocalStorage) Save(path string, r io.Reader, size int64) (int64, error)
if err := os.MkdirAll(l.tmpdir, os.ModePerm); err != nil { if err := os.MkdirAll(l.tmpdir, os.ModePerm); err != nil {
return 0, err return 0, err
} }
tmp, err := ioutil.TempFile(l.tmpdir, "upload-*") tmp, err := os.CreateTemp(l.tmpdir, "upload-*")
if err != nil { if err != nil {
return 0, err return 0, err
} }

@ -8,7 +8,7 @@
package svg package svg
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -20,7 +20,7 @@ func Discover() map[string]string {
files, _ := filepath.Glob(filepath.Join(setting.StaticRootPath, "public", "img", "svg", "*.svg")) files, _ := filepath.Glob(filepath.Join(setting.StaticRootPath, "public", "img", "svg", "*.svg"))
for _, file := range files { for _, file := range files {
content, err := ioutil.ReadFile(file) content, err := os.ReadFile(file)
if err == nil { if err == nil {
filename := filepath.Base(file) filename := filepath.Base(file)
svgs[filename[:len(filename)-4]] = string(content) svgs[filename[:len(filename)-4]] = string(content)

@ -9,7 +9,6 @@ package templates
import ( import (
"html/template" "html/template"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -28,14 +27,14 @@ var (
// GetAsset returns asset content via name // GetAsset returns asset content via name
func GetAsset(name string) ([]byte, error) { func GetAsset(name string) ([]byte, error) {
bs, err := ioutil.ReadFile(filepath.Join(setting.CustomPath, name)) bs, err := os.ReadFile(filepath.Join(setting.CustomPath, name))
if err != nil && !os.IsNotExist(err) { if err != nil && !os.IsNotExist(err) {
return nil, err return nil, err
} else if err == nil { } else if err == nil {
return bs, nil return bs, nil
} }
return ioutil.ReadFile(filepath.Join(setting.StaticRootPath, name)) return os.ReadFile(filepath.Join(setting.StaticRootPath, name))
} }
// GetAssetNames returns assets list // GetAssetNames returns assets list
@ -71,7 +70,7 @@ func Mailer() (*texttmpl.Template, *template.Template) {
continue continue
} }
content, err := ioutil.ReadFile(path.Join(staticDir, filePath)) content, err := os.ReadFile(path.Join(staticDir, filePath))
if err != nil { if err != nil {
log.Warn("Failed to read static %s template. %v", filePath, err) log.Warn("Failed to read static %s template. %v", filePath, err)
@ -100,7 +99,7 @@ func Mailer() (*texttmpl.Template, *template.Template) {
continue continue
} }
content, err := ioutil.ReadFile(path.Join(customDir, filePath)) content, err := os.ReadFile(path.Join(customDir, filePath))
if err != nil { if err != nil {
log.Warn("Failed to read custom %s template. %v", filePath, err) log.Warn("Failed to read custom %s template. %v", filePath, err)

@ -9,7 +9,7 @@ package templates
import ( import (
"html/template" "html/template"
"io/ioutil" "io"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -28,7 +28,7 @@ var (
// GetAsset get a special asset, only for chi // GetAsset get a special asset, only for chi
func GetAsset(name string) ([]byte, error) { func GetAsset(name string) ([]byte, error) {
bs, err := ioutil.ReadFile(filepath.Join(setting.CustomPath, name)) bs, err := os.ReadFile(filepath.Join(setting.CustomPath, name))
if err != nil && !os.IsNotExist(err) { if err != nil && !os.IsNotExist(err) {
return nil, err return nil, err
} else if err == nil { } else if err == nil {
@ -103,7 +103,7 @@ func Mailer() (*texttmpl.Template, *template.Template) {
continue continue
} }
content, err := ioutil.ReadFile(path.Join(customDir, filePath)) content, err := os.ReadFile(path.Join(customDir, filePath))
if err != nil { if err != nil {
log.Warn("Failed to read custom %s template. %v", filePath, err) log.Warn("Failed to read custom %s template. %v", filePath, err)
@ -130,7 +130,7 @@ func Asset(name string) ([]byte, error) {
return nil, err return nil, err
} }
defer f.Close() defer f.Close()
return ioutil.ReadAll(f) return io.ReadAll(f)
} }
func AssetNames() []string { func AssetNames() []string {

@ -5,7 +5,7 @@
package misc package misc
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -172,7 +172,7 @@ func TestAPI_RenderRaw(t *testing.T) {
ctx := wrap(m) ctx := wrap(m)
for i := 0; i < len(simpleCases); i += 2 { for i := 0; i < len(simpleCases); i += 2 {
ctx.Req.Body = ioutil.NopCloser(strings.NewReader(simpleCases[i])) ctx.Req.Body = io.NopCloser(strings.NewReader(simpleCases[i]))
MarkdownRaw(ctx) MarkdownRaw(ctx)
assert.Equal(t, simpleCases[i+1], resp.Body.String()) assert.Equal(t, simpleCases[i+1], resp.Body.String())
resp.Body.Reset() resp.Body.Reset()

@ -5,7 +5,7 @@
package private package private
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
myCtx "code.gitea.io/gitea/modules/context" myCtx "code.gitea.io/gitea/modules/context"
@ -16,7 +16,7 @@ import (
// RestoreRepo restore a repository from data // RestoreRepo restore a repository from data
func RestoreRepo(ctx *myCtx.PrivateContext) { func RestoreRepo(ctx *myCtx.PrivateContext) {
bs, err := ioutil.ReadAll(ctx.Req.Body) bs, err := io.ReadAll(ctx.Req.Body)
if err != nil { if err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{ ctx.JSON(http.StatusInternalServerError, private.Response{
Err: err.Error(), Err: err.Error(),

@ -6,7 +6,7 @@ package repo
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path" "path"
"strings" "strings"
@ -127,7 +127,7 @@ func editFile(ctx *context.Context, isNewFile bool) {
return return
} }
d, _ := ioutil.ReadAll(dataRc) d, _ := io.ReadAll(dataRc)
if err := dataRc.Close(); err != nil { if err := dataRc.Close(); err != nil {
log.Error("Error whilst closing blob data: %v", err) log.Error("Error whilst closing blob data: %v", err)
} }

@ -10,7 +10,6 @@ import (
"compress/gzip" "compress/gzip"
gocontext "context" gocontext "context"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@ -308,7 +307,7 @@ var (
func dummyInfoRefs(ctx *context.Context) { func dummyInfoRefs(ctx *context.Context) {
infoRefsOnce.Do(func() { infoRefsOnce.Do(func() {
tmpDir, err := ioutil.TempDir(os.TempDir(), "gitea-info-refs-cache") tmpDir, err := os.MkdirTemp(os.TempDir(), "gitea-info-refs-cache")
if err != nil { if err != nil {
log.Error("Failed to create temp dir for git-receive-pack cache: %v", err) log.Error("Failed to create temp dir for git-receive-pack cache: %v", err)
return return

@ -9,7 +9,7 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path" "path"
"strconv" "strconv"
@ -707,7 +707,7 @@ func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (str
return "", false return "", false
} }
defer r.Close() defer r.Close()
bytes, err = ioutil.ReadAll(r) bytes, err = io.ReadAll(r)
if err != nil { if err != nil {
return "", false return "", false
} }

@ -9,7 +9,6 @@ import (
"fmt" "fmt"
gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"path" "path"
"strconv" "strconv"
@ -300,7 +299,7 @@ func LFSFileGet(ctx *context.Context) {
buf := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc)) buf := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc))
// Building code view blocks with line number on server side. // Building code view blocks with line number on server side.
fileContent, _ := ioutil.ReadAll(buf) fileContent, _ := io.ReadAll(buf)
var output bytes.Buffer var output bytes.Buffer
lines := strings.Split(string(fileContent), "\n") lines := strings.Split(string(fileContent), "\n")

@ -8,7 +8,7 @@ package repo
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@ -1126,9 +1126,9 @@ func UpdateAvatarSetting(ctx *context.Context, form forms.AvatarForm) error {
return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big")) return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
} }
data, err := ioutil.ReadAll(r) data, err := io.ReadAll(r)
if err != nil { if err != nil {
return fmt.Errorf("ioutil.ReadAll: %v", err) return fmt.Errorf("io.ReadAll: %v", err)
} }
st := typesniffer.DetectContentType(data) st := typesniffer.DetectContentType(data)
if !(st.IsImage() && !st.IsSvgImage()) { if !(st.IsImage() && !st.IsSvgImage()) {

@ -5,8 +5,8 @@
package repo package repo
import ( import (
"io/ioutil"
"net/http" "net/http"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -22,7 +22,7 @@ import (
) )
func createSSHAuthorizedKeysTmpPath(t *testing.T) func() { func createSSHAuthorizedKeysTmpPath(t *testing.T) func() {
tmpDir, err := ioutil.TempDir("", "tmp-ssh") tmpDir, err := os.MkdirTemp("", "tmp-ssh")
if err != nil { if err != nil {
assert.Fail(t, "Unable to create temporary directory: %v", err) assert.Fail(t, "Unable to create temporary directory: %v", err)
return nil return nil

@ -11,7 +11,6 @@ import (
"fmt" "fmt"
gotemplate "html/template" gotemplate "html/template"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -344,7 +343,7 @@ func renderDirectory(ctx *context.Context, treeLink string) {
}, rd, &result) }, rd, &result)
if err != nil { if err != nil {
log.Error("Render failed: %v then fallback", err) log.Error("Render failed: %v then fallback", err)
bs, _ := ioutil.ReadAll(rd) bs, _ := io.ReadAll(rd)
ctx.Data["FileContent"] = strings.ReplaceAll( ctx.Data["FileContent"] = strings.ReplaceAll(
gotemplate.HTMLEscapeString(string(bs)), "\n", `<br>`, gotemplate.HTMLEscapeString(string(bs)), "\n", `<br>`,
) )
@ -353,7 +352,7 @@ func renderDirectory(ctx *context.Context, treeLink string) {
} }
} else { } else {
ctx.Data["IsRenderedHTML"] = true ctx.Data["IsRenderedHTML"] = true
buf, err = ioutil.ReadAll(rd) buf, err = io.ReadAll(rd)
if err != nil { if err != nil {
log.Error("ReadAll failed: %v", err) log.Error("ReadAll failed: %v", err)
} }
@ -528,13 +527,13 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
} }
ctx.Data["FileContent"] = result.String() ctx.Data["FileContent"] = result.String()
} else if readmeExist { } else if readmeExist {
buf, _ := ioutil.ReadAll(rd) buf, _ := io.ReadAll(rd)
ctx.Data["IsRenderedHTML"] = true ctx.Data["IsRenderedHTML"] = true
ctx.Data["FileContent"] = strings.ReplaceAll( ctx.Data["FileContent"] = strings.ReplaceAll(
gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`,
) )
} else { } else {
buf, _ := ioutil.ReadAll(rd) buf, _ := io.ReadAll(rd)
lineNums := linesBytesCount(buf) lineNums := linesBytesCount(buf)
ctx.Data["NumLines"] = strconv.Itoa(lineNums) ctx.Data["NumLines"] = strconv.Itoa(lineNums)
ctx.Data["NumLinesSet"] = true ctx.Data["NumLinesSet"] = true

@ -8,7 +8,7 @@ package repo
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path/filepath" "path/filepath"
@ -110,7 +110,7 @@ func wikiContentsByEntry(ctx *context.Context, entry *git.TreeEntry) []byte {
return nil return nil
} }
defer reader.Close() defer reader.Close()
content, err := ioutil.ReadAll(reader) content, err := io.ReadAll(reader)
if err != nil { if err != nil {
ctx.ServerError("ReadAll", err) ctx.ServerError("ReadAll", err)
return nil return nil

@ -5,7 +5,7 @@
package repo package repo
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"testing" "testing"
@ -47,7 +47,7 @@ func wikiContent(t *testing.T, repo *models.Repository, wikiName string) string
reader, err := entry.Blob().DataAsync() reader, err := entry.Blob().DataAsync()
assert.NoError(t, err) assert.NoError(t, err)
defer reader.Close() defer reader.Close()
bytes, err := ioutil.ReadAll(reader) bytes, err := io.ReadAll(reader)
assert.NoError(t, err) assert.NoError(t, err)
return string(bytes) return string(bytes)
} }

@ -9,7 +9,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"strings" "strings"
@ -704,7 +703,7 @@ func updateAvatarIfNeed(url string, u *models.User) {
} }
// ignore any error // ignore any error
if err == nil && resp.StatusCode == http.StatusOK { if err == nil && resp.StatusCode == http.StatusOK {
data, err := ioutil.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1)) data, err := io.ReadAll(io.LimitReader(resp.Body, setting.Avatar.MaxFileSize+1))
if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize { if err == nil && int64(len(data)) <= setting.Avatar.MaxFileSize {
_ = u.UploadAvatar(data) _ = u.UploadAvatar(data)
} }

@ -8,7 +8,7 @@ package setting
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@ -167,9 +167,9 @@ func UpdateAvatarSetting(ctx *context.Context, form *forms.AvatarForm, ctxUser *
return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big")) return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
} }
data, err := ioutil.ReadAll(fr) data, err := io.ReadAll(fr)
if err != nil { if err != nil {
return fmt.Errorf("ioutil.ReadAll: %v", err) return fmt.Errorf("io.ReadAll: %v", err)
} }
st := typesniffer.DetectContentType(data) st := typesniffer.DetectContentType(data)

@ -15,7 +15,6 @@ import (
"encoding/base64" "encoding/base64"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil"
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
@ -429,7 +428,7 @@ func loadOrCreateAsymmetricKey() (interface{}, error) {
} }
} }
bytes, err := ioutil.ReadFile(keyPath) bytes, err := os.ReadFile(keyPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -13,7 +13,6 @@ import (
"html" "html"
"html/template" "html/template"
"io" "io"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
@ -721,7 +720,7 @@ parsingLoop:
// TODO: Handle skipping first n files // TODO: Handle skipping first n files
if len(diff.Files) >= maxFiles { if len(diff.Files) >= maxFiles {
diff.IsIncomplete = true diff.IsIncomplete = true
_, err := io.Copy(ioutil.Discard, reader) _, err := io.Copy(io.Discard, reader)
if err != nil { if err != nil {
// By the definition of io.Copy this never returns io.EOF // By the definition of io.Copy this never returns io.EOF
return diff, fmt.Errorf("Copy: %v", err) return diff, fmt.Errorf("Copy: %v", err)
@ -1280,7 +1279,7 @@ func GetDiffRangeWithWhitespaceBehavior(gitRepo *git.Repository, beforeCommitID,
indexFilename, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(afterCommitID) indexFilename, deleteTemporaryFile, err := gitRepo.ReadTreeToTemporaryIndex(afterCommitID)
if err == nil { if err == nil {
defer deleteTemporaryFile() defer deleteTemporaryFile()
workdir, err := ioutil.TempDir("", "empty-work-dir") workdir, err := os.MkdirTemp("", "empty-work-dir")
if err != nil { if err != nil {
log.Error("Unable to create temporary directory: %v", err) log.Error("Unable to create temporary directory: %v", err)
return nil, err return nil, err

@ -8,7 +8,6 @@ package pull
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -75,7 +74,7 @@ func getMergeCommit(pr *models.PullRequest) (*git.Commit, error) {
} }
} }
indexTmpPath, err := ioutil.TempDir(os.TempDir(), "gitea-"+pr.BaseRepo.Name) indexTmpPath, err := os.MkdirTemp(os.TempDir(), "gitea-"+pr.BaseRepo.Name)
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to create temp dir for repository %s: %v", pr.BaseRepo.RepoPath(), err) return nil, fmt.Errorf("Failed to create temp dir for repository %s: %v", pr.BaseRepo.RepoPath(), err)
} }
@ -98,7 +97,7 @@ func getMergeCommit(pr *models.PullRequest) (*git.Commit, error) {
return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err) return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err)
} }
commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile) commitIDBytes, err := os.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
if err != nil { if err != nil {
return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err) return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
} }

@ -9,7 +9,6 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -149,7 +148,7 @@ func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.Merge
} }
sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout") sparseCheckoutListPath := filepath.Join(infoPath, "sparse-checkout")
if err := ioutil.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil { if err := os.WriteFile(sparseCheckoutListPath, []byte(sparseCheckoutList), 0600); err != nil {
log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err) log.Error("Unable to write .git/info/sparse-checkout file in %s: %v", tmpBasePath, err)
return "", fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err) return "", fmt.Errorf("Unable to write .git/info/sparse-checkout file in tmpBasePath: %v", err)
} }
@ -276,7 +275,7 @@ func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.Merge
} }
for _, failingCommitPath := range failingCommitPaths { for _, failingCommitPath := range failingCommitPaths {
if _, statErr := os.Stat(filepath.Join(failingCommitPath)); statErr == nil { if _, statErr := os.Stat(filepath.Join(failingCommitPath)); statErr == nil {
commitShaBytes, readErr := ioutil.ReadFile(filepath.Join(failingCommitPath)) commitShaBytes, readErr := os.ReadFile(filepath.Join(failingCommitPath))
if readErr != nil { if readErr != nil {
// Abandon this attempt to handle the error // Abandon this attempt to handle the error
log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String()) log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save