Replace deprecated ioutil with io and os (#20776)

* Replace ioutil with io and os

* Replace ioutil in utils/file.go

* Minor fix to tests and excluded files

Co-authored-by: Tim Scheuermann <tim.scheuermann@mattermost.com>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Этот коммит содержится в:
Tim Scheuermann
2022-08-09 14:25:46 +03:00
коммит произвёл GitHub
родитель 15b6046a62
Коммит b4570afa90
115 изменённых файлов: 408 добавлений и 475 удалений

Просмотреть файл

@@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
"net" "net"
"net/http" "net/http"
@@ -84,7 +83,7 @@ func SetMainHelper(mh *testlib.MainHelper) {
func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, enterprise bool, includeCache bool, func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, enterprise bool, includeCache bool,
updateConfig func(*model.Config), options []app.Option) *TestHelper { updateConfig func(*model.Config), options []app.Option) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "apptest") tempWorkspace, err := os.MkdirTemp("", "apptest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -5,7 +5,7 @@ package api4
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"strings" "strings"
"testing" "testing"
@@ -461,7 +461,7 @@ func TestPatchBot(t *testing.T) {
r, err := th.Client.DoAPIPut("/bots/"+createdBot.UserId, `{"creator_id":"`+th.BasicUser2.Id+`"}`) r, err := th.Client.DoAPIPut("/bots/"+createdBot.UserId, `{"creator_id":"`+th.BasicUser2.Id+`"}`)
require.NoError(t, err) require.NoError(t, err)
defer func() { defer func() {
_, _ = ioutil.ReadAll(r.Body) _, _ = io.ReadAll(r.Body)
_ = r.Body.Close() _ = r.Body.Close()
}() }()
var patchedBot *model.Bot var patchedBot *model.Bot

Просмотреть файл

@@ -7,7 +7,7 @@ import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"time" "time"
@@ -123,7 +123,7 @@ func changeSubscription(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.changeSubscription", "api.cloud.app_error", nil, err.Error(), http.StatusBadRequest) c.Err = model.NewAppError("Api4.changeSubscription", "api.cloud.app_error", nil, err.Error(), http.StatusBadRequest)
return return
@@ -174,7 +174,7 @@ func requestCloudTrial(c *Context, w http.ResponseWriter, r *http.Request) {
} }
// check if the email needs to be set // check if the email needs to be set
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return
@@ -221,7 +221,7 @@ func validateBusinessEmail(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return
@@ -394,7 +394,7 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.updateCloudCustomer", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.updateCloudCustomer", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return
@@ -432,7 +432,7 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque
return return
} }
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.updateCloudCustomerAddress", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.updateCloudCustomerAddress", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return
@@ -504,7 +504,7 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request)
auditRec := c.MakeAuditRecord("confirmCustomerPayment", audit.Fail) auditRec := c.MakeAuditRecord("confirmCustomerPayment", audit.Fail)
defer c.LogAuditRec(auditRec) defer c.LogAuditRec(auditRec)
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.confirmCustomerPayment", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.confirmCustomerPayment", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return
@@ -594,7 +594,7 @@ func handleCWSWebhook(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
bodyBytes, err := ioutil.ReadAll(r.Body) bodyBytes, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.handleCWSWebhook", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) c.Err = model.NewAppError("Api4.handleCWSWebhook", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError)
return return

Просмотреть файл

@@ -6,7 +6,7 @@ package api4
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"strings" "strings"
@@ -533,7 +533,7 @@ func TestUpdateConfigRestrictSystemAdmin(t *testing.T) {
} }
func TestUpdateConfigDiffInAuditRecord(t *testing.T) { func TestUpdateConfigDiffInAuditRecord(t *testing.T) {
logFile, err := ioutil.TempFile("", "adv.log") logFile, err := os.CreateTemp("", "adv.log")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(logFile.Name()) defer os.Remove(logFile.Name())
@@ -569,7 +569,7 @@ func TestUpdateConfigDiffInAuditRecord(t *testing.T) {
require.NoError(t, logFile.Sync()) require.NoError(t, logFile.Sync())
data, err := ioutil.ReadAll(logFile) data, err := io.ReadAll(logFile)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, data) require.NotEmpty(t, data)
@@ -955,7 +955,7 @@ func TestMigrateConfig(t *testing.T) {
file, err := json.MarshalIndent(cfg, "", " ") file, err := json.MarshalIndent(cfg, "", " ")
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile("from.json", file, 0644) err = os.WriteFile("from.json", file, 0644)
require.NoError(t, err) require.NoError(t, err)
defer os.Remove("from.json") defer os.Remove("from.json")

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"bytes" "bytes"
"image" "image"
_ "image/gif" _ "image/gif"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -100,7 +99,7 @@ func TestCreateEmoji(t *testing.T) {
} }
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
bytes, err := ioutil.ReadFile(filepath.Join(path, "testwebp.webp")) bytes, err := os.ReadFile(filepath.Join(path, "testwebp.webp"))
require.NoError(t, err) require.NoError(t, err)
newEmoji, _, err = client.CreateEmoji(emoji, bytes, "image.webp") newEmoji, _, err = client.CreateEmoji(emoji, bytes, "image.webp")
require.NoError(t, err) require.NoError(t, err)

Просмотреть файл

@@ -6,7 +6,6 @@ package api4
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -151,7 +150,7 @@ func TestDownloadExport(t *testing.T) {
data := randomBytes(t, 1024*1024) data := randomBytes(t, 1024*1024)
var buf bytes.Buffer var buf bytes.Buffer
exportName := "export.zip" exportName := "export.zip"
err = ioutil.WriteFile(filepath.Join(exportDir, exportName), data, 0600) err = os.WriteFile(filepath.Join(exportDir, exportName), data, 0600)
require.NoError(t, err) require.NoError(t, err)
n, _, err := c.DownloadExport(exportName, &buf, 0) n, _, err := c.DownloadExport(exportName, &buf, 0)
@@ -168,7 +167,7 @@ func TestDownloadExport(t *testing.T) {
data := randomBytes(t, 1024*1024) data := randomBytes(t, 1024*1024)
var buf bytes.Buffer var buf bytes.Buffer
exportName := "export.zip" exportName := "export.zip"
err = ioutil.WriteFile(filepath.Join(exportDir, exportName), data, 0600) err = os.WriteFile(filepath.Join(exportDir, exportName), data, 0600)
require.NoError(t, err) require.NoError(t, err)
offset := 1024 * 512 offset := 1024 * 512

Просмотреть файл

@@ -9,7 +9,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/textproto" "net/textproto"
@@ -55,7 +54,7 @@ func fileBytes(t *testing.T, path string) []byte {
f, err := os.Open(path) f, err := os.Open(path)
require.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
bb, err := ioutil.ReadAll(f) bb, err := io.ReadAll(f)
require.NoError(t, err) require.NoError(t, err)
return bb return bb
} }
@@ -701,10 +700,10 @@ func TestUploadFiles(t *testing.T) {
data, _, err := get(ri.Id) data, _, err := get(ri.Id)
require.NoError(t, err) require.NoError(t, err)
expected, err := ioutil.ReadFile(filepath.Join(testDir, name)) expected, err := os.ReadFile(filepath.Join(testDir, name))
require.NoError(t, err) require.NoError(t, err)
if !bytes.Equal(data, expected) { if !bytes.Equal(data, expected) {
tf, err := ioutil.TempFile("", fmt.Sprintf("test_%v_*_%s", i, name)) tf, err := os.CreateTemp("", fmt.Sprintf("test_%v_*_%s", i, name))
require.NoError(t, err) require.NoError(t, err)
defer tf.Close() defer tf.Close()
_, err = io.Copy(tf, bytes.NewReader(data)) _, err = io.Copy(tf, bytes.NewReader(data))

Просмотреть файл

@@ -6,7 +6,7 @@ package api4
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -293,7 +293,7 @@ func linkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
} }
syncableType := c.Params.SyncableType syncableType := c.Params.SyncableType
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.createGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest) c.Err = model.NewAppError("Api4.createGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest)
return return
@@ -464,7 +464,7 @@ func patchGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) {
} }
syncableType := c.Params.SyncableType syncableType := c.Params.SyncableType
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest) c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest)
return return
@@ -1109,8 +1109,8 @@ func deleteGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) {
// licensedAndConfiguredForGroupBySource returns an app error if not properly license or configured for the given group type. The returned app error // licensedAndConfiguredForGroupBySource returns an app error if not properly license or configured for the given group type. The returned app error
// will have a blank 'Where' field, which should be subsequently set by the caller, for example: // will have a blank 'Where' field, which should be subsequently set by the caller, for example:
// //
// err := licensedAndConfiguredForGroupBySource(c.App, group.Source) // err := licensedAndConfiguredForGroupBySource(c.App, group.Source)
// err.Where = "Api4.getGroup" // err.Where = "Api4.getGroup"
// //
// Temporarily, this function also checks for the CustomGroups feature flag. // Temporarily, this function also checks for the CustomGroups feature flag.
func licensedAndConfiguredForGroupBySource(app app.AppIface, source model.GroupSource) *model.AppError { func licensedAndConfiguredForGroupBySource(app app.AppIface, source model.GroupSource) *model.AppError {

Просмотреть файл

@@ -4,7 +4,7 @@
package api4 package api4
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -89,7 +89,7 @@ func TestGetImage(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, http.StatusOK, resp.StatusCode)
respBody, err := ioutil.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "success", string(respBody)) assert.Equal(t, "success", string(respBody))

Просмотреть файл

@@ -5,7 +5,7 @@ package api4
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -21,7 +21,7 @@ type testHandler struct {
} }
func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
bb, err := ioutil.ReadAll(r.Body) bb, err := io.ReadAll(r.Body)
assert.NoError(th.t, err) assert.NoError(th.t, err)
assert.NotEmpty(th.t, string(bb)) assert.NotEmpty(th.t, string(bb))
var poir model.PostActionIntegrationRequest var poir model.PostActionIntegrationRequest

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/shared/mlog"
@@ -203,7 +202,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) {
ReceiveEmailsAccepted bool `json:"receive_emails_accepted"` ReceiveEmailsAccepted bool `json:"receive_emails_accepted"`
} }
b, readErr := ioutil.ReadAll(r.Body) b, readErr := io.ReadAll(r.Body)
if readErr != nil { if readErr != nil {
c.Err = model.NewAppError("requestTrialLicense", "api.license.request-trial.bad-request", nil, "", http.StatusBadRequest) c.Err = model.NewAppError("requestTrialLicense", "api.license.request-trial.bad-request", nil, "", http.StatusBadRequest)
return return

Просмотреть файл

@@ -8,7 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -44,7 +44,7 @@ func TestPlugin(t *testing.T) {
}) })
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
// Install from URL // Install from URL
@@ -295,7 +295,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) {
}) })
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
testCluster.ClearMessages() testCluster.ClearMessages()
@@ -378,7 +378,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) {
func TestDisableOnRemove(t *testing.T) { func TestDisableOnRemove(t *testing.T) {
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
testCases := []struct { testCases := []struct {
@@ -723,7 +723,7 @@ func TestGetInstalledMarketplacePlugins(t *testing.T) {
} }
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
t.Run("marketplace client returns not-installed plugin", func(t *testing.T) { t.Run("marketplace client returns not-installed plugin", func(t *testing.T) {
@@ -752,7 +752,7 @@ func TestGetInstalledMarketplacePlugins(t *testing.T) {
manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData))
require.NoError(t, err) require.NoError(t, err)
testIcon, err := ioutil.ReadFile(filepath.Join(path, "test.svg")) testIcon, err := os.ReadFile(filepath.Join(path, "test.svg"))
require.NoError(t, err) require.NoError(t, err)
require.True(t, svg.Is(testIcon)) require.True(t, svg.Is(testIcon))
testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon)) testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon))
@@ -860,13 +860,13 @@ func TestSearchGetMarketplacePlugins(t *testing.T) {
} }
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
tarDataV2, err := ioutil.ReadFile(filepath.Join(path, "testplugin2.tar.gz")) tarDataV2, err := os.ReadFile(filepath.Join(path, "testplugin2.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
testIcon, err := ioutil.ReadFile(filepath.Join(path, "test.svg")) testIcon, err := os.ReadFile(filepath.Join(path, "test.svg"))
require.NoError(t, err) require.NoError(t, err)
require.True(t, svg.Is(testIcon)) require.True(t, svg.Is(testIcon))
testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon)) testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon))
@@ -1021,7 +1021,7 @@ func TestGetLocalPluginInMarketplace(t *testing.T) {
// Upload one local plugin // Upload one local plugin
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData))
@@ -1050,13 +1050,13 @@ func TestGetLocalPluginInMarketplace(t *testing.T) {
// Upload one local plugin // Upload one local plugin
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData))
require.NoError(t, err) require.NoError(t, err)
testIcon, err := ioutil.ReadFile(filepath.Join(path, "test.svg")) testIcon, err := os.ReadFile(filepath.Join(path, "test.svg"))
require.NoError(t, err) require.NoError(t, err)
require.True(t, svg.Is(testIcon)) require.True(t, svg.Is(testIcon))
testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon)) testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon))
@@ -1090,13 +1090,13 @@ func TestGetLocalPluginInMarketplace(t *testing.T) {
// Upload one local plugin // Upload one local plugin
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData))
require.NoError(t, err) require.NoError(t, err)
testIcon, err := ioutil.ReadFile(filepath.Join(path, "test.svg")) testIcon, err := os.ReadFile(filepath.Join(path, "test.svg"))
require.NoError(t, err) require.NoError(t, err)
require.True(t, svg.Is(testIcon)) require.True(t, svg.Is(testIcon))
testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon)) testIconData := fmt.Sprintf("data:image/svg+xml;base64,%s", base64.StdEncoding.EncodeToString(testIcon))
@@ -1262,11 +1262,11 @@ func TestInstallMarketplacePlugin(t *testing.T) {
signatureFilename := "testplugin2.tar.gz.sig" signatureFilename := "testplugin2.tar.gz.sig"
signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename)) signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename))
require.NoError(t, err) require.NoError(t, err)
sigFile, err := ioutil.ReadAll(signatureFileReader) sigFile, err := io.ReadAll(signatureFileReader)
require.NoError(t, err) require.NoError(t, err)
pluginSignature := base64.StdEncoding.EncodeToString(sigFile) pluginSignature := base64.StdEncoding.EncodeToString(sigFile)
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin2.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin2.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK) res.WriteHeader(http.StatusOK)
@@ -1622,7 +1622,7 @@ func TestInstallMarketplacePlugin(t *testing.T) {
th2.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { th2.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
pluginSignatureFile, err := os.Open(filepath.Join(path, "testplugin.tar.gz.asc")) pluginSignatureFile, err := os.Open(filepath.Join(path, "testplugin.tar.gz.asc"))
require.NoError(t, err) require.NoError(t, err)
pluginSignatureData, err := ioutil.ReadAll(pluginSignatureFile) pluginSignatureData, err := io.ReadAll(pluginSignatureFile)
require.NoError(t, err) require.NoError(t, err)
key, err := os.Open(filepath.Join(path, "development-private-key.asc")) key, err := os.Open(filepath.Join(path, "development-private-key.asc"))

Просмотреть файл

@@ -5,7 +5,7 @@ package api4
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"mime" "mime"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@@ -139,7 +139,7 @@ func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) {
auditRec.AddMeta("type", d) auditRec.AddMeta("type", d)
if d == "application/x-pem-file" { if d == "application/x-pem-file" {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
c.Err = model.NewAppError("addSamlIdpCertificate", "api.admin.saml.set_certificate_from_metadata.invalid_body.app_error", nil, err.Error(), http.StatusBadRequest) c.Err = model.NewAppError("addSamlIdpCertificate", "api.admin.saml.set_certificate_from_metadata.invalid_body.app_error", nil, err.Error(), http.StatusBadRequest)
return return

Просмотреть файл

@@ -8,7 +8,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -64,7 +64,7 @@ func TestGetPing(t *testing.T) {
resp, err := client.DoAPIGet("/system/ping", "") resp, err := client.DoAPIGet("/system/ping", "")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode) require.Equal(t, http.StatusOK, resp.StatusCode)
respBytes, err := ioutil.ReadAll(resp.Body) respBytes, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
respString := string(respBytes) respString := string(respBytes)
require.NotContains(t, respString, "TestFeatureFlag") require.NotContains(t, respString, "TestFeatureFlag")
@@ -77,7 +77,7 @@ func TestGetPing(t *testing.T) {
resp, err = client.DoAPIGet("/system/ping", "") resp, err = client.DoAPIGet("/system/ping", "")
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode) require.Equal(t, http.StatusOK, resp.StatusCode)
respBytes, err = ioutil.ReadAll(resp.Body) respBytes, err = io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
respString = string(respBytes) respString = string(respBytes)
require.Contains(t, respString, "testvalue") require.Contains(t, respString, "testvalue")
@@ -130,7 +130,7 @@ func TestEmailTest(t *testing.T) {
defer th.TearDown() defer th.TearDown()
client := th.Client client := th.Client
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -817,7 +817,7 @@ func TestPushNotificationAck(t *testing.T) {
resp := httptest.NewRecorder() resp := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil)
req.Header.Set(model.HeaderAuth, "Bearer "+session.Token) req.Header.Set(model.HeaderAuth, "Bearer "+session.Token)
req.Body = ioutil.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"id":"123", "is_id_loaded":true, "post_id":"%s", "type": "%s"}`, privatePost.Id, model.PushTypeMessage))) req.Body = io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"id":"123", "is_id_loaded":true, "post_id":"%s", "type": "%s"}`, privatePost.Id, model.PushTypeMessage)))
handler.ServeHTTP(resp, req) handler.ServeHTTP(resp, req)
assert.Equal(t, http.StatusForbidden, resp.Code) assert.Equal(t, http.StatusForbidden, resp.Code)
@@ -833,11 +833,11 @@ func TestCompleteOnboarding(t *testing.T) {
signatureFilename := "testplugin2.tar.gz.sig" signatureFilename := "testplugin2.tar.gz.sig"
signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename)) signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename))
require.NoError(t, err) require.NoError(t, err)
sigFile, err := ioutil.ReadAll(signatureFileReader) sigFile, err := io.ReadAll(signatureFileReader)
require.NoError(t, err) require.NoError(t, err)
pluginSignature := base64.StdEncoding.EncodeToString(sigFile) pluginSignature := base64.StdEncoding.EncodeToString(sigFile)
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin2.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin2.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK) res.WriteHeader(http.StatusOK)

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"runtime/debug" "runtime/debug"
@@ -261,7 +260,7 @@ func (a *App) GetLatestVersion(latestVersionUrl string) (*model.GithubReleaseInf
defer res.Body.Close() defer res.Body.Close()
responseData, err := ioutil.ReadAll(res.Body) responseData, err := io.ReadAll(res.Body)
if err != nil { if err != nil {
return nil, model.NewAppError("GetLatestVersion", "app.admin.latest_version_read_all.failure", nil, "", http.StatusInternalServerError) return nil, model.NewAppError("GetLatestVersion", "app.admin.latest_version_read_all.failure", nil, "", http.StatusInternalServerError)
} }

Просмотреть файл

@@ -7,7 +7,7 @@ import (
"context" "context"
"encoding/csv" "encoding/csv"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@@ -133,7 +133,7 @@ func TestSessionHasPermissionToGroup(t *testing.T) {
require.NoError(t, e) require.NoError(t, e)
defer file.Close() defer file.Close()
b, e := ioutil.ReadAll(file) b, e := io.ReadAll(file)
require.NoError(t, e) require.NoError(t, e)
r := csv.NewReader(strings.NewReader(string(b))) r := csv.NewReader(strings.NewReader(string(b)))

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"context" "context"
"errors" "errors"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
@@ -521,7 +520,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
// Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil // Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil
bodyBytes, _ := ioutil.ReadAll(body) bodyBytes, _ := io.ReadAll(body)
return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]any{"Trigger": cmd.Trigger, "Status": resp.Status}, string(bodyBytes), http.StatusInternalServerError) return cmd, nil, model.NewAppError("command", "api.command.execute_command.failed_resp.app_error", map[string]any{"Trigger": cmd.Trigger, "Status": resp.Status}, string(bodyBytes), http.StatusInternalServerError)
} }

