diff --git a/api4/apitestlib.go b/api4/apitestlib.go index f2577e6ab9..b835853170 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "net" "net/http" @@ -84,7 +83,7 @@ func SetMainHelper(mh *testlib.MainHelper) { func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, enterprise bool, includeCache bool, updateConfig func(*model.Config), options []app.Option) *TestHelper { - tempWorkspace, err := ioutil.TempDir("", "apptest") + tempWorkspace, err := os.MkdirTemp("", "apptest") if err != nil { panic(err) } diff --git a/api4/bot_test.go b/api4/bot_test.go index c5b7bc1413..5a76d23f45 100644 --- a/api4/bot_test.go +++ b/api4/bot_test.go @@ -5,7 +5,7 @@ package api4 import ( "encoding/json" - "io/ioutil" + "io" "strings" "testing" @@ -461,7 +461,7 @@ func TestPatchBot(t *testing.T) { r, err := th.Client.DoAPIPut("/bots/"+createdBot.UserId, `{"creator_id":"`+th.BasicUser2.Id+`"}`) require.NoError(t, err) defer func() { - _, _ = ioutil.ReadAll(r.Body) + _, _ = io.ReadAll(r.Body) _ = r.Body.Close() }() var patchedBot *model.Bot diff --git a/api4/cloud.go b/api4/cloud.go index c9675bb118..6ebeccf706 100644 --- a/api4/cloud.go +++ b/api4/cloud.go @@ -7,7 +7,7 @@ import ( "bytes" "encoding/binary" "encoding/json" - "io/ioutil" + "io" "net/http" "time" @@ -123,7 +123,7 @@ func changeSubscription(c *Context, w http.ResponseWriter, r *http.Request) { return } - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.changeSubscription", "api.cloud.app_error", nil, err.Error(), http.StatusBadRequest) return @@ -174,7 +174,7 @@ func requestCloudTrial(c *Context, w http.ResponseWriter, r *http.Request) { } // check if the email needs to be set - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return @@ -221,7 +221,7 @@ func validateBusinessEmail(c *Context, w http.ResponseWriter, r *http.Request) { return } - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.requestCloudTrial", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return @@ -394,7 +394,7 @@ func updateCloudCustomer(c *Context, w http.ResponseWriter, r *http.Request) { return } - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.updateCloudCustomer", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return @@ -432,7 +432,7 @@ func updateCloudCustomerAddress(c *Context, w http.ResponseWriter, r *http.Reque return } - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.updateCloudCustomerAddress", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return @@ -504,7 +504,7 @@ func confirmCustomerPayment(c *Context, w http.ResponseWriter, r *http.Request) auditRec := c.MakeAuditRecord("confirmCustomerPayment", audit.Fail) defer c.LogAuditRec(auditRec) - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.confirmCustomerPayment", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return @@ -594,7 +594,7 @@ func handleCWSWebhook(c *Context, w http.ResponseWriter, r *http.Request) { return } - bodyBytes, err := ioutil.ReadAll(r.Body) + bodyBytes, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.handleCWSWebhook", "api.cloud.app_error", nil, err.Error(), http.StatusInternalServerError) return diff --git a/api4/config_test.go b/api4/config_test.go index c200e306fc..52de0491c8 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -6,7 +6,7 @@ package api4 import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -533,7 +533,7 @@ func TestUpdateConfigRestrictSystemAdmin(t *testing.T) { } func TestUpdateConfigDiffInAuditRecord(t *testing.T) { - logFile, err := ioutil.TempFile("", "adv.log") + logFile, err := os.CreateTemp("", "adv.log") require.NoError(t, err) defer os.Remove(logFile.Name()) @@ -569,7 +569,7 @@ func TestUpdateConfigDiffInAuditRecord(t *testing.T) { require.NoError(t, logFile.Sync()) - data, err := ioutil.ReadAll(logFile) + data, err := io.ReadAll(logFile) require.NoError(t, err) require.NotEmpty(t, data) @@ -955,7 +955,7 @@ func TestMigrateConfig(t *testing.T) { file, err := json.MarshalIndent(cfg, "", " ") require.NoError(t, err) - err = ioutil.WriteFile("from.json", file, 0644) + err = os.WriteFile("from.json", file, 0644) require.NoError(t, err) defer os.Remove("from.json") diff --git a/api4/emoji_test.go b/api4/emoji_test.go index ac8395c26e..93b915fc8f 100644 --- a/api4/emoji_test.go +++ b/api4/emoji_test.go @@ -7,7 +7,6 @@ import ( "bytes" "image" _ "image/gif" - "io/ioutil" "os" "path/filepath" "testing" @@ -100,7 +99,7 @@ func TestCreateEmoji(t *testing.T) { } 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) newEmoji, _, err = client.CreateEmoji(emoji, bytes, "image.webp") require.NoError(t, err) diff --git a/api4/export_test.go b/api4/export_test.go index db3a961807..5a591598d4 100644 --- a/api4/export_test.go +++ b/api4/export_test.go @@ -6,7 +6,6 @@ package api4 import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -151,7 +150,7 @@ func TestDownloadExport(t *testing.T) { data := randomBytes(t, 1024*1024) var buf bytes.Buffer 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) n, _, err := c.DownloadExport(exportName, &buf, 0) @@ -168,7 +167,7 @@ func TestDownloadExport(t *testing.T) { data := randomBytes(t, 1024*1024) var buf bytes.Buffer 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) offset := 1024 * 512 diff --git a/api4/file_test.go b/api4/file_test.go index cc9b055985..49fcfd9b79 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -9,7 +9,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/textproto" @@ -55,7 +54,7 @@ func fileBytes(t *testing.T, path string) []byte { f, err := os.Open(path) require.NoError(t, err) defer f.Close() - bb, err := ioutil.ReadAll(f) + bb, err := io.ReadAll(f) require.NoError(t, err) return bb } @@ -701,10 +700,10 @@ func TestUploadFiles(t *testing.T) { data, _, err := get(ri.Id) require.NoError(t, err) - expected, err := ioutil.ReadFile(filepath.Join(testDir, name)) + expected, err := os.ReadFile(filepath.Join(testDir, name)) require.NoError(t, err) 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) defer tf.Close() _, err = io.Copy(tf, bytes.NewReader(data)) diff --git a/api4/group.go b/api4/group.go index fa7dd38e0c..e249637a81 100644 --- a/api4/group.go +++ b/api4/group.go @@ -6,7 +6,7 @@ package api4 import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "strconv" "strings" @@ -293,7 +293,7 @@ func linkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { } syncableType := c.Params.SyncableType - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.createGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest) return @@ -464,7 +464,7 @@ func patchGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { } syncableType := c.Params.SyncableType - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.io_error", nil, err.Error(), http.StatusBadRequest) 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 // will have a blank 'Where' field, which should be subsequently set by the caller, for example: // -// err := licensedAndConfiguredForGroupBySource(c.App, group.Source) -// err.Where = "Api4.getGroup" +// err := licensedAndConfiguredForGroupBySource(c.App, group.Source) +// err.Where = "Api4.getGroup" // // Temporarily, this function also checks for the CustomGroups feature flag. func licensedAndConfiguredForGroupBySource(app app.AppIface, source model.GroupSource) *model.AppError { diff --git a/api4/image_test.go b/api4/image_test.go index aead2b5bf0..4c552e7d86 100644 --- a/api4/image_test.go +++ b/api4/image_test.go @@ -4,7 +4,7 @@ package api4 import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -89,7 +89,7 @@ func TestGetImage(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, "success", string(respBody)) diff --git a/api4/integration_action_test.go b/api4/integration_action_test.go index 975e90ee90..92b4f2ccbe 100644 --- a/api4/integration_action_test.go +++ b/api4/integration_action_test.go @@ -5,7 +5,7 @@ package api4 import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -21,7 +21,7 @@ type testHandler struct { } 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.NotEmpty(th.t, string(bb)) var poir model.PostActionIntegrationRequest diff --git a/api4/license.go b/api4/license.go index 4e308a1a45..ee7a79fa54 100644 --- a/api4/license.go +++ b/api4/license.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "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"` } - b, readErr := ioutil.ReadAll(r.Body) + b, readErr := io.ReadAll(r.Body) if readErr != nil { c.Err = model.NewAppError("requestTrialLicense", "api.license.request-trial.bad-request", nil, "", http.StatusBadRequest) return diff --git a/api4/plugin_test.go b/api4/plugin_test.go index a6382ce32a..da5f145412 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -8,7 +8,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -44,7 +44,7 @@ func TestPlugin(t *testing.T) { }) 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) // Install from URL @@ -295,7 +295,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) { }) 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) testCluster.ClearMessages() @@ -378,7 +378,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) { func TestDisableOnRemove(t *testing.T) { 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) testCases := []struct { @@ -723,7 +723,7 @@ func TestGetInstalledMarketplacePlugins(t *testing.T) { } 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) 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)) 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.True(t, svg.Is(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") - tarData, err := ioutil.ReadFile(filepath.Join(path, "testplugin.tar.gz")) + tarData, err := os.ReadFile(filepath.Join(path, "testplugin.tar.gz")) 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) - testIcon, err := ioutil.ReadFile(filepath.Join(path, "test.svg")) + testIcon, err := os.ReadFile(filepath.Join(path, "test.svg")) require.NoError(t, err) require.True(t, svg.Is(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 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) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) @@ -1050,13 +1050,13 @@ func TestGetLocalPluginInMarketplace(t *testing.T) { // Upload one local plugin 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) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) 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.True(t, svg.Is(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 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) manifest, _, err := th.SystemAdminClient.UploadPlugin(bytes.NewReader(tarData)) 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.True(t, svg.Is(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" signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename)) require.NoError(t, err) - sigFile, err := ioutil.ReadAll(signatureFileReader) + sigFile, err := io.ReadAll(signatureFileReader) require.NoError(t, err) 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) pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(http.StatusOK) @@ -1622,7 +1622,7 @@ func TestInstallMarketplacePlugin(t *testing.T) { th2.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { pluginSignatureFile, err := os.Open(filepath.Join(path, "testplugin.tar.gz.asc")) require.NoError(t, err) - pluginSignatureData, err := ioutil.ReadAll(pluginSignatureFile) + pluginSignatureData, err := io.ReadAll(pluginSignatureFile) require.NoError(t, err) key, err := os.Open(filepath.Join(path, "development-private-key.asc")) diff --git a/api4/saml.go b/api4/saml.go index f102870be6..893e34f797 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -5,7 +5,7 @@ package api4 import ( "encoding/json" - "io/ioutil" + "io" "mime" "mime/multipart" "net/http" @@ -139,7 +139,7 @@ func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("type", d) if d == "application/x-pem-file" { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { c.Err = model.NewAppError("addSamlIdpCertificate", "api.admin.saml.set_certificate_from_metadata.invalid_body.app_error", nil, err.Error(), http.StatusBadRequest) return diff --git a/api4/system_test.go b/api4/system_test.go index 13eced3f1f..56373ce581 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -8,7 +8,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -64,7 +64,7 @@ func TestGetPing(t *testing.T) { resp, err := client.DoAPIGet("/system/ping", "") require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) - respBytes, err := ioutil.ReadAll(resp.Body) + respBytes, err := io.ReadAll(resp.Body) require.NoError(t, err) respString := string(respBytes) require.NotContains(t, respString, "TestFeatureFlag") @@ -77,7 +77,7 @@ func TestGetPing(t *testing.T) { resp, err = client.DoAPIGet("/system/ping", "") require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) - respBytes, err = ioutil.ReadAll(resp.Body) + respBytes, err = io.ReadAll(resp.Body) require.NoError(t, err) respString = string(respBytes) require.Contains(t, respString, "testvalue") @@ -130,7 +130,7 @@ func TestEmailTest(t *testing.T) { defer th.TearDown() client := th.Client - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -817,7 +817,7 @@ func TestPushNotificationAck(t *testing.T) { resp := httptest.NewRecorder() req := httptest.NewRequest("POST", "/api/v4/notifications/ack", nil) 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) assert.Equal(t, http.StatusForbidden, resp.Code) @@ -833,11 +833,11 @@ func TestCompleteOnboarding(t *testing.T) { signatureFilename := "testplugin2.tar.gz.sig" signatureFileReader, err := os.Open(filepath.Join(path, signatureFilename)) require.NoError(t, err) - sigFile, err := ioutil.ReadAll(signatureFileReader) + sigFile, err := io.ReadAll(signatureFileReader) require.NoError(t, err) 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) pluginServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(http.StatusOK) diff --git a/app/admin.go b/app/admin.go index 8b901b1b5d..7abca6951c 100644 --- a/app/admin.go +++ b/app/admin.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "os" "runtime/debug" @@ -261,7 +260,7 @@ func (a *App) GetLatestVersion(latestVersionUrl string) (*model.GithubReleaseInf defer res.Body.Close() - responseData, err := ioutil.ReadAll(res.Body) + responseData, err := io.ReadAll(res.Body) if err != nil { return nil, model.NewAppError("GetLatestVersion", "app.admin.latest_version_read_all.failure", nil, "", http.StatusInternalServerError) } diff --git a/app/authorization_test.go b/app/authorization_test.go index c115fa8e64..9d3cc45264 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -7,7 +7,7 @@ import ( "context" "encoding/csv" "fmt" - "io/ioutil" + "io" "os" "strconv" "strings" @@ -133,7 +133,7 @@ func TestSessionHasPermissionToGroup(t *testing.T) { require.NoError(t, e) defer file.Close() - b, e := ioutil.ReadAll(file) + b, e := io.ReadAll(file) require.NoError(t, e) r := csv.NewReader(strings.NewReader(string(b))) diff --git a/app/command.go b/app/command.go index 7d4ac80551..31a3c01554 100644 --- a/app/command.go +++ b/app/command.go @@ -7,7 +7,6 @@ import ( "context" "errors" "io" - "io/ioutil" "net/http" "net/url" "regexp" @@ -521,7 +520,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command if resp.StatusCode != http.StatusOK { // 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) } diff --git a/app/compliance.go b/app/compliance.go index a79ff37d31..0a398c6693 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -5,8 +5,8 @@ package app import ( "errors" - "io/ioutil" "net/http" + "os" "github.com/mattermost/mattermost-server/v6/model" "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) { - 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 { return nil, model.NewAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error(), http.StatusNotImplemented) } diff --git a/app/download.go b/app/download.go index d83299d483..449f787c46 100644 --- a/app/download.go +++ b/app/download.go @@ -5,7 +5,6 @@ package app import ( "io" - "io/ioutil" "net/http" "net/url" "time" @@ -64,5 +63,5 @@ func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) { defer resp.Body.Close() - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } diff --git a/app/email/helper_test.go b/app/email/helper_test.go index 2aabf04a3e..75fa7605b1 100644 --- a/app/email/helper_test.go +++ b/app/email/helper_test.go @@ -5,7 +5,6 @@ package email import ( "bytes" - "io/ioutil" "os" "path/filepath" "testing" @@ -64,7 +63,7 @@ func SetupWithStoreMock(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 { panic(err) } diff --git a/app/export_test.go b/app/export_test.go index e9231a3af4..3ed17d9547 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -6,7 +6,6 @@ package app import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -590,7 +589,7 @@ func TestBulkExport(t *testing.T) { th := Setup(t) testsDir, _ := fileutils.FindDir("tests") - dir, err := ioutil.TempDir("", "import_test") + dir, err := os.MkdirTemp("", "import_test") require.NoError(t, err) defer os.RemoveAll(dir) diff --git a/app/extract_plugin_tar_test.go b/app/extract_plugin_tar_test.go index 3cacff7272..f1662fafa0 100644 --- a/app/extract_plugin_tar_test.go +++ b/app/extract_plugin_tar_test.go @@ -8,7 +8,6 @@ import ( "bytes" "compress/gzip" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -81,7 +80,7 @@ func TestExtractTarGz(t *testing.T) { }) } - dst, err := ioutil.TempDir("", "TestExtractTarGz") + dst, err := os.MkdirTemp("", "TestExtractTarGz") require.NoError(t, err) defer os.RemoveAll(dst) @@ -175,7 +174,7 @@ func TestExtractTarGz(t *testing.T) { for i, testCase := range testCases { 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) defer os.RemoveAll(dst) diff --git a/app/helper_test.go b/app/helper_test.go index 3cbaa72497..5b15d3f519 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -5,7 +5,6 @@ package app import ( "context" - "io/ioutil" "os" "path/filepath" "strings" @@ -48,7 +47,7 @@ type TestHelper struct { } 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 { panic(err) } diff --git a/app/imaging/utils_test.go b/app/imaging/utils_test.go index cdd81db44d..6d0c5383ae 100644 --- a/app/imaging/utils_test.go +++ b/app/imaging/utils_test.go @@ -6,7 +6,6 @@ package imaging import ( "bytes" "image/color" - "io/ioutil" "os" "testing" @@ -77,7 +76,7 @@ func TestFillImageTransparency(t *testing.T) { require.NotNil(t, inputImg) require.Equal(t, "png", format) - expectedBytes, err := ioutil.ReadFile(imgDir + "/" + tc.outputName) + expectedBytes, err := os.ReadFile(imgDir + "/" + tc.outputName) require.NoError(t, err) FillImageTransparency(inputImg, tc.fillColor) diff --git a/app/import_functions.go b/app/import_functions.go index 44f89737a5..f84af9e500 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "os" "path" @@ -1217,7 +1216,7 @@ func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, p timestamp := utils.TimeFromMillis(post.CreateAt) - fileData, err := ioutil.ReadAll(file) + fileData, err := io.ReadAll(file) if err != nil { return nil, model.NewAppError("BulkImport", "app.import.attachment.read_file_data.error", map[string]any{"FilePath": *data.Path}, "", http.StatusBadRequest) } diff --git a/app/import_functions_test.go b/app/import_functions_test.go index a6e47edddc..8ac8ff6e69 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -6,7 +6,6 @@ package app import ( "archive/zip" "context" - "io/ioutil" "os" "path/filepath" "strings" @@ -4378,11 +4377,11 @@ func TestImportDirectPostWithAttachments(t *testing.T) { testImage := filepath.Join(testsDir, "test.png") testImage2 := filepath.Join(testsDir, "test.svg") // 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") - fakeFileData, _ := ioutil.ReadFile(testImage) + fakeFileData, _ := os.ReadFile(testImage) fakeFileData[0] = 0 - _ = ioutil.WriteFile(testImageFake, fakeFileData, 0644) + _ = os.WriteFile(testImageFake, fakeFileData, 0644) defer os.RemoveAll(tmpFolder) // Create a user. diff --git a/app/import_test.go b/app/import_test.go index 3286f3f03a..f3676b6e10 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -6,7 +6,6 @@ package app import ( "archive/zip" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -439,7 +438,7 @@ func BenchmarkBulkImport(b *testing.B) { info, err := importFile.Stat() require.NoError(b, err) - dir, err := ioutil.TempDir("", "testimport") + dir, err := os.MkdirTemp("", "testimport") require.NoError(b, err) defer os.RemoveAll(dir) diff --git a/app/integration_action.go b/app/integration_action.go index 6f3d703808..dfc85cfbdc 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -23,7 +23,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -253,7 +253,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI defer resp.Body.Close() var response model.PostActionIntegrationResponse - respBytes, err := ioutil.ReadAll(resp.Body) + respBytes, err := io.ReadAll(resp.Body) if err != nil { 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, ProtoMinor: 1, Header: w.headers, - Body: ioutil.NopCloser(bytes.NewReader(w.data)), + Body: io.NopCloser(bytes.NewReader(w.data)), } if resp.StatusCode == 0 { resp.StatusCode = http.StatusOK diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 6dde72a2be..8fa6debe5d 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -6,7 +6,7 @@ package app import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -1079,47 +1079,47 @@ func TestDoPluginRequest(t *testing.T) { resp, err := th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", nil, nil) assert.Nil(t, err) 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)) resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz", nil, nil) assert.Nil(t, err) 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)) resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", url.Values{"abc": []string{"xyz"}, "multiple": []string{"1 first", "2 second", "3 third"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) - body, _ = ioutil.ReadAll(resp.Body) + body, _ = io.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first", url.Values{"multiple": []string{"2 second", "3 third"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) - body, _ = ioutil.ReadAll(resp.Body) + body, _ = io.ReadAll(resp.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", url.Values{"multiple": []string{"2 second"}}, nil) assert.Nil(t, err) require.NotNil(t, resp) - body, _ = ioutil.ReadAll(resp.Body) + body, _ = io.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) 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) assert.Nil(t, err) require.NotNil(t, resp) - body, _ = ioutil.ReadAll(resp.Body) + body, _ = io.ReadAll(resp.Body) assert.Equal(t, "OK", string(body)) 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) assert.Nil(t, err) require.NotNil(t, resp) - body, _ = ioutil.ReadAll(resp.Body) + body, _ = io.ReadAll(resp.Body) assert.Equal(t, "param multiple not correct", string(body)) } diff --git a/app/layer_generators/main.go b/app/layer_generators/main.go index 4fe3586f06..1a15ff4318 100644 --- a/app/layer_generators/main.go +++ b/app/layer_generators/main.go @@ -10,7 +10,7 @@ import ( "go/ast" "go/parser" "go/token" - "io/ioutil" + "io" "log" "os" "path" @@ -58,7 +58,7 @@ func main() { log.Fatal(err) } - err = ioutil.WriteFile(outputFile, formattedCode, 0644) + err = os.WriteFile(outputFile, formattedCode, 0644) if err != nil { log.Fatal(err) } @@ -162,7 +162,7 @@ func extractStoreMetadata() (*storeMetadata, error) { if err != nil { 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 { return nil, err } diff --git a/app/ldap.go b/app/ldap.go index 40399f50f4..a782b4715c 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -4,7 +4,7 @@ package app import ( - "io/ioutil" + "io" "mime/multipart" "net/http" @@ -186,7 +186,7 @@ func (a *App) writeLdapFile(filename string, fileData *multipart.FileHeader) *mo } defer file.Close() - data, err := ioutil.ReadAll(file) + data, err := io.ReadAll(file) if err != nil { return model.NewAppError("AddLdapCertificate", "api.admin.add_certificate.saving.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/oauth.go b/app/oauth.go index 104fe654c6..8dd67ffdcb 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -891,7 +890,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service defer resp.Body.Close() // 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) mlog.Error("Error getting OAuth user", mlog.Int("response", resp.StatusCode), mlog.String("body_string", bodyString)) diff --git a/app/oauth_test.go b/app/oauth_test.go index 1d7807fa3b..57a394a710 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -7,7 +7,7 @@ import ( "encoding/base64" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -517,7 +517,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { body, receivedTeamId, receivedStateProps, _, err := th.App.AuthorizeOAuthUser(&recorder, request, model.ServiceGitlab, "", state, "") require.NotNil(t, body) - bodyBytes, bodyErr := ioutil.ReadAll(body) + bodyBytes, bodyErr := io.ReadAll(body) require.NoError(t, bodyErr) assert.Equal(t, userData, string(bodyBytes)) diff --git a/app/plugin.go b/app/plugin.go index 38be469d17..2775eb0d86 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -7,7 +7,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -39,7 +38,7 @@ type pluginSignaturePath struct { signaturePath string } -//Ensure routerService implements `product.RouterService` +// Ensure routerService implements `product.RouterService` var _ product.RouterService = (*routerService)(nil) type routerService struct { @@ -976,7 +975,7 @@ func (ch *Channels) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (* } defer fileReader.Close() - tmpDir, err := ioutil.TempDir("", "plugintmp") + tmpDir, err := os.MkdirTemp("", "plugintmp") if err != nil { 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 { 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 { 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) { - icon, err := ioutil.ReadFile(iconPath) + icon, err := os.ReadFile(iconPath) if err != nil { return "", errors.Wrapf(err, "failed to open icon at path %s", iconPath) } diff --git a/app/plugin_api.go b/app/plugin_api.go index d42d08613d..f2afc5e7ce 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "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) } - fileBuffer, err := ioutil.ReadAll(file) + fileBuffer, err := io.ReadAll(file) if err != nil { 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 { return &http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewBufferString("Not enough URL. Form of URL should be //*")), + Body: io.NopCloser(bytes.NewBufferString("Not enough URL. Form of URL should be //*")), } } destinationPluginId := split[1] @@ -1043,7 +1042,7 @@ func (api *PluginAPI) PluginHTTP(request *http.Request) *http.Response { } return &http.Response{ StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewBufferString(message)), + Body: io.NopCloser(bytes.NewBufferString(message)), } } responseTransfer := &PluginResponseWriter{} diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index 6bb40a78cd..541d0f3a18 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -11,7 +11,7 @@ import ( "image" "image/color" "image/png" - "io/ioutil" + "io" "net/http" "net/http/httptest" "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 { - pluginDir, err := ioutil.TempDir("", "") + pluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) t.Cleanup(func() { 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) t.Cleanup(func() { err = os.RemoveAll(webappPluginDir) @@ -106,7 +106,7 @@ func setupMultiPluginAPITest(t *testing.T, pluginCodes []string, pluginManifests 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) require.NoError(t, reterr) 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) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) @@ -857,7 +857,7 @@ func TestPluginAPIGetPlugins(t *testing.T) { backend := filepath.Join(pluginDir, pluginID, "backend.exe") 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) require.NoError(t, reterr) @@ -884,7 +884,7 @@ func TestPluginAPIInstallPlugin(t *testing.T) { api := th.SetupPluginAPI() 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) _, 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 // 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) { - pluginDir, err := ioutil.TempDir("", "") + pluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) app.UpdateConfig(func(cfg *model.Config) { @@ -944,7 +944,7 @@ func TestInstallPlugin(t *testing.T) { backend := filepath.Join(pluginDir, pluginID, "backend.exe") 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) require.NoError(t, reterr) 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 { - data, err := ioutil.ReadFile(fileName) + data, err := os.ReadFile(fileName) if err != nil { return err } @@ -1161,7 +1161,7 @@ func TestBasicAPIPlugins(t *testing.T) { defaultSchema := getDefaultPluginSettingsSchema() testFolder, found := fileutils.FindDir("mattermost-server/app/plugin_api_tests") 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) for _, dir := range dirs { d := dir.Name() @@ -1523,7 +1523,7 @@ func TestInterpluginPluginHTTP(t *testing.T) { "github.com/mattermost/mattermost-server/v6/model" "bytes" "net/http" - "io/ioutil" + "io" ) type MyPlugin struct { @@ -1545,7 +1545,7 @@ func TestInterpluginPluginHTTP(t *testing.T) { if resp.Body == nil { return nil, "Nil body" } - respbody, err := ioutil.ReadAll(resp.Body) + respbody, err := io.ReadAll(resp.Body) if err != nil { return nil, err.Error() } @@ -1605,9 +1605,9 @@ func TestAPIMetrics(t *testing.T) { t.Run("", func(t *testing.T) { metricsMock := &mocks.MetricsInterface{} - pluginDir, err := ioutil.TempDir("", "") + pluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) @@ -1642,7 +1642,7 @@ func TestAPIMetrics(t *testing.T) { } ` 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 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") 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.NotEmpty(t, pluginCode) @@ -1752,7 +1752,7 @@ func TestPluginHTTPConnHijack(t *testing.T) { defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "OK", string(body)) } @@ -1765,7 +1765,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) { require.True(t, found, "Cannot find tests folder") 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.NotEmpty(t, pluginCode) diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index e4eaa4d23e..b6e26b562f 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -7,7 +7,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -29,9 +28,9 @@ import ( ) 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) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) 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") 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) pluginIDs = append(pluginIDs, pluginID) activationErrors = append(activationErrors, activationErr) @@ -1024,9 +1023,9 @@ func TestHookMetrics(t *testing.T) { t.Run("", func(t *testing.T) { metricsMock := &mocks.MetricsInterface{} - pluginDir, err := ioutil.TempDir("", "") + pluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) @@ -1069,7 +1068,7 @@ func TestHookMetrics(t *testing.T) { } ` 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 metricsMock.On("ObservePluginHookDuration", pluginID, "Implemented", true, mock.Anything).Return() diff --git a/app/plugin_install.go b/app/plugin_install.go index 73d6a9e20f..12eb1f3046 100644 --- a/app/plugin_install.go +++ b/app/plugin_install.go @@ -33,14 +33,12 @@ // 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 // plugin is newer. Managed plugins unconditionally override unmanaged plugins with the same plugin id. -// package app import ( "bytes" "fmt" "io" - "io/ioutil" "net/http" "os" "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 { 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) } - dir, err := ioutil.ReadDir(extractDir) + dir, err := os.ReadDir(extractDir) if err != nil { return nil, "", model.NewAppError("extractPlugin", "app.plugin.filesystem.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/plugin_requests.go b/app/plugin_requests.go index 17301c54ce..5e75a10457 100644 --- a/app/plugin_requests.go +++ b/app/plugin_requests.go @@ -6,7 +6,7 @@ package app import ( "bytes" "fmt" - "io/ioutil" + "io" "net/http" "path" "path/filepath" @@ -157,11 +157,11 @@ func (ch *Channels) servePluginRequest(w http.ResponseWriter, r *http.Request, h sentToken := "" if r.Header.Get(model.HeaderCsrfToken) == "" { - bodyBytes, _ := ioutil.ReadAll(r.Body) - r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) + bodyBytes, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) r.ParseForm() sentToken = r.FormValue("csrf") - r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) + r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) } else { sentToken = r.Header.Get(model.HeaderCsrfToken) } diff --git a/app/plugin_signature.go b/app/plugin_signature.go index 9724080aed..bedb6946a1 100644 --- a/app/plugin_signature.go +++ b/app/plugin_signature.go @@ -6,7 +6,6 @@ package app import ( "bytes" "io" - "io/ioutil" "net/http" "path/filepath" @@ -37,7 +36,7 @@ func (a *App) AddPublicKey(name string, key io.Reader) *model.AppError { if isSamlFile(&a.Config().SamlSettings, name) { 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 { 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) { - readBytes, err := ioutil.ReadAll(reader) + readBytes, err := io.ReadAll(reader) if err != nil { return nil, errors.Wrap(err, "can't read the file") } diff --git a/app/plugin_signature_test.go b/app/plugin_signature_test.go index f1b0d31d1d..20e50bc414 100644 --- a/app/plugin_signature_test.go +++ b/app/plugin_signature_test.go @@ -4,7 +4,6 @@ package app import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -38,7 +37,7 @@ func TestPluginPublicKeys(t *testing.T) { path, _ := fileutils.FindDir("tests") 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) fileReader, err := os.Open(filepath.Join(path, publicKeyFilename)) require.NoError(t, err) diff --git a/app/plugin_test.go b/app/plugin_test.go index d5b21aefe5..47f7a2a86a 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -9,7 +9,7 @@ import ( "encoding/base64" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -384,7 +384,7 @@ func TestPrivateServePluginRequest(t *testing.T) { handler := func(context *plugin.Context, w http.ResponseWriter, r *http.Request) { assert.Equal(t, testCase.ExpectedURL, r.URL.Path) - body, _ := ioutil.ReadAll(r.Body) + body, _ := io.ReadAll(r.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) { // Install the plugin and enable - pluginBytes, err := ioutil.ReadFile(testPluginPath) + pluginBytes, err := os.ReadFile(testPluginPath) require.NoError(t, err) require.NotNil(t, pluginBytes) @@ -935,7 +935,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) { require.NoError(t, err) // Install first plugin and enable - pluginBytes, err := ioutil.ReadFile(testPluginPath) + pluginBytes, err := os.ReadFile(testPluginPath) require.NoError(t, err) require.NotNil(t, pluginBytes) diff --git a/app/response_transfer.go b/app/response_transfer.go index 624d940a3f..e3acf3b527 100644 --- a/app/response_transfer.go +++ b/app/response_transfer.go @@ -6,7 +6,7 @@ package app import ( "bytes" "fmt" - "io/ioutil" + "io" "net/http" "strconv" "strings" @@ -59,7 +59,7 @@ func (rt *PluginResponseWriter) GenerateResponse() *http.Response { res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode)) if rt.Len() > 0 { - res.Body = ioutil.NopCloser(rt) + res.Body = io.NopCloser(rt) } else { res.Body = http.NoBody } diff --git a/app/role_test.go b/app/role_test.go index 2e10c0d3c0..1bf9420ae4 100644 --- a/app/role_test.go +++ b/app/role_test.go @@ -6,7 +6,7 @@ package app import ( "context" "encoding/csv" - "io/ioutil" + "io" "os" "strconv" "strings" @@ -130,7 +130,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th require.NoError(t, e) defer file.Close() - b, e := ioutil.ReadAll(file) + b, e := io.ReadAll(file) require.NoError(t, e) r := csv.NewReader(strings.NewReader(string(b))) diff --git a/app/saml.go b/app/saml.go index 260d601cee..b0b83ba159 100644 --- a/app/saml.go +++ b/app/saml.go @@ -8,7 +8,7 @@ import ( "encoding/pem" "encoding/xml" "fmt" - "io/ioutil" + "io" "mime/multipart" "net/http" "strings" @@ -42,7 +42,7 @@ func (a *App) writeSamlFile(filename string, fileData *multipart.FileHeader) *mo } defer file.Close() - data, err := ioutil.ReadAll(file) + data, err := io.ReadAll(file) if err != nil { 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() - bodyXML, err := ioutil.ReadAll(resp.Body) + bodyXML, err := io.ReadAll(resp.Body) if err != nil { return nil, model.NewAppError("FetchSamlMetadataFromIdp", "app.admin.saml.failure_read_response_body_from_idp.app_error", nil, err.Error(), http.StatusInternalServerError) } diff --git a/app/security_update_check.go b/app/security_update_check.go index 273f520e23..cf8d9cc2c5 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -5,7 +5,7 @@ package app import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/url" "runtime" @@ -110,7 +110,7 @@ func (s *Server) DoSecurityUpdateCheck() { return } - body, err := ioutil.ReadAll(resBody.Body) + body, err := io.ReadAll(resBody.Body) resBody.Body.Close() if err != nil || resBody.StatusCode != 200 { mlog.Error("Failed to read security bulletin details") diff --git a/app/slashcommands/helper_test.go b/app/slashcommands/helper_test.go index c7fa8fcf3a..ff145921c7 100644 --- a/app/slashcommands/helper_test.go +++ b/app/slashcommands/helper_test.go @@ -6,7 +6,6 @@ package slashcommands import ( "bytes" "context" - "io/ioutil" "os" "path/filepath" "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 { - tempWorkspace, err := ioutil.TempDir("", "apptest") + tempWorkspace, err := os.MkdirTemp("", "apptest") if err != nil { panic(err) } diff --git a/app/support_packet.go b/app/support_packet.go index ea1a6b73ce..9b91471f02 100644 --- a/app/support_packet.go +++ b/app/support_packet.go @@ -6,7 +6,7 @@ package app import ( "encoding/json" "fmt" - "io/ioutil" + "os" "runtime" "strings" @@ -145,7 +145,7 @@ func (a *App) getNotificationsLog() (*model.FileData, string) { // notifications.log notificationsLog := config.GetNotificationsLogFileLocation(*a.Config().LogSettings.FileLocation) - notificationsLogFileData, notificationsLogFileDataErr := ioutil.ReadFile(notificationsLog) + notificationsLogFileData, notificationsLogFileDataErr := os.ReadFile(notificationsLog) if notificationsLogFileDataErr == nil { fileData := model.FileData{ @@ -155,7 +155,7 @@ func (a *App) getNotificationsLog() (*model.FileData, string) { return &fileData, "" } - warning = fmt.Sprintf("ioutil.ReadFile(notificationsLog) Error: %s", notificationsLogFileDataErr.Error()) + warning = fmt.Sprintf("os.ReadFile(notificationsLog) Error: %s", notificationsLogFileDataErr.Error()) } else { 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 mattermostLog := config.GetLogFileLocation(*a.Config().LogSettings.FileLocation) - mattermostLogFileData, mattermostLogFileDataErr := ioutil.ReadFile(mattermostLog) + mattermostLogFileData, mattermostLogFileDataErr := os.ReadFile(mattermostLog) if mattermostLogFileDataErr == nil { fileData := model.FileData{ @@ -181,7 +181,7 @@ func (a *App) getMattermostLog() (*model.FileData, string) { } return &fileData, "" } - warning = fmt.Sprintf("ioutil.ReadFile(mattermostLog) Error: %s", mattermostLogFileDataErr.Error()) + warning = fmt.Sprintf("os.ReadFile(mattermostLog) Error: %s", mattermostLogFileDataErr.Error()) } else { warning = "Unable to retrieve mattermost.log because LogSettings: EnableFile is false in config.json" diff --git a/app/support_packet_test.go b/app/support_packet_test.go index 05e7d0418a..9ac966c0fa 100644 --- a/app/support_packet_test.go +++ b/app/support_packet_test.go @@ -4,7 +4,6 @@ package app import ( - "io/ioutil" "os" "testing" @@ -61,9 +60,9 @@ func TestGenerateSupportPacket(t *testing.T) { defer th.TearDown() d1 := []byte("hello\ngo\n") - err := ioutil.WriteFile("mattermost.log", d1, 0777) + err := os.WriteFile("mattermost.log", d1, 0777) require.NoError(t, err) - err = ioutil.WriteFile("notifications.log", d1, 0777) + err = os.WriteFile("notifications.log", d1, 0777) require.NoError(t, err) fileDatas := th.App.GenerateSupportPacket() @@ -111,11 +110,11 @@ func TestGetNotificationsLog(t *testing.T) { fileData, warning = th.App.getNotificationsLog() 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 d1 := []byte("hello\ngo\n") - err := ioutil.WriteFile("notifications.log", d1, 0777) + err := os.WriteFile("notifications.log", d1, 0777) defer os.Remove("notifications.log") require.NoError(t, err) @@ -149,11 +148,11 @@ func TestGetMattermostLog(t *testing.T) { fileData, warning = th.App.getMattermostLog() 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 d1 := []byte("hello\ngo\n") - err := ioutil.WriteFile("mattermost.log", d1, 0777) + err := os.WriteFile("mattermost.log", d1, 0777) defer os.Remove("mattermost.log") require.NoError(t, err) diff --git a/app/teams/helper_test.go b/app/teams/helper_test.go index 4aa6987bce..176a63e9e2 100644 --- a/app/teams/helper_test.go +++ b/app/teams/helper_test.go @@ -5,7 +5,6 @@ package teams import ( "bytes" - "io/ioutil" "os" "path/filepath" "testing" @@ -43,7 +42,7 @@ func Setup(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 { panic(err) } diff --git a/app/upload_test.go b/app/upload_test.go index 447914fa25..128f157912 100644 --- a/app/upload_test.go +++ b/app/upload_test.go @@ -6,8 +6,8 @@ package app import ( "bytes" "io" - "io/ioutil" "math/rand" + "os" "path/filepath" "sync" "sync/atomic" @@ -213,7 +213,7 @@ func TestUploadData(t *testing.T) { t.Run("image processing", func(t *testing.T) { 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.NotEmpty(t, data) diff --git a/app/users/helper_test.go b/app/users/helper_test.go index 8ddf4d97e5..44e55114b6 100644 --- a/app/users/helper_test.go +++ b/app/users/helper_test.go @@ -5,7 +5,6 @@ package users import ( "bytes" - "io/ioutil" "os" "path/filepath" "runtime" @@ -48,7 +47,7 @@ func Setup(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 { panic(err) } diff --git a/app/users/profile_picture.go b/app/users/profile_picture.go index c0260c5a5b..1858140e52 100644 --- a/app/users/profile_picture.go +++ b/app/users/profile_picture.go @@ -11,7 +11,7 @@ import ( "image/draw" "image/png" "io" - "io/ioutil" + "os" "path" "path/filepath" "strings" @@ -174,7 +174,7 @@ func getFont(initialFont string) (*truetype.Font, error) { } fontDir, _ := fileutils.FindDir("fonts") - fontBytes, err := ioutil.ReadFile(filepath.Join(fontDir, initialFont)) + fontBytes, err := os.ReadFile(filepath.Join(fontDir, initialFont)) if err != nil { return nil, err } diff --git a/app/webhub_fuzz.go b/app/webhub_fuzz.go index 5f39d8952d..a305b3cfc0 100644 --- a/app/webhub_fuzz.go +++ b/app/webhub_fuzz.go @@ -6,7 +6,6 @@ package app import ( - "io/ioutil" "math/rand" "net" "net/http" @@ -273,7 +272,7 @@ func generateInitialCorpus() error { if err != nil { 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 { return err } diff --git a/audit/audit_test.go b/audit/audit_test.go index cc3ce3d676..f6055c8166 100644 --- a/audit/audit_test.go +++ b/audit/audit_test.go @@ -6,7 +6,6 @@ package audit import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -72,7 +71,7 @@ func TestAudit_LogRecord(t *testing.T) { for _, testCase := range testCases { 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) defer os.Remove(tempDir) @@ -92,7 +91,7 @@ func TestAudit_LogRecord(t *testing.T) { err = logger.Shutdown() require.NoError(t, err) - logs, err := ioutil.ReadFile(filePath) + logs, err := os.ReadFile(filePath) require.NoError(t, err) actual := strings.TrimSpace(string(logs)) diff --git a/cmd/mattermost/commands/cmdtestlib.go b/cmd/mattermost/commands/cmdtestlib.go index f79fdf9340..34a572d6b1 100644 --- a/cmd/mattermost/commands/cmdtestlib.go +++ b/cmd/mattermost/commands/cmdtestlib.go @@ -9,7 +9,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -127,7 +126,7 @@ func (h *testHelper) SetConfig(config *model.Config) { if err != nil { 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()) } } diff --git a/cmd/mattermost/commands/server_test.go b/cmd/mattermost/commands/server_test.go index 8d94a4de17..5a7d9aa8f3 100644 --- a/cmd/mattermost/commands/server_test.go +++ b/cmd/mattermost/commands/server_test.go @@ -4,7 +4,6 @@ package commands import ( - "io/ioutil" "net" "os" "syscall" @@ -77,7 +76,7 @@ func TestRunServerSystemdNotification(t *testing.T) { defer th.TearDownServerTest() // 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 { panic(err) } diff --git a/config/file.go b/config/file.go index cbf53cf73e..1455a4d99e 100644 --- a/config/file.go +++ b/config/file.go @@ -5,7 +5,7 @@ package config import ( "fmt" - "io/ioutil" + "io" "os" "path/filepath" @@ -111,7 +111,7 @@ func (fs *FileStore) persist(cfg *model.Config) error { return errors.Wrap(err, "failed to serialize") } - err = ioutil.WriteFile(fs.path, b, 0600) + err = os.WriteFile(fs.path, b, 0600) if err != nil { return errors.Wrap(err, "failed to write file") } @@ -130,7 +130,7 @@ func (fs *FileStore) Load() ([]byte, error) { } defer f.Close() - fileBytes, err := ioutil.ReadAll(f) + fileBytes, err := io.ReadAll(f) if err != nil { return nil, err } @@ -142,7 +142,7 @@ func (fs *FileStore) Load() ([]byte, error) { func (fs *FileStore) GetFile(name string) ([]byte, error) { resolvedPath := fs.resolveFilePath(name) - data, err := ioutil.ReadFile(resolvedPath) + data, err := os.ReadFile(resolvedPath) if err != nil { 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 { resolvedPath := fs.resolveFilePath(name) - err := ioutil.WriteFile(resolvedPath, data, 0600) + err := os.WriteFile(resolvedPath, data, 0600) if err != nil { return errors.Wrapf(err, "failed to write file to %s", resolvedPath) } diff --git a/config/file_test.go b/config/file_test.go index 0ae493b499..35bf30f474 100644 --- a/config/file_test.go +++ b/config/file_test.go @@ -5,7 +5,6 @@ package config import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "strings" @@ -24,7 +23,7 @@ func setupConfigFile(t *testing.T, cfg *model.Config) (string, func()) { os.Clearenv() t.Helper() - tempDir, err := ioutil.TempDir("", "setupConfigFile") + tempDir, err := os.MkdirTemp("", "setupConfigFile") require.NoError(t, err) err = os.Chdir(tempDir) @@ -32,13 +31,13 @@ func setupConfigFile(t *testing.T, cfg *model.Config) (string, func()) { var name string if cfg != nil { - f, err := ioutil.TempFile(tempDir, "setupConfigFile") + f, err := os.CreateTemp(tempDir, "setupConfigFile") require.NoError(t, err) cfgData, err := marshalConfig(cfg) require.NoError(t, err) - ioutil.WriteFile(f.Name(), cfgData, 0644) + os.WriteFile(f.Name(), cfgData, 0644) name = f.Name() } @@ -165,7 +164,7 @@ func TestFileStoreNew(t *testing.T) { _, tearDown := setupConfigFile(t, nil) defer tearDown() - tempDir, err := ioutil.TempDir("", "TestFileStoreNew") + tempDir, err := os.MkdirTemp("", "TestFileStoreNew") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -184,7 +183,7 @@ func TestFileStoreNew(t *testing.T) { _, tearDown := setupConfigFile(t, nil) defer tearDown() - tempDir, err := ioutil.TempDir("", "TestFileStoreNew") + tempDir, err := os.MkdirTemp("", "TestFileStoreNew") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -203,7 +202,7 @@ func TestFileStoreNew(t *testing.T) { _, tearDown := setupConfigFile(t, nil) defer tearDown() - tempDir, err := ioutil.TempDir("", "TestFileStoreNew") + tempDir, err := os.MkdirTemp("", "TestFileStoreNew") require.NoError(t, err) defer os.RemoveAll(tempDir) @@ -225,7 +224,7 @@ func TestFileStoreNew(t *testing.T) { cfgData, err := marshalConfig(testConfig) require.NoError(t, err) - ioutil.WriteFile(path, cfgData, 0644) + os.WriteFile(path, cfgData, 0644) fs, err := NewFileStore(path, false) require.NoError(t, err) @@ -815,7 +814,7 @@ func TestFileStoreLoad(t *testing.T) { cfgData, err := marshalConfig(invalidConfig) require.NoError(t, err) - ioutil.WriteFile(path, cfgData, 0644) + os.WriteFile(path, cfgData, 0644) err = fs.Load() if assert.Error(t, err) { @@ -876,7 +875,7 @@ func TestFileStoreLoad(t *testing.T) { cfgData, err := marshalConfig(minimalConfig) require.NoError(t, err) - err = ioutil.WriteFile(path, cfgData, 0644) + err = os.WriteFile(path, cfgData, 0644) require.NoError(t, err) err = fs.Load() @@ -971,11 +970,11 @@ func TestFileGetFile(t *testing.T) { err := os.MkdirAll("config", 0700) require.NoError(t, err) - f, err := ioutil.TempFile("config", "empty-file") + f, err := os.CreateTemp("config", "empty-file") require.NoError(t, err) defer os.Remove(f.Name()) - err = ioutil.WriteFile(f.Name(), nil, 0777) + err = os.WriteFile(f.Name(), nil, 0777) require.NoError(t, err) data, err := fs.GetFile(f.Name()) @@ -987,11 +986,11 @@ func TestFileGetFile(t *testing.T) { err := os.MkdirAll("config", 0700) require.NoError(t, err) - f, err := ioutil.TempFile("config", "test-file") + f, err := os.CreateTemp("config", "test-file") require.NoError(t, err) 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) data, err := fs.GetFile(f.Name()) @@ -1102,11 +1101,11 @@ func TestFileHasFile(t *testing.T) { err = os.MkdirAll("config", 0700) require.NoError(t, err) - f, err := ioutil.TempFile("config", "test-file") + f, err := os.CreateTemp("config", "test-file") require.NoError(t, err) 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) has, err := fs.HasFile(f.Name()) @@ -1191,11 +1190,11 @@ func TestFileRemoveFile(t *testing.T) { err = os.MkdirAll("config", 0700) require.NoError(t, err) - f, err := ioutil.TempFile("config", "test-file") + f, err := os.CreateTemp("config", "test-file") require.NoError(t, err) 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) err = fs.RemoveFile(f.Name()) @@ -1314,7 +1313,7 @@ func TestFileStoreSetReadOnlyFF(t *testing.T) { func TestResolveConfigPath(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) info, err := cf.Stat() 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) { - tempDir, err := ioutil.TempDir("", "resolveconfig") + tempDir, err := os.MkdirTemp("", "resolveconfig") require.NoError(t, err) defer os.RemoveAll(tempDir) diff --git a/config/migrate_test.go b/config/migrate_test.go index 348f29bd5f..27a1b9ccda 100644 --- a/config/migrate_test.go +++ b/config/migrate_test.go @@ -4,7 +4,6 @@ package config import ( - "io/ioutil" "os" "path" "testing" @@ -39,7 +38,7 @@ func TestMigrate(t *testing.T) { os.Clearenv() t.Helper() - tempDir, err := ioutil.TempDir("", "TestMigrate") + tempDir, err := os.MkdirTemp("", "TestMigrate") require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(tempDir) diff --git a/config/store_test.go b/config/store_test.go index dc13329522..35a999f75e 100644 --- a/config/store_test.go +++ b/config/store_test.go @@ -4,7 +4,6 @@ package config import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -18,7 +17,7 @@ func TestNewStoreFromDSN(t *testing.T) { } sqlSettings := mainHelper.GetSQLSettings() - tempDir, err := ioutil.TempDir("", "TestNewStore") + tempDir, err := os.MkdirTemp("", "TestNewStore") require.NoError(t, err) err = os.Chdir(tempDir) @@ -46,7 +45,7 @@ func TestNewStoreReadOnly(t *testing.T) { } sqlSettings := mainHelper.GetSQLSettings() - tempDir, tErr := ioutil.TempDir("", "TestNewStore") + tempDir, tErr := os.MkdirTemp("", "TestNewStore") require.NoError(t, tErr) tErr = os.Chdir(tempDir) diff --git a/model/bundle_info_test.go b/model/bundle_info_test.go index e91ec0efb4..eb771baea6 100644 --- a/model/bundle_info_test.go +++ b/model/bundle_info_test.go @@ -4,7 +4,6 @@ package model import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -14,7 +13,7 @@ import ( ) func TestBundleInfoForPath(t *testing.T) { - dir, err := ioutil.TempDir("", "mm-plugin-test") + dir, err := os.MkdirTemp("", "mm-plugin-test") require.NoError(t, err) defer os.RemoveAll(dir) diff --git a/model/client4.go b/model/client4.go index 2ce96173ef..7225c94a1c 100644 --- a/model/client4.go +++ b/model/client4.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "mime/multipart" "net" "net/http" @@ -1010,7 +1009,7 @@ func (c *Client4) GetDefaultProfileImage(userId string) ([]byte, *Response, erro } defer closeBody(r) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) } - data, err := ioutil.ReadAll(rp.Body) + data, err := io.ReadAll(rp.Body) if err != nil { 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) } - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { 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) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) if err != nil { return nil, BuildResponse(r), NewAppError("GetFile", "model.client.read_job_result_file.app_error", nil, err.Error(), r.StatusCode) } diff --git a/model/command_response.go b/model/command_response.go index b2521f8e0f..381a0f0c3d 100644 --- a/model/command_response.go +++ b/model/command_response.go @@ -6,7 +6,6 @@ package model import ( "encoding/json" "io" - "io/ioutil" "strings" "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" { 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 nil, nil @@ -49,7 +48,7 @@ func CommandResponseFromPlainText(text string) *CommandResponse { } func CommandResponseFromJSON(data io.Reader) (*CommandResponse, error) { - b, err := ioutil.ReadAll(data) + b, err := io.ReadAll(data) if err != nil { return nil, err } diff --git a/model/file_info_test.go b/model/file_info_test.go index 9d060f34c1..e2552dd77c 100644 --- a/model/file_info_test.go +++ b/model/file_info_test.go @@ -8,7 +8,7 @@ import ( "encoding/base64" _ "image/gif" _ "image/png" - "io/ioutil" + "os" "strings" "testing" @@ -76,13 +76,13 @@ func TestFileInfoIsImage(t *testing.T) { func TestGetInfoForFile(t *testing.T) { 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") // base 64 encoded version of handtinywhite.gif from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever 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") var ttc = []struct { diff --git a/model/manifest.go b/model/manifest.go index 6b7ddbd84d..9b1551e921 100644 --- a/model/manifest.go +++ b/model/manifest.go @@ -6,7 +6,7 @@ package model import ( "encoding/json" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -108,42 +108,41 @@ type PluginSettingsSchema struct { // // Example plugin.json: // -// -// { -// "id": "com.mycompany.myplugin", -// "name": "My Plugin", -// "description": "This is my plugin", -// "homepage_url": "https://example.com", -// "support_url": "https://example.com/support", -// "release_notes_url": "https://example.com/releases/v0.0.1", -// "icon_path": "assets/logo.svg", -// "version": "0.1.0", -// "min_server_version": "5.6.0", -// "server": { -// "executables": { -// "linux-amd64": "server/dist/plugin-linux-amd64", -// "darwin-amd64": "server/dist/plugin-darwin-amd64", -// "windows-amd64": "server/dist/plugin-windows-amd64.exe" -// } -// }, -// "webapp": { -// "bundle_path": "webapp/dist/main.js" -// }, -// "settings_schema": { -// "header": "Some header text", -// "footer": "Some footer text", -// "settings": [{ -// "key": "someKey", -// "display_name": "Enable Extra Feature", -// "type": "bool", -// "help_text": "When true, an extra feature will be enabled!", -// "default": "false" -// }] -// }, -// "props": { -// "someKey": "someData" -// } -// } +// { +// "id": "com.mycompany.myplugin", +// "name": "My Plugin", +// "description": "This is my plugin", +// "homepage_url": "https://example.com", +// "support_url": "https://example.com/support", +// "release_notes_url": "https://example.com/releases/v0.0.1", +// "icon_path": "assets/logo.svg", +// "version": "0.1.0", +// "min_server_version": "5.6.0", +// "server": { +// "executables": { +// "linux-amd64": "server/dist/plugin-linux-amd64", +// "darwin-amd64": "server/dist/plugin-darwin-amd64", +// "windows-amd64": "server/dist/plugin-windows-amd64.exe" +// } +// }, +// "webapp": { +// "bundle_path": "webapp/dist/main.js" +// }, +// "settings_schema": { +// "header": "Some header text", +// "footer": "Some footer text", +// "settings": [{ +// "key": "someKey", +// "display_name": "Enable Extra Feature", +// "type": "bool", +// "help_text": "When true, an extra feature will be enabled!", +// "default": "false" +// }] +// }, +// "props": { +// "someKey": "someData" +// } +// } type Manifest struct { // 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-_\.]+$. @@ -426,7 +425,7 @@ func FindManifest(dir string) (manifest *Manifest, path string, err error) { } continue } - b, ioerr := ioutil.ReadAll(f) + b, ioerr := io.ReadAll(f) f.Close() if ioerr != nil { return nil, path, ioerr diff --git a/model/manifest_test.go b/model/manifest_test.go index ae816b340d..de93569b53 100644 --- a/model/manifest_test.go +++ b/model/manifest_test.go @@ -5,7 +5,6 @@ package model import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "strings" @@ -244,7 +243,7 @@ func TestFindManifest(t *testing.T) { {"plugin.yml", `id: FOO`, false, false}, {"plugin.yml", "bar", true, false}, } { - dir, err := ioutil.TempDir("", "mm-plugin-test") + dir, err := os.MkdirTemp("", "mm-plugin-test") require.NoError(t, err) defer os.RemoveAll(dir) @@ -396,7 +395,7 @@ settings_schema: func TestFindManifest_FileErrors(t *testing.T) { 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) defer os.RemoveAll(dir) @@ -417,7 +416,7 @@ func TestFindManifest_FolderPermission(t *testing.T) { } 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) defer os.RemoveAll(dir) diff --git a/model/post_test.go b/model/post_test.go index f6935c7ca6..3cbb785100 100644 --- a/model/post_test.go +++ b/model/post_test.go @@ -5,7 +5,7 @@ package model import ( "encoding/json" - "io/ioutil" + "os" "strings" "sync" "testing" @@ -369,13 +369,13 @@ func TestPost_AttachmentsEqual(t *testing.T) { var markdownSample, markdownSampleWithRewrittenImageURLs string func init() { - bytes, err := ioutil.ReadFile("testdata/markdown-sample.md") + bytes, err := os.ReadFile("testdata/markdown-sample.md") if err != nil { panic(err) } 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 { panic(err) } diff --git a/plugin/client_rpc.go b/plugin/client_rpc.go index 12c54b61ba..feea87005a 100644 --- a/plugin/client_rpc.go +++ b/plugin/client_rpc.go @@ -13,7 +13,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "net/rpc" @@ -444,7 +443,7 @@ func (s *hooksRPCServer) ServeHTTP(args *Z_ServeHTTPArgs, returns *struct{}) err } r.Body = connectIOReader(connection) } else { - r.Body = ioutil.NopCloser(&bytes.Buffer{}) + r.Body = io.NopCloser(&bytes.Buffer{}) } defer r.Body.Close() @@ -487,7 +486,7 @@ func (g *apiRPCClient) PluginHTTP(request *http.Request) *http.Response { } if request.Body != nil { - requestBody, err := ioutil.ReadAll(request.Body) + requestBody, err := io.ReadAll(request.Body) if err != nil { log.Printf("RPC call to PluginHTTP API failed: %s", err.Error()) return nil @@ -504,20 +503,20 @@ func (g *apiRPCClient) PluginHTTP(request *http.Request) *http.Response { return nil } - _returns.Response.Body = ioutil.NopCloser(bytes.NewBuffer(_returns.ResponseBody)) + _returns.Response.Body = io.NopCloser(bytes.NewBuffer(_returns.ResponseBody)) return _returns.Response } 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 { PluginHTTP(request *http.Request) *http.Response }); ok { response := hook.PluginHTTP(args.Request) - responseBody, err := ioutil.ReadAll(response.Body) + responseBody, err := io.ReadAll(response.Body) if err != nil { return encodableError(fmt.Errorf("RPC call to PluginHTTP API failed: %s", err.Error())) } diff --git a/plugin/environment.go b/plugin/environment.go index 6469c9352b..9226a2e878 100644 --- a/plugin/environment.go +++ b/plugin/environment.go @@ -6,7 +6,6 @@ package plugin import ( "fmt" "hash/fnv" - "io/ioutil" "os" "path/filepath" "sync" @@ -86,7 +85,7 @@ func NewEnvironment(newAPIImpl apiImplCreatorFunc, // // Plugins are found non-recursively and paths beginning with a dot are always ignored. func scanSearchPath(path string) ([]*model.BundleInfo, error) { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return nil, err } @@ -468,7 +467,7 @@ func (env *Environment) UnpackWebappBundle(id string) (*model.Manifest, error) { sourceBundleFilepath := filepath.Join(destinationPath, filepath.Base(bundlePath)) - sourceBundleFileContents, err := ioutil.ReadFile(sourceBundleFilepath) + sourceBundleFileContents, err := os.ReadFile(sourceBundleFilepath) if err != nil { return nil, errors.Wrapf(err, "unable to read webapp bundle: %v", id) } diff --git a/plugin/environment_test.go b/plugin/environment_test.go index 827b822422..389021040c 100644 --- a/plugin/environment_test.go +++ b/plugin/environment_test.go @@ -5,7 +5,6 @@ package plugin import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "testing" @@ -16,7 +15,7 @@ import ( ) func TestAvailablePlugins(t *testing.T) { - dir, err1 := ioutil.TempDir("", "mm-plugin-test") + dir, err1 := os.MkdirTemp("", "mm-plugin-test") require.NoError(t, err1) t.Cleanup(func() { os.RemoveAll(dir) @@ -40,7 +39,7 @@ func TestAvailablePlugins(t *testing.T) { path := filepath.Join(dir, "plugin1", "plugin.json") manifestJSON, jsonErr := json.Marshal(bundle1.Manifest) require.NoError(t, jsonErr) - err = ioutil.WriteFile(path, manifestJSON, 0644) + err = os.WriteFile(path, manifestJSON, 0644) require.NoError(t, err) bundles, err := env.Available() @@ -54,7 +53,7 @@ func TestAvailablePlugins(t *testing.T) { defer os.RemoveAll(filepath.Join(dir, "plugin2")) path := filepath.Join(dir, "plugin2", "manifest.json") - err = ioutil.WriteFile(path, []byte("{}"), 0644) + err = os.WriteFile(path, []byte("{}"), 0644) require.NoError(t, err) bundles, err := env.Available() diff --git a/plugin/health_check_test.go b/plugin/health_check_test.go index 1854af0a9e..f2dc44c766 100644 --- a/plugin/health_check_test.go +++ b/plugin/health_check_test.go @@ -4,7 +4,6 @@ package plugin import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -27,7 +26,7 @@ func TestPluginHealthCheck(t *testing.T) { } func testPluginHealthCheckSuccess(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -48,7 +47,7 @@ func testPluginHealthCheckSuccess(t *testing.T) { } `, 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) bundle := model.BundleInfoForPath(dir) @@ -65,7 +64,7 @@ func testPluginHealthCheckSuccess(t *testing.T) { } func testPluginHealthCheckPanic(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -91,7 +90,7 @@ func testPluginHealthCheckPanic(t *testing.T) { } `, 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) bundle := model.BundleInfoForPath(dir) diff --git a/plugin/interface_generator/main.go b/plugin/interface_generator/main.go index 878b94501b..763868f52e 100644 --- a/plugin/interface_generator/main.go +++ b/plugin/interface_generator/main.go @@ -10,8 +10,8 @@ import ( "go/parser" "go/printer" "go/token" - "io/ioutil" "log" + "os" "os/exec" "path/filepath" "strings" @@ -580,7 +580,7 @@ func generateHooksGlue(info *PluginInterfaceInfo) { 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) } } @@ -613,7 +613,7 @@ func generateProductHooksInterfaces(info *PluginInterfaceInfo) { 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) } } @@ -667,7 +667,7 @@ func generatePluginTimerLayer(info *PluginInterfaceInfo) { 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) } } diff --git a/plugin/plugintest/example_hello_user_test.go b/plugin/plugintest/example_hello_user_test.go index 36b57f65b2..2095b914d3 100644 --- a/plugin/plugintest/example_hello_user_test.go +++ b/plugin/plugintest/example_hello_user_test.go @@ -5,7 +5,7 @@ package plugintest_test import ( "fmt" - "io/ioutil" + io "io" "net/http" "net/http/httptest" "testing" @@ -52,7 +52,7 @@ func Example() { r := httptest.NewRequest("GET", "/", nil) r.Header.Add("Mattermost-User-Id", user.Id) p.ServeHTTP(&plugin.Context{}, w, r) - body, err := ioutil.ReadAll(w.Result().Body) + body, err := io.ReadAll(w.Result().Body) require.NoError(t, err) assert.Equal(t, "Welcome back, billybob!", string(body)) } diff --git a/plugin/supervisor_test.go b/plugin/supervisor_test.go index 81b8d6a912..f5aa7538c0 100644 --- a/plugin/supervisor_test.go +++ b/plugin/supervisor_test.go @@ -4,7 +4,6 @@ package plugin import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -28,11 +27,11 @@ func TestSupervisor(t *testing.T) { } func testSupervisorInvalidExecutablePath(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) 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) log := mlog.CreateConsoleTestLogger(true, mlog.LvlError) @@ -43,11 +42,11 @@ func testSupervisorInvalidExecutablePath(t *testing.T) { } func testSupervisorNonExistentExecutablePath(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) 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) 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. func testSupervisorStartTimeout(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -73,7 +72,7 @@ func testSupervisorStartTimeout(t *testing.T) { } `, 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) log := mlog.CreateConsoleTestLogger(true, mlog.LvlError) diff --git a/scripts/config_generator/main_test.go b/scripts/config_generator/main_test.go index e0afc34d04..8dba358c44 100644 --- a/scripts/config_generator/main_test.go +++ b/scripts/config_generator/main_test.go @@ -5,7 +5,6 @@ package main import ( "encoding/json" - "io/ioutil" "os" "testing" @@ -15,14 +14,14 @@ import ( ) func TestDefaultsGenerator(t *testing.T) { - tmpFile, err := ioutil.TempFile("", "tempconfig") + tmpFile, err := os.CreateTemp("", "tempconfig") defer os.Remove(tmpFile.Name()) require.NoError(t, err) require.NoError(t, generateDefaultConfig(tmpFile)) _ = tmpFile.Close() var config model.Config - b, err := ioutil.ReadFile(tmpFile.Name()) + b, err := os.ReadFile(tmpFile.Name()) require.NoError(t, err) require.NoError(t, json.Unmarshal(b, &config)) require.Equal(t, *config.SqlSettings.AtRestEncryptKey, "") diff --git a/services/docextractor/archive.go b/services/docextractor/archive.go index 96194252cb..1c0e228afb 100644 --- a/services/docextractor/archive.go +++ b/services/docextractor/archive.go @@ -7,7 +7,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -25,7 +24,7 @@ func (ae *archiveExtractor) Match(filename string) bool { } 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 { 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, ",", " ") - data, err2 := ioutil.ReadAll(file) + data, err2 := io.ReadAll(file) if err2 != nil { return err2 } diff --git a/services/docextractor/mmpreview.go b/services/docextractor/mmpreview.go index a46cc3f956..b38e16c5af 100644 --- a/services/docextractor/mmpreview.go +++ b/services/docextractor/mmpreview.go @@ -10,7 +10,6 @@ package docextractor import ( "bytes" "io" - "io/ioutil" "mime/multipart" "net/http" "path" @@ -63,7 +62,7 @@ func (mpe *mmPreviewExtractor) Extract(filename string, file io.ReadSeeker) (str if resp.StatusCode != 200 { 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 { return "", errors.Wrap(err, "unable to read the response from mmpreview") } diff --git a/services/docextractor/pdf.go b/services/docextractor/pdf.go index 43010d4d29..baa7d6685e 100644 --- a/services/docextractor/pdf.go +++ b/services/docextractor/pdf.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path" "strings" @@ -33,7 +32,7 @@ func (pe *pdfExtractor) Extract(filename string, r io.ReadSeeker) (out string, o outErr = errors.New("error extracting pdf text") } }() - f, err := ioutil.TempFile(os.TempDir(), "pdflib") + f, err := os.CreateTemp(os.TempDir(), "pdflib") if err != nil { return "", fmt.Errorf("error creating temporary file: %v", err) } diff --git a/services/docextractor/plain.go b/services/docextractor/plain.go index 4d3b084502..e97bb1d0b8 100644 --- a/services/docextractor/plain.go +++ b/services/docextractor/plain.go @@ -5,7 +5,6 @@ package docextractor import ( "io" - "io/ioutil" "unicode" "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 } diff --git a/services/httpservice/client_test.go b/services/httpservice/client_test.go index a57e5134ad..a274ebf5f3 100644 --- a/services/httpservice/client_test.go +++ b/services/httpservice/client_test.go @@ -6,7 +6,7 @@ package httpservice import ( "context" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -108,7 +108,7 @@ func TestHTTPClientWithProxy(t *testing.T) { require.NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "proxy", string(body)) } diff --git a/services/imageproxy/atmos_camo_test.go b/services/imageproxy/atmos_camo_test.go index 114071b4e6..087724e122 100644 --- a/services/imageproxy/atmos_camo_test.go +++ b/services/imageproxy/atmos_camo_test.go @@ -4,7 +4,7 @@ package imageproxy import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -85,7 +85,7 @@ func TestAtmosCamoBackend_GetImageDirect(t *testing.T) { assert.Equal(t, "image/png", contentType) require.NotNil(t, body) - respBody, _ := ioutil.ReadAll(body) + respBody, _ := io.ReadAll(body) assert.Equal(t, []byte("1111111111"), respBody) } diff --git a/services/imageproxy/local.go b/services/imageproxy/local.go index fc98f6eeb8..950582ebf1 100644 --- a/services/imageproxy/local.go +++ b/services/imageproxy/local.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime" "net" "net/http" @@ -134,7 +133,7 @@ func (backend *LocalBackend) GetImageDirect(imageURL string) (io.ReadCloser, str 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) { @@ -176,7 +175,7 @@ func (backend *LocalBackend) ServeImage(w http.ResponseWriter, req *http.Request if contentType == "" || contentType == "application/octet-stream" || contentType == "binary/octet-stream" { // try to detect content type b := bufio.NewReader(resp.Body) - resp.Body = ioutil.NopCloser(b) + resp.Body = io.NopCloser(b) contentType = peekContentType(b) } if resp.ContentLength != 0 && !contentTypeMatches(imageContentTypes, contentType) { diff --git a/services/imageproxy/local_test.go b/services/imageproxy/local_test.go index da32132546..fe724bca4b 100644 --- a/services/imageproxy/local_test.go +++ b/services/imageproxy/local_test.go @@ -4,7 +4,7 @@ package imageproxy import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "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, "10", resp.Header.Get("Content-Length")) - respBody, _ := ioutil.ReadAll(resp.Body) + respBody, _ := io.ReadAll(resp.Body) 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, "attachment;filename=\"test.svg\"", resp.Header.Get("Content-Disposition")) - _, err = ioutil.ReadAll(resp.Body) + _, err = io.ReadAll(resp.Body) require.NoError(t, err) }) @@ -247,7 +247,7 @@ func TestLocalBackend_GetImageDirect(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "image/png", contentType) - respBody, _ := ioutil.ReadAll(body) + respBody, _ := io.ReadAll(body) assert.Equal(t, []byte("1111111111"), respBody) }) diff --git a/services/remotecluster/sendfile.go b/services/remotecluster/sendfile.go index d94434e2bf..9bf224cbf6 100644 --- a/services/remotecluster/sendfile.go +++ b/services/remotecluster/sendfile.go @@ -7,7 +7,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -117,7 +117,7 @@ func (rcs *Service) sendFileToRemote(timeout time.Duration, task sendFileTask) ( } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/services/remotecluster/sendmsg.go b/services/remotecluster/sendmsg.go index 2b66cdcb6a..78350a3e4a 100644 --- a/services/remotecluster/sendmsg.go +++ b/services/remotecluster/sendmsg.go @@ -8,7 +8,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -163,7 +163,7 @@ func (rcs *Service) sendFrameToRemote(timeout time.Duration, rc *model.RemoteClu return nil, err } defer resp.Body.Close() - body, err = ioutil.ReadAll(resp.Body) + body, err = io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/services/remotecluster/sendprofileImage.go b/services/remotecluster/sendprofileImage.go index ff148a3472..e86adff2ba 100644 --- a/services/remotecluster/sendprofileImage.go +++ b/services/remotecluster/sendprofileImage.go @@ -8,7 +8,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/url" @@ -134,7 +133,7 @@ func (rcs *Service) sendProfileImageToRemote(timeout time.Duration, task sendPro } defer resp.Body.Close() - _, err = ioutil.ReadAll(resp.Body) + _, err = io.ReadAll(resp.Body) if err != nil { return err } diff --git a/services/searchengine/bleveengine/bleve_test.go b/services/searchengine/bleveengine/bleve_test.go index a0ed1e1736..62e30386eb 100644 --- a/services/searchengine/bleveengine/bleve_test.go +++ b/services/searchengine/bleveengine/bleve_test.go @@ -4,7 +4,6 @@ package bleveengine import ( - "io/ioutil" "os" "testing" @@ -37,7 +36,7 @@ func TestBleveEngineTestSuite(t *testing.T) { } func (s *BleveEngineTestSuite) setupIndexes() { - indexDir, err := ioutil.TempDir("", "mmbleve") + indexDir, err := os.MkdirTemp("", "mmbleve") if err != nil { s.Require().FailNow("Cannot setup bleveengine tests: %s", err.Error()) } diff --git a/services/searchengine/bleveengine/indexer/indexing_job_test.go b/services/searchengine/bleveengine/indexer/indexing_job_test.go index 16de60201e..ce6f169306 100644 --- a/services/searchengine/bleveengine/indexer/indexing_job_test.go +++ b/services/searchengine/bleveengine/indexer/indexing_job_test.go @@ -5,7 +5,6 @@ package indexer import ( "errors" - "io/ioutil" "os" "testing" @@ -33,7 +32,7 @@ func TestBleveIndexer(t *testing.T) { 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 - tempDir, err := ioutil.TempDir("", "setupConfigFile") + tempDir, err := os.MkdirTemp("", "setupConfigFile") require.NoError(t, err) t.Cleanup(func() { diff --git a/services/telemetry/telemetry_test.go b/services/telemetry/telemetry_test.go index cd5d0626aa..31ab7656ad 100644 --- a/services/telemetry/telemetry_test.go +++ b/services/telemetry/telemetry_test.go @@ -9,7 +9,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -108,7 +108,7 @@ func makeTelemetryServiceAndReceiver(t *testing.T, cloudLicense bool) (*Telemetr pchan := make(chan testTelemetryPayload, 100) 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) var p testTelemetryPayload @@ -154,8 +154,8 @@ func initializeMocks(cfg *model.Config, cloudLicense bool) (*mocks.ServerIface, serverIfaceMock.On("Config").Return(cfg) serverIfaceMock.On("IsLeader").Return(true) - pluginDir, _ := ioutil.TempDir("", "") - webappPluginDir, _ := ioutil.TempDir("", "") + pluginDir, _ := os.MkdirTemp("", "") + webappPluginDir, _ := os.MkdirTemp("", "") cleanUp := func() { os.RemoveAll(pluginDir) os.RemoveAll(webappPluginDir) diff --git a/services/upgrader/upgrader_linux.go b/services/upgrader/upgrader_linux.go index fa45dd4951..b76c4d2d28 100644 --- a/services/upgrader/upgrader_linux.go +++ b/services/upgrader/upgrader_linux.go @@ -10,7 +10,6 @@ import ( _ "embed" "fmt" "io" - "io/ioutil" "net/http" "os" "os/user" @@ -257,7 +256,7 @@ func download(url string, limit int64) (string, error) { } defer resp.Body.Close() - out, err := ioutil.TempFile("", "*_mattermost.tar.gz") + out, err := os.CreateTemp("", "*_mattermost.tar.gz") if err != nil { return "", err } @@ -310,7 +309,7 @@ func extractBinary(executablePath string, filename string) error { if header.Typeflag == tar.TypeReg && header.Name == "mattermost/bin/mattermost" { permissions := getFilePermissionsOrDefault(executablePath, 0755) - tmpFile, err := ioutil.TempFile(path.Dir(executablePath), "*") + tmpFile, err := os.CreateTemp(path.Dir(executablePath), "*") if err != nil { return err } diff --git a/services/upgrader/upgrader_linux_test.go b/services/upgrader/upgrader_linux_test.go index 43583a243a..73853b3281 100644 --- a/services/upgrader/upgrader_linux_test.go +++ b/services/upgrader/upgrader_linux_test.go @@ -6,7 +6,7 @@ package upgrader import ( "archive/tar" "compress/gzip" - "io/ioutil" + "io" "os" "testing" @@ -75,12 +75,12 @@ func TestGetCurrentVersionTgzURL(t *testing.T) { func TestExtractBinary(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) defer os.Remove(tmpMockTarGz.Name()) tmpMockTarGz.Close() - tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") + tmpMockExecutable, err := os.CreateTemp("", "mock_exe") require.NoError(t, err) defer os.Remove(tmpMockExecutable.Name()) tmpMockExecutable.Close() @@ -89,7 +89,7 @@ func TestExtractBinary(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) defer os.Remove(tmpMockTarGz.Name()) gz := gzip.NewWriter(tmpMockTarGz) @@ -98,7 +98,7 @@ func TestExtractBinary(t *testing.T) { gz.Close() tmpMockTarGz.Close() - tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") + tmpMockExecutable, err := os.CreateTemp("", "mock_exe") require.NoError(t, err) defer os.Remove(tmpMockExecutable.Name()) 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) { - tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") + tmpMockTarGz, err := os.CreateTemp("", "mock_tgz") require.NoError(t, err) defer os.Remove(tmpMockTarGz.Name()) gz := gzip.NewWriter(tmpMockTarGz) @@ -123,7 +123,7 @@ func TestExtractBinary(t *testing.T) { gz.Close() tmpMockTarGz.Close() - tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") + tmpMockExecutable, err := os.CreateTemp("", "mock_exe") require.NoError(t, err) defer os.Remove(tmpMockExecutable.Name()) 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) { - tmpMockTarGz, err := ioutil.TempFile("", "mock_tgz") + tmpMockTarGz, err := os.CreateTemp("", "mock_tgz") require.NoError(t, err) defer os.Remove(tmpMockTarGz.Name()) gz := gzip.NewWriter(tmpMockTarGz) @@ -148,7 +148,7 @@ func TestExtractBinary(t *testing.T) { gz.Close() tmpMockTarGz.Close() - tmpMockExecutable, err := ioutil.TempFile("", "mock_exe") + tmpMockExecutable, err := os.CreateTemp("", "mock_exe") require.NoError(t, err) defer os.Remove(tmpMockExecutable.Name()) tmpMockExecutable.Close() @@ -157,7 +157,7 @@ func TestExtractBinary(t *testing.T) { tmpMockExecutableAfter, err := os.Open(tmpMockExecutable.Name()) require.NoError(t, err) defer tmpMockExecutableAfter.Close() - bytes, err := ioutil.ReadAll(tmpMockExecutableAfter) + bytes, err := io.ReadAll(tmpMockExecutableAfter) require.NoError(t, err) require.Equal(t, []byte("test"), bytes) }) diff --git a/shared/filestore/filesstore_test.go b/shared/filestore/filesstore_test.go index 662b2ef150..ea8dae2435 100644 --- a/shared/filestore/filesstore_test.go +++ b/shared/filestore/filesstore_test.go @@ -6,7 +6,6 @@ package filestore import ( "bytes" "fmt" - "io/ioutil" "math/rand" "os" "testing" @@ -38,7 +37,7 @@ func TestLocalFileBackendTestSuite(t *testing.T) { mlog.InitGlobalLogger(logger) - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) diff --git a/shared/filestore/localstore.go b/shared/filestore/localstore.go index e2d53e4942..1a21305bda 100644 --- a/shared/filestore/localstore.go +++ b/shared/filestore/localstore.go @@ -6,7 +6,6 @@ package filestore import ( "bytes" "io" - "io/ioutil" "os" "path/filepath" "time" @@ -88,7 +87,7 @@ func (b *LocalFileBackend) Reader(path string) (ReadCloseSeeker, 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 { return nil, errors.Wrapf(err, "unable to read file %s", path) } diff --git a/shared/filestore/s3store.go b/shared/filestore/s3store.go index c8738a7b5a..1cdaddd812 100644 --- a/shared/filestore/s3store.go +++ b/shared/filestore/s3store.go @@ -8,7 +8,6 @@ import ( "context" "crypto/tls" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -241,7 +240,7 @@ func (b *S3FileBackend) ReadFile(path string) ([]byte, error) { } defer minioObject.Close() - f, err := ioutil.ReadAll(minioObject) + f, err := io.ReadAll(minioObject) if err != nil { return nil, errors.Wrapf(err, "unable to read file %s", path) } diff --git a/shared/i18n/i18n.go b/shared/i18n/i18n.go index 42108b38b4..5bf0f13bfe 100644 --- a/shared/i18n/i18n.go +++ b/shared/i18n/i18n.go @@ -6,8 +6,8 @@ package i18n import ( "fmt" "html/template" - "io/ioutil" "net/http" + "os" "path/filepath" "reflect" "strings" @@ -59,7 +59,7 @@ func InitTranslations(serverLocale, clientLocale string) error { } func initTranslationsWithDir(dir string) error { - files, _ := ioutil.ReadDir(dir) + files, _ := os.ReadDir(dir) for _, f := range files { if filepath.Ext(f.Name()) == ".json" { filename := f.Name() diff --git a/shared/mail/mail_test.go b/shared/mail/mail_test.go index 207da90442..ff5c0cd71c 100644 --- a/shared/mail/mail_test.go +++ b/shared/mail/mail_test.go @@ -7,7 +7,6 @@ import ( "bytes" "context" "io" - "io/ioutil" "net" "net/mail" "net/smtp" @@ -195,12 +194,12 @@ func TestSendMailUsingConfigAdvanced(t *testing.T) { DeleteMailBox("test2@example.com") // 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) defer os.Remove(file1.Name()) file1.Write([]byte("hello world")) file1.Close() - file2, err := ioutil.TempFile("", "*") + file2, err := os.CreateTemp("", "*") require.NoError(t, err) 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 TestSendMail(t *testing.T) { - dir, err := ioutil.TempDir(".", "mail-test-") + dir, err := os.MkdirTemp(".", "mail-test-") require.NoError(t, err) defer os.RemoveAll(dir) mocm := &mockMailer{} diff --git a/shared/mlog/global_test.go b/shared/mlog/global_test.go index 3fae371f76..d97b3b15a3 100644 --- a/shared/mlog/global_test.go +++ b/shared/mlog/global_test.go @@ -6,7 +6,6 @@ package mlog_test import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -99,7 +98,7 @@ func TestLoggingAfterInitialized(t *testing.T) { t.Run(testCase.description, func(t *testing.T) { var filePath string if testCase.cfg.Type == "file" { - tempDir, err := ioutil.TempDir(os.TempDir(), "TestLoggingAfterInitialized") + tempDir, err := os.MkdirTemp(os.TempDir(), "TestLoggingAfterInitialized") require.NoError(t, err) defer os.Remove(tempDir) @@ -122,7 +121,7 @@ func TestLoggingAfterInitialized(t *testing.T) { logger.Shutdown() if testCase.cfg.Type == "file" { - logs, err := ioutil.ReadFile(filePath) + logs, err := os.ReadFile(filePath) require.NoError(t, err) actual := strings.TrimSpace(string(logs)) diff --git a/shared/mlog/mlog.go b/shared/mlog/mlog.go index 8618b28352..060f3cd302 100644 --- a/shared/mlog/mlog.go +++ b/shared/mlog/mlog.go @@ -10,7 +10,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "os" "strings" @@ -181,12 +180,14 @@ func NewLogger(options ...Option) (*Logger, error) { // Configure provides a new configuration for this logger. // 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 // using the following precedence: -// cfgFile > cfgEscaped +// +// cfgFile > cfgEscaped // // An optional set of factories can be provided which will be called to create any target // types or formatters not built-in. @@ -199,7 +200,7 @@ func (l *Logger) Configure(cfgFile string, cfgEscaped string, factories *Factori // Add config from file if cfgFile != "" { - b, err := ioutil.ReadFile(cfgFile) + b, err := os.ReadFile(cfgFile) if err != nil { return fmt.Errorf("error reading logger config file %s: %w", cfgFile, err) } diff --git a/shared/templates/templates_test.go b/shared/templates/templates_test.go index f847790cfe..4a11207db9 100644 --- a/shared/templates/templates_test.go +++ b/shared/templates/templates_test.go @@ -6,7 +6,6 @@ package templates import ( "bytes" "html/template" - "io/ioutil" "os" "path/filepath" "testing" @@ -17,12 +16,12 @@ import ( ) func TestHTMLTemplateWatcher(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(dir) 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() require.NoError(t, err) @@ -45,7 +44,7 @@ func TestHTMLTemplateWatcher(t *testing.T) { require.NoError(t, err) 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 { text, err := watcher.RenderToString("foo", Data{}) diff --git a/store/layer_generators/main.go b/store/layer_generators/main.go index 28b015ac0c..cfb95abdb8 100644 --- a/store/layer_generators/main.go +++ b/store/layer_generators/main.go @@ -10,7 +10,7 @@ import ( "go/format" "go/parser" "go/token" - "io/ioutil" + "io" "log" "os" "path" @@ -49,7 +49,7 @@ func buildRetryLayer() error { return err } - return ioutil.WriteFile(path.Join("retrylayer/retrylayer.go"), formatedCode, 0644) + return os.WriteFile(path.Join("retrylayer/retrylayer.go"), formatedCode, 0644) } func buildTimerLayer() error { @@ -62,7 +62,7 @@ func buildTimerLayer() error { return err } - return ioutil.WriteFile(path.Join("timerlayer", "timerlayer.go"), formatedCode, 0644) + return os.WriteFile(path.Join("timerlayer", "timerlayer.go"), formatedCode, 0644) } func buildOpenTracingLayer() error { @@ -75,7 +75,7 @@ func buildOpenTracingLayer() error { return err } - return ioutil.WriteFile(path.Join("opentracinglayer", "opentracinglayer.go"), formatedCode, 0644) + return os.WriteFile(path.Join("opentracinglayer", "opentracinglayer.go"), formatedCode, 0644) } type methodParam struct { @@ -155,7 +155,7 @@ func extractStoreMetadata() (*storeMetadata, error) { if err != nil { return nil, fmt.Errorf("unable to open store/store.go file: %w", err) } - src, err := ioutil.ReadAll(file) + src, err := io.ReadAll(file) if err != nil { return nil, err } diff --git a/testlib/helper.go b/testlib/helper.go index c28d998bfd..e4b4021404 100644 --- a/testlib/helper.go +++ b/testlib/helper.go @@ -6,7 +6,6 @@ package testlib import ( "flag" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -164,7 +163,7 @@ func (h *MainHelper) PreloadMigrations() { } else { finalPath = filepath.Join("mattermost-server", relPath, "postgres_migration_warmup.sql") } - buf, err = ioutil.ReadFile(finalPath) + buf, err = os.ReadFile(finalPath) if err != nil { panic(fmt.Errorf("cannot read file: %v", err)) } @@ -175,7 +174,7 @@ func (h *MainHelper) PreloadMigrations() { } else { finalPath = filepath.Join("mattermost-server", relPath, "mysql_migration_warmup.sql") } - buf, err = ioutil.ReadFile(finalPath) + buf, err = os.ReadFile(finalPath) if err != nil { panic(fmt.Errorf("cannot read file: %v", err)) } diff --git a/testlib/resources.go b/testlib/resources.go index 716692a447..15bc08bc5d 100644 --- a/testlib/resources.go +++ b/testlib/resources.go @@ -6,7 +6,6 @@ package testlib import ( "encoding/json" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -116,7 +115,7 @@ func CopyFile(src, dst string) error { func SetupTestResources() (string, error) { testResourcesToSetup := getTestResourcesToSetup() - tempDir, err := ioutil.TempDir("", "testlib") + tempDir, err := os.MkdirTemp("", "testlib") if err != nil { return "", errors.Wrap(err, "failed to create temporary directory") } @@ -195,7 +194,7 @@ func setupConfig(configDir string) error { } configJSON := path.Join(configDir, "config.json") - err = ioutil.WriteFile(configJSON, buf, 0644) + err = os.WriteFile(configJSON, buf, 0644) if err != nil { return errors.Wrapf(err, "failed to write config to %s", configJSON) } diff --git a/utils/archive_test.go b/utils/archive_test.go index 37444311ab..576c4e91f9 100644 --- a/utils/archive_test.go +++ b/utils/archive_test.go @@ -6,7 +6,6 @@ package utils import ( "archive/zip" "errors" - "io/ioutil" "os" "path/filepath" "testing" @@ -90,7 +89,7 @@ func TestUnzipToPath(t *testing.T) { testDir, _ := fileutils.FindDir("tests") require.NotEmpty(t, testDir) - dir, err := ioutil.TempDir("", "unzip") + dir, err := os.MkdirTemp("", "unzip") require.NoError(t, err) defer os.RemoveAll(dir) diff --git a/utils/file.go b/utils/file.go index 175aa9ac21..4338f51508 100644 --- a/utils/file.go +++ b/utils/file.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" ) @@ -85,7 +84,7 @@ func CopyDir(src string, dst string) (err error) { return } - items, err := ioutil.ReadDir(src) + items, err := os.ReadDir(src) if err != nil { return } @@ -100,7 +99,12 @@ func CopyDir(src string, dst string) (err error) { return } } else { - if item.Mode()&os.ModeSymlink != 0 { + info, ierr := item.Info() + if ierr != nil { + continue + } + + if info.Mode()&os.ModeSymlink != 0 { continue } diff --git a/utils/file_test.go b/utils/file_test.go index e74c273cb7..f41c092c42 100644 --- a/utils/file_test.go +++ b/utils/file_test.go @@ -7,7 +7,6 @@ import ( "bytes" "crypto/rand" "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -17,18 +16,18 @@ import ( ) func TestCopyDir(t *testing.T) { - srcDir, err := ioutil.TempDir("", "src") + srcDir, err := os.MkdirTemp("", "src") require.NoError(t, err) defer os.RemoveAll(srcDir) - dstParentDir, err := ioutil.TempDir("", "dstparent") + dstParentDir, err := os.MkdirTemp("", "dstparent") require.NoError(t, err) defer os.RemoveAll(dstParentDir) dstDir := filepath.Join(dstParentDir, "dst") tempFile := "temp.txt" - err = ioutil.WriteFile(filepath.Join(srcDir, tempFile), []byte("test file"), 0655) + err = os.WriteFile(filepath.Join(srcDir, tempFile), []byte("test file"), 0655) require.NoError(t, err) childDir := "child" @@ -36,7 +35,7 @@ func TestCopyDir(t *testing.T) { require.NoError(t, err) childTempFile := "childtemp.txt" - err = ioutil.WriteFile(filepath.Join(srcDir, childDir, childTempFile), []byte("test file"), 0755) + err = os.WriteFile(filepath.Join(srcDir, childDir, childTempFile), []byte("test file"), 0755) require.NoError(t, err) err = CopyDir(srcDir, dstDir) @@ -46,7 +45,7 @@ func TestCopyDir(t *testing.T) { assert.NoError(t, err) assert.Equal(t, uint32(0655), uint32(stat.Mode())) assert.False(t, stat.IsDir()) - data, err := ioutil.ReadFile(filepath.Join(dstDir, tempFile)) + data, err := os.ReadFile(filepath.Join(dstDir, tempFile)) assert.NoError(t, err) assert.Equal(t, "test file", string(data)) @@ -58,7 +57,7 @@ func TestCopyDir(t *testing.T) { assert.NoError(t, err) assert.Equal(t, uint32(0755), uint32(stat.Mode())) assert.False(t, stat.IsDir()) - data, err = ioutil.ReadFile(filepath.Join(dstDir, childDir, childTempFile)) + data, err = os.ReadFile(filepath.Join(dstDir, childDir, childTempFile)) assert.NoError(t, err) assert.Equal(t, "test file", string(data)) diff --git a/utils/fileutils/fileutils_test.go b/utils/fileutils/fileutils_test.go index 93dcfffd10..c223586443 100644 --- a/utils/fileutils/fileutils_test.go +++ b/utils/fileutils/fileutils_test.go @@ -5,7 +5,6 @@ package fileutils import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -26,23 +25,23 @@ func TestFindFile(t *testing.T) { // tmpDir3/ // tmpDir4/ // tmpDir5/ - tmpDir1, err := ioutil.TempDir("", "") + tmpDir1, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(tmpDir1) - tmpDir2, err := ioutil.TempDir(tmpDir1, "") + tmpDir2, err := os.MkdirTemp(tmpDir1, "") require.NoError(t, err) err = os.Mkdir(filepath.Join(tmpDir2, "other.txt"), 0700) require.NoError(t, err) - tmpDir3, err := ioutil.TempDir(tmpDir2, "") + tmpDir3, err := os.MkdirTemp(tmpDir2, "") require.NoError(t, err) - tmpDir4, err := ioutil.TempDir(tmpDir3, "") + tmpDir4, err := os.MkdirTemp(tmpDir3, "") require.NoError(t, err) - tmpDir5, err := ioutil.TempDir(tmpDir4, "") + tmpDir5, err := os.MkdirTemp(tmpDir4, "") require.NoError(t, err) type testCase struct { @@ -56,7 +55,7 @@ func TestFindFile(t *testing.T) { for _, fileName := range []string{"file1.json", "file2.xml", "other.txt"} { filePath := filepath.Join(tmpDir1, fileName) - require.NoError(t, ioutil.WriteFile(filePath, []byte("{}"), 0600)) + require.NoError(t, os.WriteFile(filePath, []byte("{}"), 0600)) // Relative paths end up getting symlinks fully resolved, so use this below as necessary. filePathResolved, err := filepath.EvalSymlinks(filePath) diff --git a/utils/license.go b/utils/license.go index 96a228ba8e..c18b9fad7f 100644 --- a/utils/license.go +++ b/utils/license.go @@ -11,7 +11,7 @@ import ( "encoding/base64" "encoding/json" "encoding/pem" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -141,7 +141,7 @@ func GetLicenseFileFromDisk(fileName string) []byte { } defer file.Close() - licenseBytes, err := ioutil.ReadAll(file) + licenseBytes, err := io.ReadAll(file) if err != nil { mlog.Error("Failed to read license key from disk at", mlog.String("filename", fileName), mlog.Err(err)) return nil diff --git a/utils/license_test.go b/utils/license_test.go index c32faa044f..8c57685444 100644 --- a/utils/license_test.go +++ b/utils/license_test.go @@ -6,7 +6,6 @@ package utils import ( "bytes" "encoding/base64" - "io/ioutil" "os" "testing" @@ -80,10 +79,10 @@ func TestGetLicenseFileFromDisk(t *testing.T) { }) t.Run("not a license file", func(t *testing.T) { - f, err := ioutil.TempFile("", "TestGetLicenseFileFromDisk") + f, err := os.CreateTemp("", "TestGetLicenseFileFromDisk") require.NoError(t, err) defer os.Remove(f.Name()) - ioutil.WriteFile(f.Name(), []byte("not a license"), 0777) + os.WriteFile(f.Name(), []byte("not a license"), 0777) fileBytes := GetLicenseFileFromDisk(f.Name()) require.NotEmpty(t, fileBytes, "should have read the file") diff --git a/utils/subpath.go b/utils/subpath.go index 078527244c..f70b299472 100644 --- a/utils/subpath.go +++ b/utils/subpath.go @@ -7,7 +7,6 @@ import ( "crypto/sha256" "encoding/base64" "fmt" - "io/ioutil" "net/url" "os" "path" @@ -63,7 +62,7 @@ func UpdateAssetsSubpathInDir(subpath, directory string) error { } rootHTMLPath := filepath.Join(staticDir, "root.html") - oldRootHTML, err := ioutil.ReadFile(rootHTMLPath) + oldRootHTML, err := os.ReadFile(rootHTMLPath) if err != nil { return errors.Wrap(err, "failed to open root.html") } @@ -113,19 +112,19 @@ func UpdateAssetsSubpathInDir(subpath, directory string) error { } // Write out the updated root.html. - if err = ioutil.WriteFile(rootHTMLPath, []byte(newRootHTML), 0); err != nil { + if err = os.WriteFile(rootHTMLPath, []byte(newRootHTML), 0); err != nil { return errors.Wrapf(err, "failed to update root.html with subpath %s", subpath) } // Rewrite the manifest.json and *.css references to `/static/*` (or a previously rewritten subpath). err = filepath.Walk(staticDir, func(walkPath string, info os.FileInfo, err error) error { if filepath.Base(walkPath) == "manifest.json" || filepath.Ext(walkPath) == ".css" { - old, err := ioutil.ReadFile(walkPath) + old, err := os.ReadFile(walkPath) if err != nil { return errors.Wrapf(err, "failed to open %s", walkPath) } new := strings.Replace(string(old), pathToReplace, newPath, -1) - if err = ioutil.WriteFile(walkPath, []byte(new), 0); err != nil { + if err = os.WriteFile(walkPath, []byte(new), 0); err != nil { return errors.Wrapf(err, "failed to update %s with subpath %s", walkPath, subpath) } } diff --git a/utils/subpath_test.go b/utils/subpath_test.go index efc9c383e3..85724aabaa 100644 --- a/utils/subpath_test.go +++ b/utils/subpath_test.go @@ -5,7 +5,6 @@ package utils_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -41,7 +40,7 @@ func TestUpdateAssetsSubpathFromConfig(t *testing.T) { }) t.Run("no config", func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "test_update_assets_subpath") + tempDir, err := os.MkdirTemp("", "test_update_assets_subpath") require.NoError(t, err) defer os.RemoveAll(tempDir) os.Chdir(tempDir) @@ -53,7 +52,7 @@ func TestUpdateAssetsSubpathFromConfig(t *testing.T) { func TestUpdateAssetsSubpath(t *testing.T) { t.Run("no client dir", func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "test_update_assets_subpath") + tempDir, err := os.MkdirTemp("", "test_update_assets_subpath") require.NoError(t, err) defer os.RemoveAll(tempDir) os.Chdir(tempDir) @@ -63,7 +62,7 @@ func TestUpdateAssetsSubpath(t *testing.T) { }) t.Run("valid", func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "test_update_assets_subpath") + tempDir, err := os.MkdirTemp("", "test_update_assets_subpath") require.NoError(t, err) defer os.RemoveAll(tempDir) os.Chdir(tempDir) @@ -163,9 +162,9 @@ func TestUpdateAssetsSubpath(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.Description, func(t *testing.T) { - ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "root.html"), []byte(testCase.RootHTML), 0700) - ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "main.css"), []byte(testCase.MainCSS), 0700) - ioutil.WriteFile(filepath.Join(tempDir, model.ClientDir, "manifest.json"), []byte(testCase.ManifestJSON), 0700) + os.WriteFile(filepath.Join(tempDir, model.ClientDir, "root.html"), []byte(testCase.RootHTML), 0700) + os.WriteFile(filepath.Join(tempDir, model.ClientDir, "main.css"), []byte(testCase.MainCSS), 0700) + os.WriteFile(filepath.Join(tempDir, model.ClientDir, "manifest.json"), []byte(testCase.ManifestJSON), 0700) err := utils.UpdateAssetsSubpath(testCase.Subpath) if testCase.ExpectedError != nil { require.Equal(t, testCase.ExpectedError, err) @@ -173,7 +172,7 @@ func TestUpdateAssetsSubpath(t *testing.T) { require.NoError(t, err) } - contents, err := ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "root.html")) + contents, err := os.ReadFile(filepath.Join(tempDir, model.ClientDir, "root.html")) require.NoError(t, err) // Rewrite the expected and contents for simpler diffs when failed. @@ -181,11 +180,11 @@ func TestUpdateAssetsSubpath(t *testing.T) { contentsStr := strings.Replace(string(contents), ">", ">\n", -1) require.Equal(t, expectedRootHTML, contentsStr) - contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "main.css")) + contents, err = os.ReadFile(filepath.Join(tempDir, model.ClientDir, "main.css")) require.NoError(t, err) require.Equal(t, testCase.ExpectedMainCSS, string(contents)) - contents, err = ioutil.ReadFile(filepath.Join(tempDir, model.ClientDir, "manifest.json")) + contents, err = os.ReadFile(filepath.Join(tempDir, model.ClientDir, "manifest.json")) require.NoError(t, err) require.Equal(t, testCase.ExpectedManifestJSON, string(contents)) }) diff --git a/utils/test_files_compiler.go b/utils/test_files_compiler.go index 77ad84ce02..904cb4b6e9 100644 --- a/utils/test_files_compiler.go +++ b/utils/test_files_compiler.go @@ -5,7 +5,6 @@ package utils import ( "bytes" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -16,7 +15,7 @@ import ( ) func CompileGo(t *testing.T, sourceCode, outputPath string) { - dir, err := ioutil.TempDir(".", "") + dir, err := os.MkdirTemp(".", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -25,7 +24,7 @@ func CompileGo(t *testing.T, sourceCode, outputPath string) { // Write out main.go given the source code. main := filepath.Join(dir, "main.go") - err = ioutil.WriteFile(main, []byte(sourceCode), 0600) + err = os.WriteFile(main, []byte(sourceCode), 0600) require.NoError(t, err) _, sourceFile, _, ok := runtime.Caller(0) @@ -45,7 +44,7 @@ func CompileGo(t *testing.T, sourceCode, outputPath string) { } func CompileGoTest(t *testing.T, sourceCode, outputPath string) { - dir, err := ioutil.TempDir(".", "") + dir, err := os.MkdirTemp(".", "") require.NoError(t, err) defer os.RemoveAll(dir) @@ -54,7 +53,7 @@ func CompileGoTest(t *testing.T, sourceCode, outputPath string) { // Write out main.go given the source code. main := filepath.Join(dir, "main_test.go") - err = ioutil.WriteFile(main, []byte(sourceCode), 0600) + err = os.WriteFile(main, []byte(sourceCode), 0600) require.NoError(t, err) _, sourceFile, _, ok := runtime.Caller(0) diff --git a/utils/utils.go b/utils/utils.go index 9fad79e6d7..cf53e19f55 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -4,7 +4,7 @@ package utils import ( - "io/ioutil" + "io" "math" "net" "net/http" @@ -165,7 +165,7 @@ func GetURLWithCache(url string, cache *RequestCache, skip bool) ([]byte, error) return nil, errors.Errorf("Fetching notices failed with status code %d", resp.StatusCode) } - cache.Data, err = ioutil.ReadAll(resp.Body) + cache.Data, err = io.ReadAll(resp.Body) if err != nil { cache.Data = nil return nil, err diff --git a/web/oauth_test.go b/web/oauth_test.go index d8513d1579..1f8c610cc5 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -8,7 +8,6 @@ import ( "encoding/base64" "encoding/json" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -636,7 +635,7 @@ func HTTPGet(url string, httpClient *http.Client, authToken string, followRedire func closeBody(r *http.Response) { if r != nil && r.Body != nil { - ioutil.ReadAll(r.Body) + io.ReadAll(r.Body) r.Body.Close() } } diff --git a/web/web_test.go b/web/web_test.go index d31503560e..d68abdf754 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -5,7 +5,6 @@ package web import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -218,12 +217,12 @@ func TestStaticFilesRequest(t *testing.T) { mainJS := `var x = alert();` mainJSPath := filepath.Join(pluginDir, "main.js") require.NoError(t, err) - err = ioutil.WriteFile(mainJSPath, []byte(mainJS), 0777) + err = os.WriteFile(mainJSPath, []byte(mainJS), 0777) require.NoError(t, err) // Write the plugin.json manifest pluginManifest := `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "webapp": {"bundle_path":"main.js"}, "settings_schema": {"settings": []}}` - ioutil.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(pluginManifest), 0600) + os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(pluginManifest), 0600) // Activate the plugin manifest, activated, reterr := th.App.GetPluginsEnvironment().Activate(pluginID) @@ -272,9 +271,9 @@ func TestPublicFilesRequest(t *testing.T) { th := Setup(t).InitPlugins() defer th.TearDown() - pluginDir, err := ioutil.TempDir("", "") + pluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) - webappPluginDir, err := ioutil.TempDir("", "") + webappPluginDir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(pluginDir) defer os.RemoveAll(webappPluginDir) @@ -306,7 +305,7 @@ func TestPublicFilesRequest(t *testing.T) { // Write the plugin.json manifest pluginManifest := `{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}` - ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600) + os.WriteFile(filepath.Join(pluginDir, pluginID, "plugin.json"), []byte(pluginManifest), 0600) // Write the test public file helloHTML := `Hello from the static files public folder for the com.mattermost.sample plugin!` @@ -314,11 +313,11 @@ func TestPublicFilesRequest(t *testing.T) { os.MkdirAll(htmlFolderPath, os.ModePerm) htmlFilePath := filepath.Join(htmlFolderPath, "hello.html") - htmlFileErr := ioutil.WriteFile(htmlFilePath, []byte(helloHTML), 0600) + htmlFileErr := os.WriteFile(htmlFilePath, []byte(helloHTML), 0600) assert.NoError(t, htmlFileErr) nefariousHTML := `You shouldn't be able to get here!` - htmlFileErr = ioutil.WriteFile(filepath.Join(pluginDir, pluginID, "nefarious-file-access.html"), []byte(nefariousHTML), 0600) + htmlFileErr = os.WriteFile(filepath.Join(pluginDir, pluginID, "nefarious-file-access.html"), []byte(nefariousHTML), 0600) assert.NoError(t, htmlFileErr) manifest, activated, reterr := env.Activate(pluginID)