Просмотреть файл

@@ -5,8 +5,8 @@ package app
import ( import (
"errors" "errors"
"io/ioutil"
"net/http" "net/http"
"os"
"github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/shared/mlog"
@@ -75,7 +75,7 @@ func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.Ap
} }
func (a *App) GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) { func (a *App) GetComplianceFile(job *model.Compliance) ([]byte, *model.AppError) {
f, err := ioutil.ReadFile(*a.Config().ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip") f, err := os.ReadFile(*a.Config().ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip")
if err != nil { if err != nil {
return nil, model.NewAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error(), http.StatusNotImplemented) return nil, model.NewAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error(), http.StatusNotImplemented)
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package app
import ( import (
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
@@ -64,5 +63,5 @@ func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) {
defer resp.Body.Close() defer resp.Body.Close()
return ioutil.ReadAll(resp.Body) return io.ReadAll(resp.Body)
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package email
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -64,7 +63,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper {
} }
func setupTestHelper(s store.Store, tb testing.TB) *TestHelper { func setupTestHelper(s store.Store, tb testing.TB) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "userservicetest") tempWorkspace, err := os.MkdirTemp("", "userservicetest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package app
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@@ -590,7 +589,7 @@ func TestBulkExport(t *testing.T) {
th := Setup(t) th := Setup(t)
testsDir, _ := fileutils.FindDir("tests") testsDir, _ := fileutils.FindDir("tests")
dir, err := ioutil.TempDir("", "import_test") dir, err := os.MkdirTemp("", "import_test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@@ -81,7 +80,7 @@ func TestExtractTarGz(t *testing.T) {
}) })
} }
dst, err := ioutil.TempDir("", "TestExtractTarGz") dst, err := os.MkdirTemp("", "TestExtractTarGz")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dst) defer os.RemoveAll(dst)
@@ -175,7 +174,7 @@ func TestExtractTarGz(t *testing.T) {
for i, testCase := range testCases { for i, testCase := range testCases {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
dst, err := ioutil.TempDir("", "TestExtractTarGz") dst, err := os.MkdirTemp("", "TestExtractTarGz")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dst) defer os.RemoveAll(dst)

Просмотреть файл

@@ -5,7 +5,6 @@ package app
import ( import (
"context" "context"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -48,7 +47,7 @@ type TestHelper struct {
} }
func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, options []Option, tb testing.TB) *TestHelper { func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, options []Option, tb testing.TB) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "apptest") tempWorkspace, err := os.MkdirTemp("", "apptest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package imaging
import ( import (
"bytes" "bytes"
"image/color" "image/color"
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -77,7 +76,7 @@ func TestFillImageTransparency(t *testing.T) {
require.NotNil(t, inputImg) require.NotNil(t, inputImg)
require.Equal(t, "png", format) require.Equal(t, "png", format)
expectedBytes, err := ioutil.ReadFile(imgDir + "/" + tc.outputName) expectedBytes, err := os.ReadFile(imgDir + "/" + tc.outputName)
require.NoError(t, err) require.NoError(t, err)
FillImageTransparency(inputImg, tc.fillColor) FillImageTransparency(inputImg, tc.fillColor)

Просмотреть файл

@@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path" "path"
@@ -1217,7 +1216,7 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p
timestamp := utils.TimeFromMillis(post.CreateAt) timestamp := utils.TimeFromMillis(post.CreateAt)
fileData, err := ioutil.ReadAll(file) fileData, err := io.ReadAll(file)
if err != nil { if err != nil {
return nil, model.NewAppError("BulkImport", "app.import.attachment.read_file_data.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest) return nil, model.NewAppError("BulkImport", "app.import.attachment.read_file_data.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package app
import ( import (
"archive/zip" "archive/zip"
"context" "context"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -4378,11 +4377,11 @@ func TestImportDirectPostWithAttachments(t *testing.T) {
testImage := filepath.Join(testsDir, "test.png") testImage := filepath.Join(testsDir, "test.png")
testImage2 := filepath.Join(testsDir, "test.svg") testImage2 := filepath.Join(testsDir, "test.svg")
// create a temp file with same name as original but with a different first byte // create a temp file with same name as original but with a different first byte
tmpFolder, _ := ioutil.TempDir("", "imgFake") tmpFolder, _ := os.MkdirTemp("", "imgFake")
testImageFake := filepath.Join(tmpFolder, "test.png") testImageFake := filepath.Join(tmpFolder, "test.png")
fakeFileData, _ := ioutil.ReadFile(testImage) fakeFileData, _ := os.ReadFile(testImage)
fakeFileData[0] = 0 fakeFileData[0] = 0
_ = ioutil.WriteFile(testImageFake, fakeFileData, 0644) _ = os.WriteFile(testImageFake, fakeFileData, 0644)
defer os.RemoveAll(tmpFolder) defer os.RemoveAll(tmpFolder)
// Create a user. // Create a user.

Просмотреть файл

@@ -6,7 +6,6 @@ package app
import ( import (
"archive/zip" "archive/zip"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -439,7 +438,7 @@ func BenchmarkBulkImport(b *testing.B) {
info, err := importFile.Stat() info, err := importFile.Stat()
require.NoError(b, err) require.NoError(b, err)
dir, err := ioutil.TempDir("", "testimport") dir, err := os.MkdirTemp("", "testimport")
require.NoError(b, err) require.NoError(b, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

Просмотреть файл

@@ -23,7 +23,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@@ -253,7 +253,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI
defer resp.Body.Close() defer resp.Body.Close()
var response model.PostActionIntegrationResponse var response model.PostActionIntegrationResponse
respBytes, err := ioutil.ReadAll(resp.Body) respBytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", model.NewAppError("DoPostActionWithCookie", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest) return "", model.NewAppError("DoPostActionWithCookie", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest)
} }
@@ -435,7 +435,7 @@ func (ch *Channels) doPluginRequest(c *request.Context, method, rawURL string, v
ProtoMajor: 1, ProtoMajor: 1,
ProtoMinor: 1, ProtoMinor: 1,
Header: w.headers, Header: w.headers,
Body: ioutil.NopCloser(bytes.NewReader(w.data)), Body: io.NopCloser(bytes.NewReader(w.data)),
} }
if resp.StatusCode == 0 { if resp.StatusCode == 0 {
resp.StatusCode = http.StatusOK resp.StatusCode = http.StatusOK

Просмотреть файл

@@ -6,7 +6,7 @@ package app
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -1079,47 +1079,47 @@ func TestDoPluginRequest(t *testing.T) {
resp, err := th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", nil, nil) resp, err := th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", nil, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ := ioutil.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
assert.Equal(t, "could not find param abc=xyz", string(body)) assert.Equal(t, "could not find param abc=xyz", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz", nil, nil) resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz", nil, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "param multiple should have 3 values", string(body)) assert.Equal(t, "param multiple should have 3 values", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin",
url.Values{"abc": []string{"xyz"}, "multiple": []string{"1 first", "2 second", "3 third"}}, nil) url.Values{"abc": []string{"xyz"}, "multiple": []string{"1 first", "2 second", "3 third"}}, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "OK", string(body)) assert.Equal(t, "OK", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first", resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first",
url.Values{"multiple": []string{"2 second", "3 third"}}, nil) url.Values{"multiple": []string{"2 second", "3 third"}}, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "OK", string(body)) assert.Equal(t, "OK", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third", resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third",
url.Values{"multiple": []string{"2 second"}}, nil) url.Values{"multiple": []string{"2 second"}}, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "OK", string(body)) assert.Equal(t, "OK", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
url.Values{"multiple": []string{"2 second"}, "abc": []string{"xyz"}}, nil) url.Values{"multiple": []string{"2 second"}, "abc": []string{"xyz"}}, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "OK", string(body)) assert.Equal(t, "OK", string(body))
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third", resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
url.Values{"multiple": []string{"4 fourth"}, "abc": []string{"xyz"}}, nil) url.Values{"multiple": []string{"4 fourth"}, "abc": []string{"xyz"}}, nil)
assert.Nil(t, err) assert.Nil(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)
body, _ = ioutil.ReadAll(resp.Body) body, _ = io.ReadAll(resp.Body)
assert.Equal(t, "param multiple not correct", string(body)) assert.Equal(t, "param multiple not correct", string(body))
} }

Просмотреть файл

@@ -10,7 +10,7 @@ import (
"go/ast" "go/ast"
"go/parser" "go/parser"
"go/token" "go/token"
"io/ioutil" "io"
"log" "log"
"os" "os"
"path" "path"
@@ -58,7 +58,7 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
err = ioutil.WriteFile(outputFile, formattedCode, 0644) err = os.WriteFile(outputFile, formattedCode, 0644)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -162,7 +162,7 @@ func extractStoreMetadata() (*storeMetadata, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to open %s file: %w", inputFile, err) return nil, fmt.Errorf("unable to open %s file: %w", inputFile, err)
} }
src, err := ioutil.ReadAll(file) src, err := io.ReadAll(file)
if err != nil { if err != nil {
return nil, err return nil, err
} }

Просмотреть файл

@@ -4,7 +4,7 @@
package app package app
import ( import (
"io/ioutil" "io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
@@ -186,7 +186,7 @@ func (a *App) writeLdapFile(filename string, fileData *multipart.FileHeader) *mo
} }
defer file.Close() defer file.Close()
data, err := ioutil.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
return model.NewAppError("AddLdapCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("AddLdapCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError)
} }

Просмотреть файл

@@ -11,7 +11,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
@@ -891,7 +890,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service
defer resp.Body.Close() defer resp.Body.Close()
// Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil // Ignore the error below because the resulting string will just be the empty string if bodyBytes is nil
bodyBytes, _ := ioutil.ReadAll(resp.Body) bodyBytes, _ := io.ReadAll(resp.Body)
bodyString := string(bodyBytes) bodyString := string(bodyBytes)
mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString)) mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString))

Просмотреть файл

@@ -7,7 +7,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors" "errors"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -517,7 +517,7 @@ func TestAuthorizeOAuthUser(t *testing.T) {
body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "") body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "")
require.NotNil(t, body) require.NotNil(t, body)
bodyBytes, bodyErr := ioutil.ReadAll(body) bodyBytes, bodyErr := io.ReadAll(body)
require.NoError(t, bodyErr) require.NoError(t, bodyErr)
assert.Equal(t, userData, string(bodyBytes)) assert.Equal(t, userData, string(bodyBytes))

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -39,7 +38,7 @@ type pluginSignaturePath struct {
signaturePath string signaturePath string
} }
//Ensure routerService implements `product.RouterService` // Ensure routerService implements `product.RouterService`
var _ product.RouterService = (*routerService)(nil) var _ product.RouterService = (*routerService)(nil)
type routerService struct { type routerService struct {
@@ -976,7 +975,7 @@ func (ch *Channels) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*
} }
defer fileReader.Close() defer fileReader.Close()
tmpDir, err := ioutil.TempDir("", "plugintmp") tmpDir, err := os.MkdirTemp("", "plugintmp")
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Failed to create temp dir plugintmp") return nil, errors.Wrap(err, "Failed to create temp dir plugintmp")
} }
@@ -1086,7 +1085,7 @@ func getPrepackagedPlugin(pluginPath *pluginSignaturePath, pluginFile io.ReadSee
if sigErr != nil { if sigErr != nil {
return nil, "", errors.Wrapf(sigErr, "Failed to open prepackaged plugin signature %s", sig) return nil, "", errors.Wrapf(sigErr, "Failed to open prepackaged plugin signature %s", sig)
} }
bytes, sigErr := ioutil.ReadAll(sigReader) bytes, sigErr := io.ReadAll(sigReader)
if sigErr != nil { if sigErr != nil {
return nil, "", errors.Wrapf(sigErr, "Failed to read prepackaged plugin signature %s", sig) return nil, "", errors.Wrapf(sigErr, "Failed to read prepackaged plugin signature %s", sig)
} }
@@ -1105,7 +1104,7 @@ func getPrepackagedPlugin(pluginPath *pluginSignaturePath, pluginFile io.ReadSee
} }
func getIcon(iconPath string) (string, error) { func getIcon(iconPath string) (string, error) {
icon, err := ioutil.ReadFile(iconPath) icon, err := os.ReadFile(iconPath)
if err != nil { if err != nil {
return "", errors.Wrapf(err, "failed to open icon at path %s", iconPath) return "", errors.Wrapf(err, "failed to open icon at path %s", iconPath)
} }

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"path/filepath" "path/filepath"
@@ -897,7 +896,7 @@ func (api *PluginAPI) InstallPlugin(file io.Reader, replace bool) (*model.Manife
return nil, model.NewAppError("installPlugin", "app.plugin.upload_disabled.app_error", nil, "", http.StatusNotImplemented) return nil, model.NewAppError("installPlugin", "app.plugin.upload_disabled.app_error", nil, "", http.StatusNotImplemented)
} }
fileBuffer, err := ioutil.ReadAll(file) fileBuffer, err := io.ReadAll(file)
if err != nil { if err != nil {
return nil, model.NewAppError("InstallPlugin", "api.plugin.upload.file.app_error", nil, "", http.StatusBadRequest) return nil, model.NewAppError("InstallPlugin", "api.plugin.upload.file.app_error", nil, "", http.StatusBadRequest)
} }
@@ -1029,7 +1028,7 @@ func (api *PluginAPI) PluginHTTP(request *http.Request) *http.Response {
if len(split) != 3 { if len(split) != 3 {
return &http.Response{ return &http.Response{
StatusCode: http.StatusBadRequest, StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(bytes.NewBufferString("Not enough URL. Form of URL should be /<pluginid>/*")), Body: io.NopCloser(bytes.NewBufferString("Not enough URL. Form of URL should be /<pluginid>/*")),
} }
} }
destinationPluginId := split[1] destinationPluginId := split[1]
@@ -1043,7 +1042,7 @@ func (api *PluginAPI) PluginHTTP(request *http.Request) *http.Response {
} }
return &http.Response{ return &http.Response{
StatusCode: http.StatusBadRequest, StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(bytes.NewBufferString(message)), Body: io.NopCloser(bytes.NewBufferString(message)),
} }
} }
responseTransfer := &PluginResponseWriter{} responseTransfer := &PluginResponseWriter{}

Просмотреть файл

@@ -11,7 +11,7 @@ import (
"image" "image"
"image/color" "image/color"
"image/png" "image/png"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -70,7 +70,7 @@ func setDefaultPluginConfig(th *TestHelper, pluginID string) {
} }
func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, asMain bool, app *App, c *request.Context) string { func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, asMain bool, app *App, c *request.Context) string {
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { t.Cleanup(func() {
err = os.RemoveAll(pluginDir) err = os.RemoveAll(pluginDir)
@@ -79,7 +79,7 @@ func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests
} }
}) })
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { t.Cleanup(func() {
err = os.RemoveAll(webappPluginDir) err = os.RemoveAll(webappPluginDir)
@@ -106,7 +106,7 @@ func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests
utils.CompileGoTest(t, pluginCodes[i], backend) utils.CompileGoTest(t, pluginCodes[i], backend)
} }
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifests[i]), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifests[i]), 0600)
manifest, activated, reterr := env.Activate(pluginID) manifest, activated, reterr := env.Activate(pluginID)
require.NoError(t, reterr) require.NoError(t, reterr)
require.NotNil(t, manifest) require.NotNil(t, manifest)
@@ -841,9 +841,9 @@ func TestPluginAPIGetPlugins(t *testing.T) {
} }
` `
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(pluginDir) defer os.RemoveAll(pluginDir)
defer os.RemoveAll(webappPluginDir) defer os.RemoveAll(webappPluginDir)
@@ -857,7 +857,7 @@ func TestPluginAPIGetPlugins(t *testing.T) {
backend := filepath.Join(pluginDir, pluginID, "backend.exe") backend := filepath.Join(pluginDir, pluginID, "backend.exe")
utils.CompileGo(t, pluginCode, backend) utils.CompileGo(t, pluginCode, backend)
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(fmt.Sprintf(`{"id": "%s", "server": {"executable": "backend.exe"}}`, pluginID)), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(fmt.Sprintf(`{"id": "%s", "server": {"executable": "backend.exe"}}`, pluginID)), 0600)
manifest, activated, reterr := env.Activate(pluginID) manifest, activated, reterr := env.Activate(pluginID)
require.NoError(t, reterr) require.NoError(t, reterr)
@@ -884,7 +884,7 @@ func TestPluginAPIInstallPlugin(t *testing.T) {
api := th.SetupPluginAPI() api := th.SetupPluginAPI()
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz"))
require.NoError(t, err) require.NoError(t, err)
_, appErr := api.InstallPlugin(bytes.NewReader(tarData), true) _, appErr := api.InstallPlugin(bytes.NewReader(tarData), true)
@@ -922,9 +922,9 @@ func TestInstallPlugin(t *testing.T) {
// since it removes plugin dirs right after it returns, does not update App configs with the plugin // since it removes plugin dirs right after it returns, does not update App configs with the plugin
// dirs and this behavior tends to break this test as a result. // dirs and this behavior tends to break this test as a result.
setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) (func(), string) { setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) (func(), string) {
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
app.UpdateConfig(func(cfg *model.Config) { app.UpdateConfig(func(cfg *model.Config) {
@@ -944,7 +944,7 @@ func TestInstallPlugin(t *testing.T) {
backend := filepath.Join(pluginDir, pluginID, "backend.exe") backend := filepath.Join(pluginDir, pluginID, "backend.exe")
utils.CompileGo(t, pluginCode, backend) utils.CompileGo(t, pluginCode, backend)
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600)
manifest, activated, reterr := env.Activate(pluginID) manifest, activated, reterr := env.Activate(pluginID)
require.NoError(t, reterr) require.NoError(t, reterr)
require.NotNil(t, manifest) require.NotNil(t, manifest)
@@ -1126,7 +1126,7 @@ func TestPluginAPIRemoveTeamIcon(t *testing.T) {
} }
func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string, settingsSchema string) error { func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string, settingsSchema string) error {
data, err := ioutil.ReadFile(fileName) data, err := os.ReadFile(fileName)
if err != nil { if err != nil {
return err return err
} }
@@ -1161,7 +1161,7 @@ func TestBasicAPIPlugins(t *testing.T) {
defaultSchema := getDefaultPluginSettingsSchema() defaultSchema := getDefaultPluginSettingsSchema()
testFolder, found := fileutils.FindDir("mattermost-server/app/plugin_api_tests") testFolder, found := fileutils.FindDir("mattermost-server/app/plugin_api_tests")
require.True(t, found, "Cannot read find app folder") require.True(t, found, "Cannot read find app folder")
dirs, err := ioutil.ReadDir(testFolder) dirs, err := os.ReadDir(testFolder)
require.NoError(t, err, "Cannot read test folder %v", testFolder) require.NoError(t, err, "Cannot read test folder %v", testFolder)
for _, dir := range dirs { for _, dir := range dirs {
d := dir.Name() d := dir.Name()
@@ -1523,7 +1523,7 @@ func TestInterpluginPluginHTTP(t *testing.T) {
"github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/model"
"bytes" "bytes"
"net/http" "net/http"
"io/ioutil" "io"
) )
type MyPlugin struct { type MyPlugin struct {
@@ -1545,7 +1545,7 @@ func TestInterpluginPluginHTTP(t *testing.T) {
if resp.Body == nil { if resp.Body == nil {
return nil, "Nil body" return nil, "Nil body"
} }
respbody, err := ioutil.ReadAll(resp.Body) respbody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err.Error() return nil, err.Error()
} }
@@ -1605,9 +1605,9 @@ func TestAPIMetrics(t *testing.T) {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
metricsMock := &mocks.MetricsInterface{} metricsMock := &mocks.MetricsInterface{}
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(pluginDir) defer os.RemoveAll(pluginDir)
defer os.RemoveAll(webappPluginDir) defer os.RemoveAll(webappPluginDir)
@@ -1642,7 +1642,7 @@ func TestAPIMetrics(t *testing.T) {
} }
` `
utils.CompileGo(t, code, backend) utils.CompileGo(t, code, backend)
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600)
// Don't care about these mocks // Don't care about these mocks
metricsMock.On("ObservePluginHookDuration", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return() metricsMock.On("ObservePluginHookDuration", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return()
@@ -1730,7 +1730,7 @@ func TestPluginHTTPConnHijack(t *testing.T) {
require.True(t, found, "Cannot find tests folder") require.True(t, found, "Cannot find tests folder")
fullPath := path.Join(testFolder, "manual.test_http_hijack_plugin", "main.go") fullPath := path.Join(testFolder, "manual.test_http_hijack_plugin", "main.go")
pluginCode, err := ioutil.ReadFile(fullPath) pluginCode, err := os.ReadFile(fullPath)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, pluginCode) require.NotEmpty(t, pluginCode)
@@ -1752,7 +1752,7 @@ func TestPluginHTTPConnHijack(t *testing.T) {
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "OK", string(body)) require.Equal(t, "OK", string(body))
} }
@@ -1765,7 +1765,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) {
require.True(t, found, "Cannot find tests folder") require.True(t, found, "Cannot find tests folder")
fullPath := path.Join(testFolder, "manual.test_http_upgrade_websocket_plugin", "main.go") fullPath := path.Join(testFolder, "manual.test_http_upgrade_websocket_plugin", "main.go")
pluginCode, err := ioutil.ReadFile(fullPath) pluginCode, err := os.ReadFile(fullPath)
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, pluginCode) require.NotEmpty(t, pluginCode)

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -29,9 +28,9 @@ import (
) )
func SetAppEnvironmentWithPlugins(t *testing.T, pluginCode []string, app *App, apiFunc func(*model.Manifest) plugin.API) (func(), []string, []error) { func SetAppEnvironmentWithPlugins(t *testing.T, pluginCode []string, app *App, apiFunc func(*model.Manifest) plugin.API) (func(), []string, []error) {
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
env, err := plugin.NewEnvironment(apiFunc, NewDriverImpl(app.Srv()), pluginDir, webappPluginDir, app.Log(), nil) env, err := plugin.NewEnvironment(apiFunc, NewDriverImpl(app.Srv()), pluginDir, webappPluginDir, app.Log(), nil)
@@ -45,7 +44,7 @@ func SetAppEnvironmentWithPlugins(t *testing.T, pluginCode []string, app *App, a
backend := filepath.Join(pluginDir, pluginID, "backend.exe") backend := filepath.Join(pluginDir, pluginID, "backend.exe")
utils.CompileGo(t, code, backend) utils.CompileGo(t, code, backend)
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600)
_, _, activationErr := env.Activate(pluginID) _, _, activationErr := env.Activate(pluginID)
pluginIDs = append(pluginIDs, pluginID) pluginIDs = append(pluginIDs, pluginID)
activationErrors = append(activationErrors, activationErr) activationErrors = append(activationErrors, activationErr)
@@ -1024,9 +1023,9 @@ func TestHookMetrics(t *testing.T) {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
metricsMock := &mocks.MetricsInterface{} metricsMock := &mocks.MetricsInterface{}
pluginDir, err := ioutil.TempDir("", "") pluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
webappPluginDir, err := ioutil.TempDir("", "") webappPluginDir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(pluginDir) defer os.RemoveAll(pluginDir)
defer os.RemoveAll(webappPluginDir) defer os.RemoveAll(webappPluginDir)
@@ -1069,7 +1068,7 @@ func TestHookMetrics(t *testing.T) {
} }
` `
utils.CompileGo(t, code, backend) utils.CompileGo(t, code, backend)
ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600) os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(`{"id": "`+pluginID+`", "server": {"executable": "backend.exe"}}`), 0600)
// Setup mocks before activating // Setup mocks before activating
metricsMock.On("ObservePluginHookDuration", pluginID, "Implemented", true, mock.Anything).Return() metricsMock.On("ObservePluginHookDuration", pluginID, "Implemented", true, mock.Anything).Return()

Просмотреть файл

@@ -33,14 +33,12 @@
// Prepackaged plugins are included with the server. They otherwise follow the above flow, except do not get uploaded // Prepackaged plugins are included with the server. They otherwise follow the above flow, except do not get uploaded
// to the filestore. Prepackaged plugins override all other plugins with the same plugin id, but only when the prepackaged // to the filestore. Prepackaged plugins override all other plugins with the same plugin id, but only when the prepackaged
// plugin is newer. Managed plugins unconditionally override unmanaged plugins with the same plugin id. // plugin is newer. Managed plugins unconditionally override unmanaged plugins with the same plugin id.
//
package app package app
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -280,7 +278,7 @@ func (ch *Channels) installPluginLocally(pluginFile, signature io.ReadSeeker, in
} }
} }
tmpDir, err := ioutil.TempDir("", "plugintmp") tmpDir, err := os.MkdirTemp("", "plugintmp")
if err != nil { if err != nil {
return nil, model.NewAppError("installPluginLocally", "app.plugin.filesystem.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("installPluginLocally", "app.plugin.filesystem.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -305,7 +303,7 @@ func extractPlugin(pluginFile io.ReadSeeker, extractDir string) (*model.Manifest
return nil, "", model.NewAppError("extractPlugin", "app.plugin.extract.app_error", nil, err.Error(), http.StatusBadRequest) return nil, "", model.NewAppError("extractPlugin", "app.plugin.extract.app_error", nil, err.Error(), http.StatusBadRequest)
} }
dir, err := ioutil.ReadDir(extractDir) dir, err := os.ReadDir(extractDir)
if err != nil { if err != nil {
return nil, "", model.NewAppError("extractPlugin", "app.plugin.filesystem.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, "", model.NewAppError("extractPlugin", "app.plugin.filesystem.app_error", nil, err.Error(), http.StatusInternalServerError)
} }

Просмотреть файл

@@ -6,7 +6,7 @@ package app
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"path" "path"
"path/filepath" "path/filepath"
@@ -157,11 +157,11 @@ func (ch *Channels) servePluginRequest(w http.ResponseWriter, r *http.Request, h
sentToken := "" sentToken := ""
if r.Header.Get(model.HeaderCsrfToken) == "" { if r.Header.Get(model.HeaderCsrfToken) == "" {
bodyBytes, _ := ioutil.ReadAll(r.Body) bodyBytes, _ := io.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
r.ParseForm() r.ParseForm()
sentToken = r.FormValue("csrf") sentToken = r.FormValue("csrf")
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
} else { } else {
sentToken = r.Header.Get(model.HeaderCsrfToken) sentToken = r.Header.Get(model.HeaderCsrfToken)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package app
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"path/filepath" "path/filepath"
@@ -37,7 +36,7 @@ func (a *App) AddPublicKey(name string, key io.Reader) *model.AppError {
if isSamlFile(&a.Config().SamlSettings, name) { if isSamlFile(&a.Config().SamlSettings, name) {
return model.NewAppError("AddPublicKey", "app.plugin.modify_saml.app_error", nil, "", http.StatusInternalServerError) return model.NewAppError("AddPublicKey", "app.plugin.modify_saml.app_error", nil, "", http.StatusInternalServerError)
} }
data, err := ioutil.ReadAll(key) data, err := io.ReadAll(key)
if err != nil { if err != nil {
return model.NewAppError("AddPublicKey", "app.plugin.write_file.read.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("AddPublicKey", "app.plugin.write_file.read.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -122,7 +121,7 @@ func verifyBinarySignature(publicKey, signedFile, signature io.Reader) error {
} }
func decodeIfArmored(reader io.Reader) (io.Reader, error) { func decodeIfArmored(reader io.Reader) (io.Reader, error) {
readBytes, err := ioutil.ReadAll(reader) readBytes, err := io.ReadAll(reader)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "can't read the file") return nil, errors.Wrap(err, "can't read the file")
} }

Просмотреть файл

@@ -4,7 +4,6 @@
package app package app
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -38,7 +37,7 @@ func TestPluginPublicKeys(t *testing.T) {
path, _ := fileutils.FindDir("tests") path, _ := fileutils.FindDir("tests")
publicKeyFilename := "test-public-key.plugin.gpg" publicKeyFilename := "test-public-key.plugin.gpg"
publicKey, err := ioutil.ReadFile(filepath.Join(path, publicKeyFilename)) publicKey, err := os.ReadFile(filepath.Join(path, publicKeyFilename))
require.NoError(t, err) require.NoError(t, err)
fileReader, err := os.Open(filepath.Join(path, publicKeyFilename)) fileReader, err := os.Open(filepath.Join(path, publicKeyFilename))
require.NoError(t, err) require.NoError(t, err)

Просмотреть файл

@@ -9,7 +9,7 @@ import (
"encoding/base64" "encoding/base64"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -384,7 +384,7 @@ func TestPrivateServePluginRequest(t *testing.T) {
handler := func(context *plugin.Context, w http.ResponseWriter, r *http.Request) { handler := func(context *plugin.Context, w http.ResponseWriter, r *http.Request) {
assert.Equal(t, testCase.ExpectedURL, r.URL.Path) assert.Equal(t, testCase.ExpectedURL, r.URL.Path)
body, _ := ioutil.ReadAll(r.Body) body, _ := io.ReadAll(r.Body)
assert.Equal(t, expectedBody, body) assert.Equal(t, expectedBody, body)
} }
@@ -827,7 +827,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
t.Run("automatic, enabled plugin, no signature", func(t *testing.T) { t.Run("automatic, enabled plugin, no signature", func(t *testing.T) {
// Install the plugin and enable // Install the plugin and enable
pluginBytes, err := ioutil.ReadFile(testPluginPath) pluginBytes, err := os.ReadFile(testPluginPath)
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, pluginBytes) require.NotNil(t, pluginBytes)
@@ -935,7 +935,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
// Install first plugin and enable // Install first plugin and enable
pluginBytes, err := ioutil.ReadFile(testPluginPath) pluginBytes, err := os.ReadFile(testPluginPath)
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, pluginBytes) require.NotNil(t, pluginBytes)

Просмотреть файл

@@ -6,7 +6,7 @@ package app
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -59,7 +59,7 @@ func (rt *PluginResponseWriter) GenerateResponse() *http.Response {
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
if rt.Len() > 0 { if rt.Len() > 0 {
res.Body = ioutil.NopCloser(rt) res.Body = io.NopCloser(rt)
} else { } else {
res.Body = http.NoBody res.Body = http.NoBody
} }

Просмотреть файл

@@ -6,7 +6,7 @@ package app
import ( import (
"context" "context"
"encoding/csv" "encoding/csv"
"io/ioutil" "io"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@@ -130,7 +130,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th
require.NoError(t, e) require.NoError(t, e)
defer file.Close() defer file.Close()
b, e := ioutil.ReadAll(file) b, e := io.ReadAll(file)
require.NoError(t, e) require.NoError(t, e)
r := csv.NewReader(strings.NewReader(string(b))) r := csv.NewReader(strings.NewReader(string(b)))

Просмотреть файл

@@ -8,7 +8,7 @@ import (
"encoding/pem" "encoding/pem"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io/ioutil" "io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"strings" "strings"
@@ -42,7 +42,7 @@ func (a *App) writeSamlFile(filename string, fileData *multipart.FileHeader) *mo
} }
defer file.Close() defer file.Close()
data, err := ioutil.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
return model.NewAppError("AddSamlCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError) return model.NewAppError("AddSamlCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError)
} }
@@ -212,7 +212,7 @@ func (a *App) FetchSamlMetadataFromIdp(url string) ([]byte, *model.AppError) {
} }
defer resp.Body.Close() defer resp.Body.Close()
bodyXML, err := ioutil.ReadAll(resp.Body) bodyXML, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, model.NewAppError("FetchSamlMetadataFromIdp", "app.admin.saml.failure_read_response_body_from_idp.app_error", nil, err.Error(), http.StatusInternalServerError) return nil, model.NewAppError("FetchSamlMetadataFromIdp", "app.admin.saml.failure_read_response_body_from_idp.app_error", nil, err.Error(), http.StatusInternalServerError)
} }

Просмотреть файл

@@ -5,7 +5,7 @@ package app
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"runtime" "runtime"
@@ -110,7 +110,7 @@ func (s *Server) DoSecurityUpdateCheck() {
return return
} }
body, err := ioutil.ReadAll(resBody.Body) body, err := io.ReadAll(resBody.Body)
resBody.Body.Close() resBody.Body.Close()
if err != nil || resBody.StatusCode != 200 { if err != nil || resBody.StatusCode != 200 {
mlog.Error("Failed to read security bulletin details") mlog.Error("Failed to read security bulletin details")

Просмотреть файл

@@ -6,7 +6,6 @@ package slashcommands
import ( import (
"bytes" "bytes"
"context" "context"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -42,7 +41,7 @@ type TestHelper struct {
} }
func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, tb testing.TB, configSet func(*model.Config)) *TestHelper { func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, tb testing.TB, configSet func(*model.Config)) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "apptest") tempWorkspace, err := os.MkdirTemp("", "apptest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -6,7 +6,7 @@ package app
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"runtime" "runtime"
"strings" "strings"
@@ -145,7 +145,7 @@ func (a *App) getNotificationsLog() (*model.FileData, string) {
// notifications.log // notifications.log
notificationsLog := config.GetNotificationsLogFileLocation(*a.Config().LogSettings.FileLocation) notificationsLog := config.GetNotificationsLogFileLocation(*a.Config().LogSettings.FileLocation)
notificationsLogFileData, notificationsLogFileDataErr := ioutil.ReadFile(notificationsLog) notificationsLogFileData, notificationsLogFileDataErr := os.ReadFile(notificationsLog)
if notificationsLogFileDataErr == nil { if notificationsLogFileDataErr == nil {
fileData := model.FileData{ fileData := model.FileData{
@@ -155,7 +155,7 @@ func (a *App) getNotificationsLog() (*model.FileData, string) {
return &fileData, "" return &fileData, ""
} }
warning = fmt.Sprintf("ioutil.ReadFile(notificationsLog) Error: %s", notificationsLogFileDataErr.Error()) warning = fmt.Sprintf("os.ReadFile(notificationsLog) Error: %s", notificationsLogFileDataErr.Error())
} else { } else {
warning = "Unable to retrieve notifications.log because LogSettings: EnableFile is false in config.json" warning = "Unable to retrieve notifications.log because LogSettings: EnableFile is false in config.json"
@@ -172,7 +172,7 @@ func (a *App) getMattermostLog() (*model.FileData, string) {
// mattermost.log // mattermost.log
mattermostLog := config.GetLogFileLocation(*a.Config().LogSettings.FileLocation) mattermostLog := config.GetLogFileLocation(*a.Config().LogSettings.FileLocation)
mattermostLogFileData, mattermostLogFileDataErr := ioutil.ReadFile(mattermostLog) mattermostLogFileData, mattermostLogFileDataErr := os.ReadFile(mattermostLog)
if mattermostLogFileDataErr == nil { if mattermostLogFileDataErr == nil {
fileData := model.FileData{ fileData := model.FileData{
@@ -181,7 +181,7 @@ func (a *App) getMattermostLog() (*model.FileData, string) {
} }
return &fileData, "" return &fileData, ""
} }
warning = fmt.Sprintf("ioutil.ReadFile(mattermostLog) Error: %s", mattermostLogFileDataErr.Error()) warning = fmt.Sprintf("os.ReadFile(mattermostLog) Error: %s", mattermostLogFileDataErr.Error())
} else { } else {
warning = "Unable to retrieve mattermost.log because LogSettings: EnableFile is false in config.json" warning = "Unable to retrieve mattermost.log because LogSettings: EnableFile is false in config.json"

Просмотреть файл

@@ -4,7 +4,6 @@
package app package app
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -61,9 +60,9 @@ func TestGenerateSupportPacket(t *testing.T) {
defer th.TearDown() defer th.TearDown()
d1 := []byte("hello\ngo\n") d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("mattermost.log", d1, 0777) err := os.WriteFile("mattermost.log", d1, 0777)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile("notifications.log", d1, 0777) err = os.WriteFile("notifications.log", d1, 0777)
require.NoError(t, err) require.NoError(t, err)
fileDatas := th.App.GenerateSupportPacket() fileDatas := th.App.GenerateSupportPacket()
@@ -111,11 +110,11 @@ func TestGetNotificationsLog(t *testing.T) {
fileData, warning = th.App.getNotificationsLog() fileData, warning = th.App.getNotificationsLog()
assert.Nil(t, fileData) assert.Nil(t, fileData)
assert.Contains(t, warning, "ioutil.ReadFile(notificationsLog) Error:") assert.Contains(t, warning, "os.ReadFile(notificationsLog) Error:")
// Happy path where we have file and no warning // Happy path where we have file and no warning
d1 := []byte("hello\ngo\n") d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("notifications.log", d1, 0777) err := os.WriteFile("notifications.log", d1, 0777)
defer os.Remove("notifications.log") defer os.Remove("notifications.log")
require.NoError(t, err) require.NoError(t, err)
@@ -149,11 +148,11 @@ func TestGetMattermostLog(t *testing.T) {
fileData, warning = th.App.getMattermostLog() fileData, warning = th.App.getMattermostLog()
assert.Nil(t, fileData) assert.Nil(t, fileData)
assert.Contains(t, warning, "ioutil.ReadFile(mattermostLog) Error:") assert.Contains(t, warning, "os.ReadFile(mattermostLog) Error:")
// Happy path where we get a log file and no warning // Happy path where we get a log file and no warning
d1 := []byte("hello\ngo\n") d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("mattermost.log", d1, 0777) err := os.WriteFile("mattermost.log", d1, 0777)
defer os.Remove("mattermost.log") defer os.Remove("mattermost.log")
require.NoError(t, err) require.NoError(t, err)

Просмотреть файл

@@ -5,7 +5,6 @@ package teams
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -43,7 +42,7 @@ func Setup(tb testing.TB) *TestHelper {
} }
func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *TestHelper { func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "teamservicetest") tempWorkspace, err := os.MkdirTemp("", "teamservicetest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -6,8 +6,8 @@ package app
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
"os"
"path/filepath" "path/filepath"
"sync" "sync"
"sync/atomic" "sync/atomic"
@@ -213,7 +213,7 @@ func TestUploadData(t *testing.T) {
t.Run("image processing", func(t *testing.T) { t.Run("image processing", func(t *testing.T) {
testDir, _ := fileutils.FindDir("tests") testDir, _ := fileutils.FindDir("tests")
data, err := ioutil.ReadFile(filepath.Join(testDir, "test.png")) data, err := os.ReadFile(filepath.Join(testDir, "test.png"))
require.NoError(t, err) require.NoError(t, err)
require.NotEmpty(t, data) require.NotEmpty(t, data)

Просмотреть файл

@@ -5,7 +5,6 @@ package users
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@@ -48,7 +47,7 @@ func Setup(tb testing.TB) *TestHelper {
} }
func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *TestHelper { func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "userservicetest") tempWorkspace, err := os.MkdirTemp("", "userservicetest")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -11,7 +11,7 @@ import (
"image/draw" "image/draw"
"image/png" "image/png"
"io" "io"
"io/ioutil" "os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -174,7 +174,7 @@ func getFont(initialFont string) (*truetype.Font, error) {
} }
fontDir, _ := fileutils.FindDir("fonts") fontDir, _ := fileutils.FindDir("fonts")
fontBytes, err := ioutil.ReadFile(filepath.Join(fontDir, initialFont)) fontBytes, err := os.ReadFile(filepath.Join(fontDir, initialFont))
if err != nil { if err != nil {
return nil, err return nil, err
} }

Просмотреть файл

@@ -6,7 +6,6 @@
package app package app
import ( import (
"io/ioutil"
"math/rand" "math/rand"
"net" "net"
"net/http" "net/http"
@@ -273,7 +272,7 @@ func generateInitialCorpus() error {
if err != nil { if err != nil {
return err return err
} }
err = ioutil.WriteFile("./workdir/corpus"+strconv.Itoa(i), data, 0644) err = os.WriteFile("./workdir/corpus"+strconv.Itoa(i), data, 0644)
if err != nil { if err != nil {
return err return err
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package audit
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@@ -72,7 +71,7 @@ func TestAudit_LogRecord(t *testing.T) {
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.description, func(t *testing.T) { t.Run(testCase.description, func(t *testing.T) {
tempDir, err := ioutil.TempDir(os.TempDir(), "TestAudit_LogRecord") tempDir, err := os.MkdirTemp(os.TempDir(), "TestAudit_LogRecord")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tempDir) defer os.Remove(tempDir)
@@ -92,7 +91,7 @@ func TestAudit_LogRecord(t *testing.T) {
err = logger.Shutdown() err = logger.Shutdown()
require.NoError(t, err) require.NoError(t, err)
logs, err := ioutil.ReadFile(filePath) logs, err := os.ReadFile(filePath)
require.NoError(t, err) require.NoError(t, err)
actual := strings.TrimSpace(string(logs)) actual := strings.TrimSpace(string(logs))

Просмотреть файл

@@ -9,7 +9,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@@ -127,7 +126,7 @@ func (h *testHelper) SetConfig(config *model.Config) {
if err != nil { if err != nil {
panic("failed to marshal config: " + err.Error()) panic("failed to marshal config: " + err.Error())
} }
if err := ioutil.WriteFile(h.configFilePath, buf, 0600); err != nil { if err := os.WriteFile(h.configFilePath, buf, 0600); err != nil {
panic("failed to write file " + h.configFilePath + ": " + err.Error()) panic("failed to write file " + h.configFilePath + ": " + err.Error())
} }
} }

Просмотреть файл

@@ -4,7 +4,6 @@
package commands package commands
import ( import (
"io/ioutil"
"net" "net"
"os" "os"
"syscall" "syscall"
@@ -77,7 +76,7 @@ func TestRunServerSystemdNotification(t *testing.T) {
defer th.TearDownServerTest() defer th.TearDownServerTest()
// Get a random temporary filename for using as a mock systemd socket // Get a random temporary filename for using as a mock systemd socket
socketFile, err := ioutil.TempFile("", "mattermost-systemd-mock-socket-") socketFile, err := os.CreateTemp("", "mattermost-systemd-mock-socket-")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -5,7 +5,7 @@ package config
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
@@ -111,7 +111,7 @@ func (fs *FileStore) persist(cfg *model.Config) error {
return errors.Wrap(err, "failed to serialize") return errors.Wrap(err, "failed to serialize")
} }
err = ioutil.WriteFile(fs.path, b, 0600) err = os.WriteFile(fs.path, b, 0600)
if err != nil { if err != nil {
return errors.Wrap(err, "failed to write file") return errors.Wrap(err, "failed to write file")
} }
@@ -130,7 +130,7 @@ func (fs *FileStore) Load() ([]byte, error) {
} }
defer f.Close() defer f.Close()
fileBytes, err := ioutil.ReadAll(f) fileBytes, err := io.ReadAll(f)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -142,7 +142,7 @@ func (fs *FileStore) Load() ([]byte, error) {
func (fs *FileStore) GetFile(name string) ([]byte, error) { func (fs *FileStore) GetFile(name string) ([]byte, error) {
resolvedPath := fs.resolveFilePath(name) resolvedPath := fs.resolveFilePath(name)
data, err := ioutil.ReadFile(resolvedPath) data, err := os.ReadFile(resolvedPath)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to read file from %s", resolvedPath) return nil, errors.Wrapf(err, "failed to read file from %s", resolvedPath)
} }
@@ -160,7 +160,7 @@ func (fs *FileStore) GetFilePath(name string) string {
func (fs *FileStore) SetFile(name string, data []byte) error { func (fs *FileStore) SetFile(name string, data []byte) error {
resolvedPath := fs.resolveFilePath(name) resolvedPath := fs.resolveFilePath(name)
err := ioutil.WriteFile(resolvedPath, data, 0600) err := os.WriteFile(resolvedPath, data, 0600)
if err != nil { if err != nil {
return errors.Wrapf(err, "failed to write file to %s", resolvedPath) return errors.Wrapf(err, "failed to write file to %s", resolvedPath)
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package config
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -24,7 +23,7 @@ func setupConfigFile(t *testing.T, cfg *model.Config) (string, func()) {
os.Clearenv() os.Clearenv()
t.Helper() t.Helper()
tempDir, err := ioutil.TempDir("", "setupConfigFile") tempDir, err := os.MkdirTemp("", "setupConfigFile")
require.NoError(t, err) require.NoError(t, err)
err = os.Chdir(tempDir) err = os.Chdir(tempDir)
@@ -32,13 +31,13 @@ func setupConfigFile(t *testing.T, cfg *model.Config) (string, func()) {
var name string var name string
if cfg != nil { if cfg != nil {
f, err := ioutil.TempFile(tempDir, "setupConfigFile") f, err := os.CreateTemp(tempDir, "setupConfigFile")
require.NoError(t, err) require.NoError(t, err)
cfgData, err := marshalConfig(cfg) cfgData, err := marshalConfig(cfg)
require.NoError(t, err) require.NoError(t, err)
ioutil.WriteFile(f.Name(), cfgData, 0644) os.WriteFile(f.Name(), cfgData, 0644)
name = f.Name() name = f.Name()
} }
@@ -165,7 +164,7 @@ func TestFileStoreNew(t *testing.T) {
_, tearDown := setupConfigFile(t, nil) _, tearDown := setupConfigFile(t, nil)
defer tearDown() defer tearDown()
tempDir, err := ioutil.TempDir("", "TestFileStoreNew") tempDir, err := os.MkdirTemp("", "TestFileStoreNew")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)
@@ -184,7 +183,7 @@ func TestFileStoreNew(t *testing.T) {
_, tearDown := setupConfigFile(t, nil) _, tearDown := setupConfigFile(t, nil)
defer tearDown() defer tearDown()
tempDir, err := ioutil.TempDir("", "TestFileStoreNew") tempDir, err := os.MkdirTemp("", "TestFileStoreNew")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)
@@ -203,7 +202,7 @@ func TestFileStoreNew(t *testing.T) {
_, tearDown := setupConfigFile(t, nil) _, tearDown := setupConfigFile(t, nil)
defer tearDown() defer tearDown()
tempDir, err := ioutil.TempDir("", "TestFileStoreNew") tempDir, err := os.MkdirTemp("", "TestFileStoreNew")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)
@@ -225,7 +224,7 @@ func TestFileStoreNew(t *testing.T) {
cfgData, err := marshalConfig(testConfig) cfgData, err := marshalConfig(testConfig)
require.NoError(t, err) require.NoError(t, err)
ioutil.WriteFile(path, cfgData, 0644) os.WriteFile(path, cfgData, 0644)
fs, err := NewFileStore(path, false) fs, err := NewFileStore(path, false)
require.NoError(t, err) require.NoError(t, err)
@@ -815,7 +814,7 @@ func TestFileStoreLoad(t *testing.T) {
cfgData, err := marshalConfig(invalidConfig) cfgData, err := marshalConfig(invalidConfig)
require.NoError(t, err) require.NoError(t, err)
ioutil.WriteFile(path, cfgData, 0644) os.WriteFile(path, cfgData, 0644)
err = fs.Load() err = fs.Load()
if assert.Error(t, err) { if assert.Error(t, err) {
@@ -876,7 +875,7 @@ func TestFileStoreLoad(t *testing.T) {
cfgData, err := marshalConfig(minimalConfig) cfgData, err := marshalConfig(minimalConfig)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(path, cfgData, 0644) err = os.WriteFile(path, cfgData, 0644)
require.NoError(t, err) require.NoError(t, err)
err = fs.Load() err = fs.Load()
@@ -971,11 +970,11 @@ func TestFileGetFile(t *testing.T) {
err := os.MkdirAll("config", 0700) err := os.MkdirAll("config", 0700)
require.NoError(t, err) require.NoError(t, err)
f, err := ioutil.TempFile("config", "empty-file") f, err := os.CreateTemp("config", "empty-file")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(f.Name()) defer os.Remove(f.Name())
err = ioutil.WriteFile(f.Name(), nil, 0777) err = os.WriteFile(f.Name(), nil, 0777)
require.NoError(t, err) require.NoError(t, err)
data, err := fs.GetFile(f.Name()) data, err := fs.GetFile(f.Name())
@@ -987,11 +986,11 @@ func TestFileGetFile(t *testing.T) {
err := os.MkdirAll("config", 0700) err := os.MkdirAll("config", 0700)
require.NoError(t, err) require.NoError(t, err)
f, err := ioutil.TempFile("config", "test-file") f, err := os.CreateTemp("config", "test-file")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(f.Name()) defer os.Remove(f.Name())
err = ioutil.WriteFile(f.Name(), []byte("test"), 0777) err = os.WriteFile(f.Name(), []byte("test"), 0777)
require.NoError(t, err) require.NoError(t, err)
data, err := fs.GetFile(f.Name()) data, err := fs.GetFile(f.Name())
@@ -1102,11 +1101,11 @@ func TestFileHasFile(t *testing.T) {
err = os.MkdirAll("config", 0700) err = os.MkdirAll("config", 0700)
require.NoError(t, err) require.NoError(t, err)
f, err := ioutil.TempFile("config", "test-file") f, err := os.CreateTemp("config", "test-file")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(f.Name()) defer os.Remove(f.Name())
err = ioutil.WriteFile(f.Name(), []byte("test"), 0777) err = os.WriteFile(f.Name(), []byte("test"), 0777)
require.NoError(t, err) require.NoError(t, err)
has, err := fs.HasFile(f.Name()) has, err := fs.HasFile(f.Name())
@@ -1191,11 +1190,11 @@ func TestFileRemoveFile(t *testing.T) {
err = os.MkdirAll("config", 0700) err = os.MkdirAll("config", 0700)
require.NoError(t, err) require.NoError(t, err)
f, err := ioutil.TempFile("config", "test-file") f, err := os.CreateTemp("config", "test-file")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(f.Name()) defer os.Remove(f.Name())
err = ioutil.WriteFile(f.Name(), []byte("test"), 0777) err = os.WriteFile(f.Name(), []byte("test"), 0777)
require.NoError(t, err) require.NoError(t, err)
err = fs.RemoveFile(f.Name()) err = fs.RemoveFile(f.Name())
@@ -1314,7 +1313,7 @@ func TestFileStoreSetReadOnlyFF(t *testing.T) {
func TestResolveConfigPath(t *testing.T) { func TestResolveConfigPath(t *testing.T) {
t.Run("should be able to resolve an absolute path", func(t *testing.T) { t.Run("should be able to resolve an absolute path", func(t *testing.T) {
cf, err := ioutil.TempFile("", "config-test.json") cf, err := os.CreateTemp("", "config-test.json")
require.NoError(t, err) require.NoError(t, err)
info, err := cf.Stat() info, err := cf.Stat()
require.NoError(t, err) require.NoError(t, err)
@@ -1329,7 +1328,7 @@ func TestResolveConfigPath(t *testing.T) {
}) })
t.Run("should be able to resolve relative path", func(t *testing.T) { t.Run("should be able to resolve relative path", func(t *testing.T) {
tempDir, err := ioutil.TempDir("", "resolveconfig") tempDir, err := os.MkdirTemp("", "resolveconfig")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)

Просмотреть файл

@@ -4,7 +4,6 @@
package config package config
import ( import (
"io/ioutil"
"os" "os"
"path" "path"
"testing" "testing"
@@ -39,7 +38,7 @@ func TestMigrate(t *testing.T) {
os.Clearenv() os.Clearenv()
t.Helper() t.Helper()
tempDir, err := ioutil.TempDir("", "TestMigrate") tempDir, err := os.MkdirTemp("", "TestMigrate")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { t.Cleanup(func() {
os.RemoveAll(tempDir) os.RemoveAll(tempDir)

Просмотреть файл

@@ -4,7 +4,6 @@
package config package config
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -18,7 +17,7 @@ func TestNewStoreFromDSN(t *testing.T) {
} }
sqlSettings := mainHelper.GetSQLSettings() sqlSettings := mainHelper.GetSQLSettings()
tempDir, err := ioutil.TempDir("", "TestNewStore") tempDir, err := os.MkdirTemp("", "TestNewStore")
require.NoError(t, err) require.NoError(t, err)
err = os.Chdir(tempDir) err = os.Chdir(tempDir)
@@ -46,7 +45,7 @@ func TestNewStoreReadOnly(t *testing.T) {
} }
sqlSettings := mainHelper.GetSQLSettings() sqlSettings := mainHelper.GetSQLSettings()
tempDir, tErr := ioutil.TempDir("", "TestNewStore") tempDir, tErr := os.MkdirTemp("", "TestNewStore")
require.NoError(t, tErr) require.NoError(t, tErr)
tErr = os.Chdir(tempDir) tErr = os.Chdir(tempDir)

Просмотреть файл

@@ -4,7 +4,6 @@
package model package model
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -14,7 +13,7 @@ import (
) )
func TestBundleInfoForPath(t *testing.T) { func TestBundleInfoForPath(t *testing.T) {
dir, err := ioutil.TempDir("", "mm-plugin-test") dir, err := os.MkdirTemp("", "mm-plugin-test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime/multipart" "mime/multipart"
"net" "net"
"net/http" "net/http"
@@ -1010,7 +1009,7 @@ func (c *Client4) GetDefaultProfileImage(userId string) ([]byte, *Response, erro
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetDefaultProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetDefaultProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -1026,7 +1025,7 @@ func (c *Client4) GetProfileImage(userId, etag string) ([]byte, *Response, error
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetProfileImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -2774,7 +2773,7 @@ func (c *Client4) GetTeamIcon(teamId, etag string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetTeamIcon", "model.client.get_team_icon.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetTeamIcon", "model.client.get_team_icon.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4311,7 +4310,7 @@ func (c *Client4) GetFile(fileId string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4326,7 +4325,7 @@ func (c *Client4) DownloadFile(fileId string, download bool) ([]byte, *Response,
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("DownloadFile", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("DownloadFile", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4341,7 +4340,7 @@ func (c *Client4) GetFileThumbnail(fileId string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetFileThumbnail", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetFileThumbnail", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4356,7 +4355,7 @@ func (c *Client4) DownloadFileThumbnail(fileId string, download bool) ([]byte, *
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("DownloadFileThumbnail", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("DownloadFileThumbnail", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4381,7 +4380,7 @@ func (c *Client4) GetFilePreview(fileId string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetFilePreview", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetFilePreview", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4396,7 +4395,7 @@ func (c *Client4) DownloadFilePreview(fileId string, download bool) ([]byte, *Re
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("DownloadFilePreview", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("DownloadFilePreview", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -4464,7 +4463,7 @@ func (c *Client4) GenerateSupportPacket() ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_job_result_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_job_result_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -5268,7 +5267,7 @@ func (c *Client4) DownloadComplianceReport(reportId string) ([]byte, *Response,
return nil, BuildResponse(rp), AppErrorFromJSON(rp.Body) return nil, BuildResponse(rp), AppErrorFromJSON(rp.Body)
} }
data, err := ioutil.ReadAll(rp.Body) data, err := io.ReadAll(rp.Body)
if err != nil { if err != nil {
return nil, BuildResponse(rp), NewAppError("DownloadComplianceReport", "model.client.read_file.app_error", nil, err.Error(), rp.StatusCode) return nil, BuildResponse(rp), NewAppError("DownloadComplianceReport", "model.client.read_file.app_error", nil, err.Error(), rp.StatusCode)
} }
@@ -5614,7 +5613,7 @@ func (c *Client4) GetBrandImage() ([]byte, *Response, error) {
return nil, BuildResponse(r), AppErrorFromJSON(r.Body) return nil, BuildResponse(r), AppErrorFromJSON(r.Body)
} }
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetBrandImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetBrandImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -6560,7 +6559,7 @@ func (c *Client4) GetEmojiImage(emojiId string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetEmojiImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetEmojiImage", "model.client.read_file.app_error", nil, err.Error(), r.StatusCode)
} }
@@ -6801,7 +6800,7 @@ func (c *Client4) DownloadJob(jobId string) ([]byte, *Response, error) {
} }
defer closeBody(r) defer closeBody(r)
data, err := ioutil.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_job_result_file.app_error", nil, err.Error(), r.StatusCode) return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_job_result_file.app_error", nil, err.Error(), r.StatusCode)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package model
import ( import (
"encoding/json" "encoding/json"
"io" "io"
"io/ioutil"
"strings" "strings"
"github.com/mattermost/mattermost-server/v6/utils/jsonutils" "github.com/mattermost/mattermost-server/v6/utils/jsonutils"
@@ -36,7 +35,7 @@ func CommandResponseFromHTTPBody(contentType string, body io.Reader) (*CommandRe
if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" { if strings.TrimSpace(strings.Split(contentType, ";")[0]) == "application/json" {
return CommandResponseFromJSON(body) return CommandResponseFromJSON(body)
} }
if b, err := ioutil.ReadAll(body); err == nil { if b, err := io.ReadAll(body); err == nil {
return CommandResponseFromPlainText(string(b)), nil return CommandResponseFromPlainText(string(b)), nil
} }
return nil, nil return nil, nil
@@ -49,7 +48,7 @@ func CommandResponseFromPlainText(text string) *CommandResponse {
} }
func CommandResponseFromJSON(data io.Reader) (*CommandResponse, error) { func CommandResponseFromJSON(data io.Reader) (*CommandResponse, error) {
b, err := ioutil.ReadAll(data) b, err := io.ReadAll(data)
if err != nil { if err != nil {
return nil, err return nil, err
} }

Просмотреть файл

@@ -8,7 +8,7 @@ import (
"encoding/base64" "encoding/base64"
_ "image/gif" _ "image/gif"
_ "image/png" _ "image/png"
"io/ioutil" "os"
"strings" "strings"
"testing" "testing"
@@ -76,13 +76,13 @@ func TestFileInfoIsImage(t *testing.T) {
func TestGetInfoForFile(t *testing.T) { func TestGetInfoForFile(t *testing.T) {
fakeFile := make([]byte, 1000) fakeFile := make([]byte, 1000)
pngFile, err := ioutil.ReadFile("../tests/test.png") pngFile, err := os.ReadFile("../tests/test.png")
require.NoError(t, err, "Failed to load test.png") require.NoError(t, err, "Failed to load test.png")
// base 64 encoded version of handtinywhite.gif from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever // base 64 encoded version of handtinywhite.gif from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever
gifFile, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=") gifFile, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIABAP///wAAACwAAAAAAQABAAACAkQBADs=")
animatedGifFile, err := ioutil.ReadFile("../tests/testgif.gif") animatedGifFile, err := os.ReadFile("../tests/testgif.gif")
require.NoError(t, err, "Failed to load testgif.gif") require.NoError(t, err, "Failed to load testgif.gif")
var ttc = []struct { var ttc = []struct {

Просмотреть файл

@@ -6,7 +6,7 @@ package model
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -108,42 +108,41 @@ type PluginSettingsSchema struct {
// //
// Example plugin.json: // Example plugin.json:
// //
// // {
// { // "id": "com.mycompany.myplugin",
// "id": "com.mycompany.myplugin", // "name": "My Plugin",
// "name": "My Plugin", // "description": "This is my plugin",
// "description": "This is my plugin", // "homepage_url": "https://example.com",
// "homepage_url": "https://example.com", // "support_url": "https://example.com/support",
// "support_url": "https://example.com/support", // "release_notes_url": "https://example.com/releases/v0.0.1",
// "release_notes_url": "https://example.com/releases/v0.0.1", // "icon_path": "assets/logo.svg",
// "icon_path": "assets/logo.svg", // "version": "0.1.0",
// "version": "0.1.0", // "min_server_version": "5.6.0",
// "min_server_version": "5.6.0", // "server": {
// "server": { // "executables": {
// "executables": { // "linux-amd64": "server/dist/plugin-linux-amd64",
// "linux-amd64": "server/dist/plugin-linux-amd64", // "darwin-amd64": "server/dist/plugin-darwin-amd64",
// "darwin-amd64": "server/dist/plugin-darwin-amd64", // "windows-amd64": "server/dist/plugin-windows-amd64.exe"
// "windows-amd64": "server/dist/plugin-windows-amd64.exe" // }
// } // },
// }, // "webapp": {
// "webapp": { // "bundle_path": "webapp/dist/main.js"
// "bundle_path": "webapp/dist/main.js" // },
// }, // "settings_schema": {
// "settings_schema": { // "header": "Some header text",
// "header": "Some header text", // "footer": "Some footer text",
// "footer": "Some footer text", // "settings": [{
// "settings": [{ // "key": "someKey",
// "key": "someKey", // "display_name": "Enable Extra Feature",
// "display_name": "Enable Extra Feature", // "type": "bool",
// "type": "bool", // "help_text": "When true, an extra feature will be enabled!",
// "help_text": "When true, an extra feature will be enabled!", // "default": "false"
// "default": "false" // }]
// }] // },
// }, // "props": {
// "props": { // "someKey": "someData"
// "someKey": "someData" // }
// } // }
// }
type Manifest struct { type Manifest struct {
// The id is a globally unique identifier that represents your plugin. Ids must be at least // The id is a globally unique identifier that represents your plugin. Ids must be at least
// 3 characters, at most 190 characters and must match ^[a-zA-Z0-9-_\.]+$. // 3 characters, at most 190 characters and must match ^[a-zA-Z0-9-_\.]+$.
@@ -426,7 +425,7 @@ func FindManifest(dir string) (manifest *Manifest, path string, err error) {
} }
continue continue
} }
b, ioerr := ioutil.ReadAll(f) b, ioerr := io.ReadAll(f)
f.Close() f.Close()
if ioerr != nil { if ioerr != nil {
return nil, path, ioerr return nil, path, ioerr

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -244,7 +243,7 @@ func TestFindManifest(t *testing.T) {
{"plugin.yml", `id: FOO`, false, false}, {"plugin.yml", `id: FOO`, false, false},
{"plugin.yml", "bar", true, false}, {"plugin.yml", "bar", true, false},
} { } {
dir, err := ioutil.TempDir("", "mm-plugin-test") dir, err := os.MkdirTemp("", "mm-plugin-test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -396,7 +395,7 @@ settings_schema:
func TestFindManifest_FileErrors(t *testing.T) { func TestFindManifest_FileErrors(t *testing.T) {
for _, tc := range []string{"plugin.yaml", "plugin.json"} { for _, tc := range []string{"plugin.yaml", "plugin.json"} {
dir, err := ioutil.TempDir("", "mm-plugin-test") dir, err := os.MkdirTemp("", "mm-plugin-test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -417,7 +416,7 @@ func TestFindManifest_FolderPermission(t *testing.T) {
} }
for _, tc := range []string{"plugin.yaml", "plugin.json"} { for _, tc := range []string{"plugin.yaml", "plugin.json"} {
dir, err := ioutil.TempDir("", "mm-plugin-test") dir, err := os.MkdirTemp("", "mm-plugin-test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

Просмотреть файл

@@ -5,7 +5,7 @@ package model
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "os"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@@ -369,13 +369,13 @@ func TestPost_AttachmentsEqual(t *testing.T) {
var markdownSample, markdownSampleWithRewrittenImageURLs string var markdownSample, markdownSampleWithRewrittenImageURLs string
func init() { func init() {
bytes, err := ioutil.ReadFile("testdata/markdown-sample.md") bytes, err := os.ReadFile("testdata/markdown-sample.md")
if err != nil { if err != nil {
panic(err) panic(err)
} }
markdownSample = string(bytes) markdownSample = string(bytes)
bytes, err = ioutil.ReadFile("testdata/markdown-sample-with-rewritten-image-urls.md") bytes, err = os.ReadFile("testdata/markdown-sample-with-rewritten-image-urls.md")
if err != nil { if err != nil {
panic(err) panic(err)
} }

Просмотреть файл

@@ -13,7 +13,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/rpc" "net/rpc"
@@ -444,7 +443,7 @@ func (s *hooksRPCServer) ServeHTTP(args *Z_ServeHTTPArgs, returns *struct{}) err
} }
r.Body = connectIOReader(connection) r.Body = connectIOReader(connection)
} else { } else {
r.Body = ioutil.NopCloser(&bytes.Buffer{}) r.Body = io.NopCloser(&bytes.Buffer{})
} }
defer r.Body.Close() defer r.Body.Close()
@@ -487,7 +486,7 @@ func (g *apiRPCClient) PluginHTTP(request *http.Request) *http.Response {
} }
if request.Body != nil { if request.Body != nil {
requestBody, err := ioutil.ReadAll(request.Body) requestBody, err := io.ReadAll(request.Body)
if err != nil { if err != nil {
log.Printf("RPC call to PluginHTTP API failed: %s", err.Error()) log.Printf("RPC call to PluginHTTP API failed: %s", err.Error())
return nil return nil
@@ -504,20 +503,20 @@ func (g *apiRPCClient) PluginHTTP(request *http.Request) *http.Response {
return nil return nil
} }
_returns.Response.Body = ioutil.NopCloser(bytes.NewBuffer(_returns.ResponseBody)) _returns.Response.Body = io.NopCloser(bytes.NewBuffer(_returns.ResponseBody))
return _returns.Response return _returns.Response
} }
func (s *apiRPCServer) PluginHTTP(args *Z_PluginHTTPArgs, returns *Z_PluginHTTPReturns) error { func (s *apiRPCServer) PluginHTTP(args *Z_PluginHTTPArgs, returns *Z_PluginHTTPReturns) error {
args.Request.Body = ioutil.NopCloser(bytes.NewBuffer(args.RequestBody)) args.Request.Body = io.NopCloser(bytes.NewBuffer(args.RequestBody))
if hook, ok := s.impl.(interface { if hook, ok := s.impl.(interface {
PluginHTTP(request *http.Request) *http.Response PluginHTTP(request *http.Request) *http.Response
}); ok { }); ok {
response := hook.PluginHTTP(args.Request) response := hook.PluginHTTP(args.Request)
responseBody, err := ioutil.ReadAll(response.Body) responseBody, err := io.ReadAll(response.Body)
if err != nil { if err != nil {
return encodableError(fmt.Errorf("RPC call to PluginHTTP API failed: %s", err.Error())) return encodableError(fmt.Errorf("RPC call to PluginHTTP API failed: %s", err.Error()))
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package plugin
import ( import (
"fmt" "fmt"
"hash/fnv" "hash/fnv"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
@@ -86,7 +85,7 @@ func NewEnvironment(newAPIImpl apiImplCreatorFunc,
// //
// Plugins are found non-recursively and paths beginning with a dot are always ignored. // Plugins are found non-recursively and paths beginning with a dot are always ignored.
func scanSearchPath(path string) ([]*model.BundleInfo, error) { func scanSearchPath(path string) ([]*model.BundleInfo, error) {
files, err := ioutil.ReadDir(path) files, err := os.ReadDir(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -468,7 +467,7 @@ func (env *Environment) UnpackWebappBundle(id string) (*model.Manifest, error) {
sourceBundleFilepath := filepath.Join(destinationPath, filepath.Base(bundlePath)) sourceBundleFilepath := filepath.Join(destinationPath, filepath.Base(bundlePath))
sourceBundleFileContents, err := ioutil.ReadFile(sourceBundleFilepath) sourceBundleFileContents, err := os.ReadFile(sourceBundleFilepath)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read webapp bundle: %v", id) return nil, errors.Wrapf(err, "unable to read webapp bundle: %v", id)
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package plugin
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -16,7 +15,7 @@ import (
) )
func TestAvailablePlugins(t *testing.T) { func TestAvailablePlugins(t *testing.T) {
dir, err1 := ioutil.TempDir("", "mm-plugin-test") dir, err1 := os.MkdirTemp("", "mm-plugin-test")
require.NoError(t, err1) require.NoError(t, err1)
t.Cleanup(func() { t.Cleanup(func() {
os.RemoveAll(dir) os.RemoveAll(dir)
@@ -40,7 +39,7 @@ func TestAvailablePlugins(t *testing.T) {
path := filepath.Join(dir, "plugin1", "plugin.json") path := filepath.Join(dir, "plugin1", "plugin.json")
manifestJSON, jsonErr := json.Marshal(bundle1.Manifest) manifestJSON, jsonErr := json.Marshal(bundle1.Manifest)
require.NoError(t, jsonErr) require.NoError(t, jsonErr)
err = ioutil.WriteFile(path, manifestJSON, 0644) err = os.WriteFile(path, manifestJSON, 0644)
require.NoError(t, err) require.NoError(t, err)
bundles, err := env.Available() bundles, err := env.Available()
@@ -54,7 +53,7 @@ func TestAvailablePlugins(t *testing.T) {
defer os.RemoveAll(filepath.Join(dir, "plugin2")) defer os.RemoveAll(filepath.Join(dir, "plugin2"))
path := filepath.Join(dir, "plugin2", "manifest.json") path := filepath.Join(dir, "plugin2", "manifest.json")
err = ioutil.WriteFile(path, []byte("{}"), 0644) err = os.WriteFile(path, []byte("{}"), 0644)
require.NoError(t, err) require.NoError(t, err)
bundles, err := env.Available() bundles, err := env.Available()

Просмотреть файл

@@ -4,7 +4,6 @@
package plugin package plugin
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -27,7 +26,7 @@ func TestPluginHealthCheck(t *testing.T) {
} }
func testPluginHealthCheckSuccess(t *testing.T) { func testPluginHealthCheckSuccess(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -48,7 +47,7 @@ func testPluginHealthCheckSuccess(t *testing.T) {
} }
`, backend) `, backend)
err = ioutil.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600) err = os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600)
require.NoError(t, err) require.NoError(t, err)
bundle := model.BundleInfoForPath(dir) bundle := model.BundleInfoForPath(dir)
@@ -65,7 +64,7 @@ func testPluginHealthCheckSuccess(t *testing.T) {
} }
func testPluginHealthCheckPanic(t *testing.T) { func testPluginHealthCheckPanic(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -91,7 +90,7 @@ func testPluginHealthCheckPanic(t *testing.T) {
} }
`, backend) `, backend)
err = ioutil.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600) err = os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600)
require.NoError(t, err) require.NoError(t, err)
bundle := model.BundleInfoForPath(dir) bundle := model.BundleInfoForPath(dir)

Просмотреть файл

@@ -10,8 +10,8 @@ import (
"go/parser" "go/parser"
"go/printer" "go/printer"
"go/token" "go/token"
"io/ioutil"
"log" "log"
"os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -580,7 +580,7 @@ func generateHooksGlue(info *PluginInterfaceInfo) {
panic(err) panic(err)
} }
if err := ioutil.WriteFile(filepath.Join(getPluginPackageDir(), "client_rpc_generated.go"), formatted, 0664); err != nil { if err := os.WriteFile(filepath.Join(getPluginPackageDir(), "client_rpc_generated.go"), formatted, 0664); err != nil {
panic(err) panic(err)
} }
} }
@@ -613,7 +613,7 @@ func generateProductHooksInterfaces(info *PluginInterfaceInfo) {
panic(err) panic(err)
} }
if err := ioutil.WriteFile(filepath.Join(getPluginPackageDir(), "product_hooks_generated.go"), formatted, 0664); err != nil { if err := os.WriteFile(filepath.Join(getPluginPackageDir(), "product_hooks_generated.go"), formatted, 0664); err != nil {
panic(err) panic(err)
} }
} }
@@ -667,7 +667,7 @@ func generatePluginTimerLayer(info *PluginInterfaceInfo) {
panic(err) panic(err)
} }
if err := ioutil.WriteFile(filepath.Join(getPluginPackageDir(), fileName), formatted, 0664); err != nil { if err := os.WriteFile(filepath.Join(getPluginPackageDir(), fileName), formatted, 0664); err != nil {
panic(err) panic(err)
} }
} }

Просмотреть файл

@@ -5,7 +5,7 @@ package plugintest_test
import ( import (
"fmt" "fmt"
"io/ioutil" io "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -52,7 +52,7 @@ func Example() {
r := httptest.NewRequest("GET", "/", nil) r := httptest.NewRequest("GET", "/", nil)
r.Header.Add("Mattermost-User-Id", user.Id) r.Header.Add("Mattermost-User-Id", user.Id)
p.ServeHTTP(&plugin.Context{}, w, r) p.ServeHTTP(&plugin.Context{}, w, r)
body, err := ioutil.ReadAll(w.Result().Body) body, err := io.ReadAll(w.Result().Body)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "Welcome back, billybob!", string(body)) assert.Equal(t, "Welcome back, billybob!", string(body))
} }

Просмотреть файл

@@ -4,7 +4,6 @@
package plugin package plugin
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -28,11 +27,11 @@ func TestSupervisor(t *testing.T) {
} }
func testSupervisorInvalidExecutablePath(t *testing.T) { func testSupervisorInvalidExecutablePath(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
ioutil.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "/foo/../../backend.exe"}}`), 0600) os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "/foo/../../backend.exe"}}`), 0600)
bundle := model.BundleInfoForPath(dir) bundle := model.BundleInfoForPath(dir)
log := mlog.CreateConsoleTestLogger(true, mlog.LvlError) log := mlog.CreateConsoleTestLogger(true, mlog.LvlError)
@@ -43,11 +42,11 @@ func testSupervisorInvalidExecutablePath(t *testing.T) {
} }
func testSupervisorNonExistentExecutablePath(t *testing.T) { func testSupervisorNonExistentExecutablePath(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
ioutil.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "thisfileshouldnotexist"}}`), 0600) os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "thisfileshouldnotexist"}}`), 0600)
bundle := model.BundleInfoForPath(dir) bundle := model.BundleInfoForPath(dir)
log := mlog.CreateConsoleTestLogger(true, mlog.LvlError) log := mlog.CreateConsoleTestLogger(true, mlog.LvlError)
@@ -59,7 +58,7 @@ func testSupervisorNonExistentExecutablePath(t *testing.T) {
// If plugin development goes really wrong, let's make sure plugin activation won't block forever. // If plugin development goes really wrong, let's make sure plugin activation won't block forever.
func testSupervisorStartTimeout(t *testing.T) { func testSupervisorStartTimeout(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
@@ -73,7 +72,7 @@ func testSupervisorStartTimeout(t *testing.T) {
} }
`, backend) `, backend)
ioutil.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600) os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(`{"id": "foo", "server": {"executable": "backend.exe"}}`), 0600)
bundle := model.BundleInfoForPath(dir) bundle := model.BundleInfoForPath(dir)
log := mlog.CreateConsoleTestLogger(true, mlog.LvlError) log := mlog.CreateConsoleTestLogger(true, mlog.LvlError)

Просмотреть файл

@@ -5,7 +5,6 @@ package main
import ( import (
"encoding/json" "encoding/json"
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -15,14 +14,14 @@ import (
) )
func TestDefaultsGenerator(t *testing.T) { func TestDefaultsGenerator(t *testing.T) {
tmpFile, err := ioutil.TempFile("", "tempconfig") tmpFile, err := os.CreateTemp("", "tempconfig")
defer os.Remove(tmpFile.Name()) defer os.Remove(tmpFile.Name())
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, generateDefaultConfig(tmpFile)) require.NoError(t, generateDefaultConfig(tmpFile))
_ = tmpFile.Close() _ = tmpFile.Close()
var config model.Config var config model.Config
b, err := ioutil.ReadFile(tmpFile.Name()) b, err := os.ReadFile(tmpFile.Name())
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, json.Unmarshal(b, &config)) require.NoError(t, json.Unmarshal(b, &config))
require.Equal(t, *config.SqlSettings.AtRestEncryptKey, "") require.Equal(t, *config.SqlSettings.AtRestEncryptKey, "")

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -25,7 +24,7 @@ func (ae *archiveExtractor) Match(filename string) bool {
} }
func (ae *archiveExtractor) Extract(name string, r io.ReadSeeker) (string, error) { func (ae *archiveExtractor) Extract(name string, r io.ReadSeeker) (string, error) {
dir, err := ioutil.TempDir(os.TempDir(), "archiver") dir, err := os.MkdirTemp(os.TempDir(), "archiver")
if err != nil { if err != nil {
return "", fmt.Errorf("error creating temporary file: %v", err) return "", fmt.Errorf("error creating temporary file: %v", err)
} }
@@ -49,7 +48,7 @@ func (ae *archiveExtractor) Extract(name string, r io.ReadSeeker) (string, error
filename = strings.ReplaceAll(filename, "-", " ") filename = strings.ReplaceAll(filename, "-", " ")
filename = strings.ReplaceAll(filename, ".", " ") filename = strings.ReplaceAll(filename, ".", " ")
filename = strings.ReplaceAll(filename, ",", " ") filename = strings.ReplaceAll(filename, ",", " ")
data, err2 := ioutil.ReadAll(file) data, err2 := io.ReadAll(file)
if err2 != nil { if err2 != nil {
return err2 return err2
} }

Просмотреть файл

@@ -10,7 +10,6 @@ package docextractor
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"path" "path"
@@ -63,7 +62,7 @@ func (mpe *mmPreviewExtractor) Extract(filename string, file io.ReadSeeker) (str
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
return "", errors.New("Unable to generate file preview using mmpreview (The server has replied with an error)") return "", errors.New("Unable to generate file preview using mmpreview (The server has replied with an error)")
} }
data, err := ioutil.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return "", errors.Wrap(err, "unable to read the response from mmpreview") return "", errors.Wrap(err, "unable to read the response from mmpreview")
} }

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path" "path"
"strings" "strings"
@@ -33,7 +32,7 @@ func (pe *pdfExtractor) Extract(filename string, r io.ReadSeeker) (out string, o
outErr = errors.New("error extracting pdf text") outErr = errors.New("error extracting pdf text")
} }
}() }()
f, err := ioutil.TempFile(os.TempDir(), "pdflib") f, err := os.CreateTemp(os.TempDir(), "pdflib")
if err != nil { if err != nil {
return "", fmt.Errorf("error creating temporary file: %v", err) return "", fmt.Errorf("error creating temporary file: %v", err)
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package docextractor
import ( import (
"io" "io"
"io/ioutil"
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
) )
@@ -47,6 +46,6 @@ func (pe *plainExtractor) Extract(filename string, r io.ReadSeeker) (string, err
} }
} }
text, _ := ioutil.ReadAll(r) text, _ := io.ReadAll(r)
return string(runes[0:total]) + string(text), nil return string(runes[0:total]) + string(text), nil
} }

Просмотреть файл

@@ -6,7 +6,7 @@ package httpservice
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -108,7 +108,7 @@ func TestHTTPClientWithProxy(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "proxy", string(body)) require.Equal(t, "proxy", string(body))
} }

Просмотреть файл

@@ -4,7 +4,7 @@
package imageproxy package imageproxy
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -85,7 +85,7 @@ func TestAtmosCamoBackend_GetImageDirect(t *testing.T) {
assert.Equal(t, "image/png", contentType) assert.Equal(t, "image/png", contentType)
require.NotNil(t, body) require.NotNil(t, body)
respBody, _ := ioutil.ReadAll(body) respBody, _ := io.ReadAll(body)
assert.Equal(t, []byte("1111111111"), respBody) assert.Equal(t, []byte("1111111111"), respBody)
} }

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"net" "net"
"net/http" "net/http"
@@ -134,7 +133,7 @@ func (backend *LocalBackend) GetImageDirect(imageURL string) (io.ReadCloser, str
return nil, "", ErrLocalRequestFailed return nil, "", ErrLocalRequestFailed
} }
return ioutil.NopCloser(recorder.Body), recorder.Header().Get("Content-Type"), nil return io.NopCloser(recorder.Body), recorder.Header().Get("Content-Type"), nil
} }
func (backend *LocalBackend) ServeImage(w http.ResponseWriter, req *http.Request) { func (backend *LocalBackend) ServeImage(w http.ResponseWriter, req *http.Request) {
@@ -176,7 +175,7 @@ func (backend *LocalBackend) ServeImage(w http.ResponseWriter, req *http.Request
if contentType == "" || contentType == "application/octet-stream" || contentType == "binary/octet-stream" { if contentType == "" || contentType == "application/octet-stream" || contentType == "binary/octet-stream" {
// try to detect content type // try to detect content type
b := bufio.NewReader(resp.Body) b := bufio.NewReader(resp.Body)
resp.Body = ioutil.NopCloser(b) resp.Body = io.NopCloser(b)
contentType = peekContentType(b) contentType = peekContentType(b)
} }
if resp.ContentLength != 0 && !contentTypeMatches(imageContentTypes, contentType) { if resp.ContentLength != 0 && !contentTypeMatches(imageContentTypes, contentType) {

Просмотреть файл

@@ -4,7 +4,7 @@
package imageproxy package imageproxy
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -60,7 +60,7 @@ func TestLocalBackend_GetImage(t *testing.T) {
assert.Equal(t, "max-age=2592000, private", resp.Header.Get("Cache-Control")) assert.Equal(t, "max-age=2592000, private", resp.Header.Get("Cache-Control"))
assert.Equal(t, "10", resp.Header.Get("Content-Length")) assert.Equal(t, "10", resp.Header.Get("Content-Length"))
respBody, _ := ioutil.ReadAll(resp.Body) respBody, _ := io.ReadAll(resp.Body)
assert.Equal(t, []byte("1111111111"), respBody) assert.Equal(t, []byte("1111111111"), respBody)
}) })
@@ -190,7 +190,7 @@ func TestLocalBackend_GetImage(t *testing.T) {
assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "attachment;filename=\"test.svg\"", resp.Header.Get("Content-Disposition")) assert.Equal(t, "attachment;filename=\"test.svg\"", resp.Header.Get("Content-Disposition"))
_, err = ioutil.ReadAll(resp.Body) _, err = io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
}) })
@@ -247,7 +247,7 @@ func TestLocalBackend_GetImageDirect(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "image/png", contentType) assert.Equal(t, "image/png", contentType)
respBody, _ := ioutil.ReadAll(body) respBody, _ := io.ReadAll(body)
assert.Equal(t, []byte("1111111111"), respBody) assert.Equal(t, []byte("1111111111"), respBody)
}) })

Просмотреть файл

@@ -7,7 +7,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@@ -117,7 +117,7 @@ func (rcs *Service) sendFileToRemote(timeout time.Duration, task sendFileTask) (
} }
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 nil, err return nil, err
} }

Просмотреть файл

@@ -8,7 +8,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@@ -163,7 +163,7 @@ func (rcs *Service) sendFrameToRemote(timeout time.Duration, rc *model.RemoteClu
return nil, err return nil, 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 nil, err return nil, err
} }

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/url" "net/url"
@@ -134,7 +133,7 @@ func (rcs *Service) sendProfileImageToRemote(timeout time.Duration, task sendPro
} }
defer resp.Body.Close() defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body) _, err = io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }

Просмотреть файл

@@ -4,7 +4,6 @@
package bleveengine package bleveengine
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -37,7 +36,7 @@ func TestBleveEngineTestSuite(t *testing.T) {
} }
func (s *BleveEngineTestSuite) setupIndexes() { func (s *BleveEngineTestSuite) setupIndexes() {
indexDir, err := ioutil.TempDir("", "mmbleve") indexDir, err := os.MkdirTemp("", "mmbleve")
if err != nil { if err != nil {
s.Require().FailNow("Cannot setup bleveengine tests: %s", err.Error()) s.Require().FailNow("Cannot setup bleveengine tests: %s", err.Error())
} }

Просмотреть файл

@@ -5,7 +5,6 @@ package indexer
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -33,7 +32,7 @@ func TestBleveIndexer(t *testing.T) {
mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil) mockStore.JobStore.On("UpdateOptimistically", job, model.JobStatusInProgress).Return(true, nil)
mockStore.PostStore.On("GetOldestEntityCreationTime").Return(int64(1), errors.New("")) // intentionally return error to return from function mockStore.PostStore.On("GetOldestEntityCreationTime").Return(int64(1), errors.New("")) // intentionally return error to return from function
tempDir, err := ioutil.TempDir("", "setupConfigFile") tempDir, err := os.MkdirTemp("", "setupConfigFile")
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { t.Cleanup(func() {

Просмотреть файл

@@ -9,7 +9,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -108,7 +108,7 @@ func makeTelemetryServiceAndReceiver(t *testing.T, cloudLicense bool) (*Telemetr
pchan := make(chan testTelemetryPayload, 100) pchan := make(chan testTelemetryPayload, 100)
receiver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { receiver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)
var p testTelemetryPayload var p testTelemetryPayload
@@ -154,8 +154,8 @@ func initializeMocks(cfg *model.Config, cloudLicense bool) (*mocks.ServerIface,
serverIfaceMock.On("Config").Return(cfg) serverIfaceMock.On("Config").Return(cfg)
serverIfaceMock.On("IsLeader").Return(true) serverIfaceMock.On("IsLeader").Return(true)
pluginDir, _ := ioutil.TempDir("", "") pluginDir, _ := os.MkdirTemp("", "")
webappPluginDir, _ := ioutil.TempDir("", "") webappPluginDir, _ := os.MkdirTemp("", "")
cleanUp := func() { cleanUp := func() {
os.RemoveAll(pluginDir) os.RemoveAll(pluginDir)
os.RemoveAll(webappPluginDir) os.RemoveAll(webappPluginDir)

Просмотреть файл

@@ -10,7 +10,6 @@ import (
_ "embed" _ "embed"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"os/user" "os/user"
@@ -257,7 +256,7 @@ func download(url string, limit int64) (string, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
out, err := ioutil.TempFile("", "*_mattermost.tar.gz") out, err := os.CreateTemp("", "*_mattermost.tar.gz")
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -310,7 +309,7 @@ func extractBinary(executablePath string, filename string) error {
if header.Typeflag == tar.TypeReg && header.Name == "mattermost/bin/mattermost" { if header.Typeflag == tar.TypeReg && header.Name == "mattermost/bin/mattermost" {
permissions := getFilePermissionsOrDefault(executablePath, 0755) permissions := getFilePermissionsOrDefault(executablePath, 0755)
tmpFile, err := ioutil.TempFile(path.Dir(executablePath), "*") tmpFile, err := os.CreateTemp(path.Dir(executablePath), "*")
if err != nil { if err != nil {
return err return err
} }

Просмотреть файл

@@ -6,7 +6,7 @@ package upgrader
import ( import (
"archive/tar" "archive/tar"
"compress/gzip" "compress/gzip"
"io/ioutil" "io"
"os" "os"
"testing" "testing"
@@ -75,12 +75,12 @@ func TestGetCurrentVersionTgzURL(t *testing.T) {
func TestExtractBinary(t *testing.T) { func TestExtractBinary(t *testing.T) {
t.Run("extract from empty file", func(t *testing.T) { t.Run("extract from empty file", func(t *testing.T) {
tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") tmpMockTarGz, err := os.CreateTemp("", "mock_tgz")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockTarGz.Name()) defer os.Remove(tmpMockTarGz.Name())
tmpMockTarGz.Close() tmpMockTarGz.Close()
tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") tmpMockExecutable, err := os.CreateTemp("", "mock_exe")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockExecutable.Name()) defer os.Remove(tmpMockExecutable.Name())
tmpMockExecutable.Close() tmpMockExecutable.Close()
@@ -89,7 +89,7 @@ func TestExtractBinary(t *testing.T) {
}) })
t.Run("extract from empty tar.gz file", func(t *testing.T) { t.Run("extract from empty tar.gz file", func(t *testing.T) {
tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") tmpMockTarGz, err := os.CreateTemp("", "mock_tgz")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockTarGz.Name()) defer os.Remove(tmpMockTarGz.Name())
gz := gzip.NewWriter(tmpMockTarGz) gz := gzip.NewWriter(tmpMockTarGz)
@@ -98,7 +98,7 @@ func TestExtractBinary(t *testing.T) {
gz.Close() gz.Close()
tmpMockTarGz.Close() tmpMockTarGz.Close()
tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") tmpMockExecutable, err := os.CreateTemp("", "mock_exe")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockExecutable.Name()) defer os.Remove(tmpMockExecutable.Name())
tmpMockExecutable.Close() tmpMockExecutable.Close()
@@ -107,7 +107,7 @@ func TestExtractBinary(t *testing.T) {
}) })
t.Run("extract from tar.gz without mattermost/bin/mattermost file", func(t *testing.T) { t.Run("extract from tar.gz without mattermost/bin/mattermost file", func(t *testing.T) {
tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") tmpMockTarGz, err := os.CreateTemp("", "mock_tgz")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockTarGz.Name()) defer os.Remove(tmpMockTarGz.Name())
gz := gzip.NewWriter(tmpMockTarGz) gz := gzip.NewWriter(tmpMockTarGz)
@@ -123,7 +123,7 @@ func TestExtractBinary(t *testing.T) {
gz.Close() gz.Close()
tmpMockTarGz.Close() tmpMockTarGz.Close()
tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") tmpMockExecutable, err := os.CreateTemp("", "mock_exe")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockExecutable.Name()) defer os.Remove(tmpMockExecutable.Name())
tmpMockExecutable.Close() tmpMockExecutable.Close()
@@ -132,7 +132,7 @@ func TestExtractBinary(t *testing.T) {
}) })
t.Run("extract from tar.gz with mattermost/bin/mattermost file", func(t *testing.T) { t.Run("extract from tar.gz with mattermost/bin/mattermost file", func(t *testing.T) {
tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") tmpMockTarGz, err := os.CreateTemp("", "mock_tgz")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockTarGz.Name()) defer os.Remove(tmpMockTarGz.Name())
gz := gzip.NewWriter(tmpMockTarGz) gz := gzip.NewWriter(tmpMockTarGz)
@@ -148,7 +148,7 @@ func TestExtractBinary(t *testing.T) {
gz.Close() gz.Close()
tmpMockTarGz.Close() tmpMockTarGz.Close()
tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") tmpMockExecutable, err := os.CreateTemp("", "mock_exe")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpMockExecutable.Name()) defer os.Remove(tmpMockExecutable.Name())
tmpMockExecutable.Close() tmpMockExecutable.Close()
@@ -157,7 +157,7 @@ func TestExtractBinary(t *testing.T) {
tmpMockExecutableAfter, err := os.Open(tmpMockExecutable.Name()) tmpMockExecutableAfter, err := os.Open(tmpMockExecutable.Name())
require.NoError(t, err) require.NoError(t, err)
defer tmpMockExecutableAfter.Close() defer tmpMockExecutableAfter.Close()
bytes, err := ioutil.ReadAll(tmpMockExecutableAfter) bytes, err := io.ReadAll(tmpMockExecutableAfter)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte("test"), bytes) require.Equal(t, []byte("test"), bytes)
}) })

Просмотреть файл

@@ -6,7 +6,6 @@ package filestore
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
@@ -38,7 +37,7 @@ func TestLocalFileBackendTestSuite(t *testing.T) {
mlog.InitGlobalLogger(logger) mlog.InitGlobalLogger(logger)
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)

Просмотреть файл

@@ -6,7 +6,6 @@ package filestore
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"time" "time"
@@ -88,7 +87,7 @@ func (b *LocalFileBackend) Reader(path string) (ReadCloseSeeker, error) {
} }
func (b *LocalFileBackend) ReadFile(path string) ([]byte, error) { func (b *LocalFileBackend) ReadFile(path string) ([]byte, error) {
f, err := ioutil.ReadFile(filepath.Join(b.directory, path)) f, err := os.ReadFile(filepath.Join(b.directory, path))
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read file %s", path) return nil, errors.Wrapf(err, "unable to read file %s", path)
} }

Просмотреть файл

@@ -8,7 +8,6 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -241,7 +240,7 @@ func (b *S3FileBackend) ReadFile(path string) ([]byte, error) {
} }
defer minioObject.Close() defer minioObject.Close()
f, err := ioutil.ReadAll(minioObject) f, err := io.ReadAll(minioObject)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to read file %s", path) return nil, errors.Wrapf(err, "unable to read file %s", path)
} }

Просмотреть файл

@@ -6,8 +6,8 @@ package i18n
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings" "strings"
@@ -59,7 +59,7 @@ func InitTranslations(serverLocale, clientLocale string) error {
} }
func initTranslationsWithDir(dir string) error { func initTranslationsWithDir(dir string) error {
files, _ := ioutil.ReadDir(dir) files, _ := os.ReadDir(dir)
for _, f := range files { for _, f := range files {
if filepath.Ext(f.Name()) == ".json" { if filepath.Ext(f.Name()) == ".json" {
filename := f.Name() filename := f.Name()

Просмотреть файл

@@ -7,7 +7,6 @@ import (
"bytes" "bytes"
"context" "context"
"io" "io"
"io/ioutil"
"net" "net"
"net/mail" "net/mail"
"net/smtp" "net/smtp"
@@ -195,12 +194,12 @@ func TestSendMailUsingConfigAdvanced(t *testing.T) {
DeleteMailBox("test2@example.com") DeleteMailBox("test2@example.com")
// create two files with the same name that will both be attached to the email // create two files with the same name that will both be attached to the email
file1, err := ioutil.TempFile("", "*") file1, err := os.CreateTemp("", "*")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(file1.Name()) defer os.Remove(file1.Name())
file1.Write([]byte("hello world")) file1.Write([]byte("hello world"))
file1.Close() file1.Close()
file2, err := ioutil.TempFile("", "*") file2, err := os.CreateTemp("", "*")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(file2.Name()) defer os.Remove(file2.Name())
@@ -326,7 +325,7 @@ func (m *mockMailer) Write(p []byte) (int, error) {
func (m *mockMailer) Close() error { return nil } func (m *mockMailer) Close() error { return nil }
func TestSendMail(t *testing.T) { func TestSendMail(t *testing.T) {
dir, err := ioutil.TempDir(".", "mail-test-") dir, err := os.MkdirTemp(".", "mail-test-")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
mocm := &mockMailer{} mocm := &mockMailer{}

Просмотреть файл

@@ -6,7 +6,6 @@ package mlog_test
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@@ -99,7 +98,7 @@ func TestLoggingAfterInitialized(t *testing.T) {
t.Run(testCase.description, func(t *testing.T) { t.Run(testCase.description, func(t *testing.T) {
var filePath string var filePath string
if testCase.cfg.Type == "file" { if testCase.cfg.Type == "file" {
tempDir, err := ioutil.TempDir(os.TempDir(), "TestLoggingAfterInitialized") tempDir, err := os.MkdirTemp(os.TempDir(), "TestLoggingAfterInitialized")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tempDir) defer os.Remove(tempDir)
@@ -122,7 +121,7 @@ func TestLoggingAfterInitialized(t *testing.T) {
logger.Shutdown() logger.Shutdown()
if testCase.cfg.Type == "file" { if testCase.cfg.Type == "file" {
logs, err := ioutil.ReadFile(filePath) logs, err := os.ReadFile(filePath)
require.NoError(t, err) require.NoError(t, err)
actual := strings.TrimSpace(string(logs)) actual := strings.TrimSpace(string(logs))

Просмотреть файл

@@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"strings" "strings"
@@ -181,12 +180,14 @@ func NewLogger(options ...Option) (*Logger, error) {
// Configure provides a new configuration for this logger. // Configure provides a new configuration for this logger.
// Zero or more sources of config can be provided: // Zero or more sources of config can be provided:
// cfgFile - path to file containing JSON //
// cfgEscaped - JSON string probably from ENV var // cfgFile - path to file containing JSON
// cfgEscaped - JSON string probably from ENV var
// //
// For each case JSON containing log targets is provided. Target name collisions are resolved // For each case JSON containing log targets is provided. Target name collisions are resolved
// using the following precedence: // using the following precedence:
// cfgFile > cfgEscaped //
// cfgFile > cfgEscaped
// //
// An optional set of factories can be provided which will be called to create any target // An optional set of factories can be provided which will be called to create any target
// types or formatters not built-in. // types or formatters not built-in.
@@ -199,7 +200,7 @@ func (l *Logger) Configure(cfgFile string, cfgEscaped string, factories *Factori
// Add config from file // Add config from file
if cfgFile != "" { if cfgFile != "" {
b, err := ioutil.ReadFile(cfgFile) b, err := os.ReadFile(cfgFile)
if err != nil { if err != nil {
return fmt.Errorf("error reading logger config file %s: %w", cfgFile, err) return fmt.Errorf("error reading logger config file %s: %w", cfgFile, err)
} }

Просмотреть файл

@@ -6,7 +6,6 @@ package templates
import ( import (
"bytes" "bytes"
"html/template" "html/template"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -17,12 +16,12 @@ import (
) )
func TestHTMLTemplateWatcher(t *testing.T) { func TestHTMLTemplateWatcher(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
require.NoError(t, os.Mkdir(filepath.Join(dir, "templates"), 0700)) require.NoError(t, os.Mkdir(filepath.Join(dir, "templates"), 0700))
require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}foo{{ end }}`), 0600)) require.NoError(t, os.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}foo{{ end }}`), 0600))
prevDir, err := os.Getwd() prevDir, err := os.Getwd()
require.NoError(t, err) require.NoError(t, err)
@@ -45,7 +44,7 @@ func TestHTMLTemplateWatcher(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "foo", text) assert.Equal(t, "foo", text)
require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}bar{{ end }}`), 0600)) require.NoError(t, os.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}bar{{ end }}`), 0600))
require.Eventually(t, func() bool { require.Eventually(t, func() bool {
text, err := watcher.RenderToString("foo", Data{}) text, err := watcher.RenderToString("foo", Data{})

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше